I have a problem that ORDER BY is not working the way I want.
My code:
SELECT
LastName + ' ' + FirstName AS [Full name],
TitleOfCourtesy AS titleOfCourtesy,
CASE
WHEN TitleOfCourtesy IN ('Ms.', 'Mrs.')
THEN 'Female'
WHEN TitleOfCourtesy = 'Mr.'
THEN 'Male'
END AS Sex
FROM
Employees
WHERE
TitleOfCourtesy IN ('Mrs.','Ms.','Mr.')
-- ORDER BY Sex DESC;
This code returns this result set:
When I add ORDER BY(uncomment last line), it returns:
I think result should be like this (this is what I want):
Here is my Employees table:
I don't understand why Callahan Laura and Dodsworth Anne is moving up in img 2. What happened? Did I misunderstand how ORDER BY works? Any help is appreciated!




ORDER BY Sex DESC, FullName ASCif it is important to you to get that ordering. If you have ties for the value you are ordering by SQL Server is free to return them in any order (as it also is for queries with noORDER BYso your first query has no guaranteed ordering either)ORDER BYclause that guarantees that. The ordering of your first resultset isn't some "natural" ordering. It is just whatever order the execution plan happened to deliver the rows inORDER BY Sex DESC, EmployeeId ASCthenORDER BYall such default behaviour goes out of the window. In fact what SQL Server appears to be doing here is to scan the table in physical clustered order. Any values that are out of place according to the specifiedORDER BYare being extracted and added at the end of the batch of equal ranks to which they belong. This is entirely legitimate behaviour within the rules of the SQL standard. It may not be what you wanted, but it is not wrong.