SQL SELECT Selection with sorted Results

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

SELECT * FROM Employees ORDER BY LName

This statement will return all the columns from the table Employees.

IdFNameLNamePhoneNumber
2JohnJohnson2468101214
1JamesSmith1234567890
3MichaelWilliams1357911131
SELECT * FROM Employees ORDER BY LName DESC

Or

 SELECT * FROM Employees ORDER BY LName ASC

This statement changes the sorting direction.

One may also specify multiple sorting columns. For example:

SELECT * FROM Employees ORDER BY LName ASC, FName ASC

This example will sort the results first by LName and then, for records that have the same LName, sort by FName. This will give you a result similar to what you would find in a telephone book.

In order to save retyping the column name in the ORDER BY clause, it is possible to use instead the column's number. Note that column numbers start from 1.

SELECT Id, FName, LName, PhoneNumber FROM Employees ORDER BY 3

You may also embed a CASE statement in the ORDER BY clause.

SELECT Id, FName, LName, PhoneNumber FROM Employees ORDER BY CASE WHEN LName='Jones` THEN 0 ELSE 1 END ASC

This will sort your results to have all records with the LName of "Jones" at the top.



Got any SQL Question?