ORDER BY 절은 질의 결과를 오름차순 또는 내림차순으로 정렬하며, ASC 또는 DESC와 같은 정렬 옵션을 명시하지 않으면 디폴트로 오름차순으로 정렬한다. ORDER BY 절을 지정하지 않으면, 조회되는 레코드의 순서는 질의에 따라 다르다.
SELECT ...
ORDER BY {col_name | expr | position} [ASC | DESC],...]
[ FOR <orderby_for_condition> ] ]
<orderby_for_condition> ::=
ORDERBY_NUM() { BETWEEN int AND int } |
{ { = | =< | < | > | >= } int } |
IN ( int, ...)
--selecting rows sorted by ORDER BY clause
SELECT * FROM sales_tbl ORDER BY dept_no DESC, name ASC;
;xr
=== <Result of SELECT Command in Line 1> ===
dept_no name sales_month sales_amount
==============================================================
501 'Chang' 5 150
501 'Stephan' 4 100
501 'Sue' 6 150
301 'Max' 4 300
201 'George' 1 450
201 'Laura' 2 500
NULL 'Yoka' 4 NULL
7 rows selected.
--sorting reversely and limiting result rows by LIMIT clause
SELECT dept_no AS a1, avg(sales_amount) AS a2 FROM sales_tbl
GROUP BY a1 ORDER BY a2 DESC LIMIT 0,3;
;xr
=== <Result of SELECT Command in Line 1> ===
a1 a2
==========================
201 475
301 300
501 133
3 rows selected.
--sorting reversely and limiting result rows by FOR clause
SELECT dept_no AS a1, avg(sales_amount) AS a2 FROM sales_tbl
GROUP BY a1 ORDER BY a2 DESC FOR ORDERBY_NUM() BETWEEN 1 AND 3;
;xr
=== <Result of SELECT Command in Line 1> ===
a1 a2
==========================
201 475
301 300
501 133
3 rows selected.