Share via

Comparing the speed

BenTam-3003 686 Reputation points
2022-03-07T14:45:02.727+00:00

Dear All,

I have one table "Absence" with the following field names: "StudentID (int), SubjectID (nvarchar(10)), CourseID (nvarchar(20)), Absence (int)" A primary index on three fields "StudentID, SubjectID, CourseID". Please note that StudentID is an INTEGER field and both SubjectID and CourseID are NVARCHAR fields.

Comparing the speed, which is faster?

  1. Select top 1 * from Absence order by StudentID, SubjectID, CourseID
  2. Select top 1 * from Absence order by StudentID, CourseID, SubjectID
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


Answer accepted by question author

Tom Phillips 17,786 Reputation points
2022-03-07T15:38:17.257+00:00

There are many variables in the query plan which might affect how "fast" a query runs. You can test it yourself by using the "actual execution" button in SSMS.

In your example, you said "primary index" I assume you mean clustered index. If so, in theory 1 should be faster because it will not need a sort on StudentID, CourseID, SubjectID to find the top 1.

However, unless you have billions of rows and many duplicate CourseID, SubjectID, in reality, you are not going to see any difference with a table row allocation that small. Because, SQL Server reads 8K pages, not a row.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Naomi Nosonovsky 8,906 Reputation points
    2022-03-07T15:33:23.15+00:00

    In theory the first one should be faster, but you may want to test performance.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.