Member-only story

Sorting data in SQL refers to the process of arranging the rows of a result set in a specified order based on the values in one or more columns. The ORDER BY
clause in SQL is used to perform this operation. Sorting allows you to organize the data in a meaningful way, making it easier to analyze and interpret.
1. Ascending Order (default):
SELECT * FROM table_name ORDER BY column_name;
2. Descending Order:
SELECT * FROM table_name ORDER BY column_name DESC;
3. Sorting by Multiple Columns:
SELECT * FROM table_name ORDER BY column1, column2;
4. Sorting by Multiple Columns with Different Orders:
SELECT * FROM table_name ORDER BY column1 ASC, column2 DESC;
5. Sorting by Column Position:
SELECT * FROM table_name ORDER BY 2;
6. Sorting by Expression:
SELECT * FROM table_name ORDER BY column1 + column2;
7. Sorting by Case:
SELECT * FROM table_name ORDER BY CASE WHEN condition THEN column1 ELSE column2 END;
8. Sorting NULL Values First:
SELECT * FROM table_name ORDER BY column_name IS NULL, column_name;
9. Sorting NULL Values Last:
SELECT * FROM table_name ORDER BY column_name IS NULL DESC, column_name;
10. Sorting by String Length:
SELECT * FROM table_name ORDER BY LEN(column_name);
11. Sorting by Random Order:
SELECT * FROM table_name ORDER BY NEWID();
12. Sorting by Date:
SELECT * FROM table_name ORDER BY date_column;
13. Sorting by Weekday:
SELECT * FROM table_name ORDER BY DATEPART(dw, date_column);