在SQL中,可以使用ORDER BY子句對查詢結果進行排序。下面是一些常用的技巧:
按單個列排序: SELECT * FROM table_name ORDER BY column_name ASC/DESC;
按多個列排序: SELECT * FROM table_name ORDER BY column1 ASC/DESC, column2 ASC/DESC;
按列的位置排序: SELECT * FROM table_name ORDER BY 2 ASC/DESC;
按多列不同排序方式: SELECT * FROM table_name ORDER BY column1 ASC, column2 DESC;
按字符串排序: SELECT * FROM table_name ORDER BY column_name COLLATE “NOCASE”;
按NULL值排序: SELECT * FROM table_name ORDER BY column_name NULLS FIRST/LAST;
按條件排序: SELECT * FROM table_name ORDER BY CASE WHEN condition1 THEN 1 WHEN condition2 THEN 2 ELSE 3 END;
按表達式結果排序: SELECT * FROM table_name ORDER BY expression_name;