SQL Strategy - A site to master SQL while executing it on the Web
Home >> SQL Strategy - Sort (ORDER BY)

Sort(ORDER BY)

Learn how to sort data conditionally extracted with a SELECT statement.

1. How to write sort (ORDER BY)

--ENAME (employee name), JOB and SAL (salary) with 'SALESMAN' as JOB, sorted by SAL
SELECTENAME,JOB,SAL
FROMEMP
WHEREJOB = 'SALESMAN'
ORDER BYSAL
■How to sort

To sort records, use ORDER BY, where ORDER BY is followed by the column name to be used as the sort key. To use multiple sort keys, use a comma-separated list of column names, such as ORDER BY SAL,DEPTNO.

■ORDER BY position

ORDER BY is written after the WHERE condition; if no WHERE condition is specified, the ORDER BY clause is written after the FROM clause.

■sort order

Normally sorted in ascending order, but can be sorted in descending order by adding the DESC keyword, as in ORDER BY SAL DESC. To explicitly sort in ascending order, add the ASC keyword.

ASCascending-order
DESCdescending-order

■Practice

Now for the Practice, I will give you two questions.


2. past question of the sort

Basic Information Technology Engineer AM Spring 2003 Q69
Which SQL statement is used to obtain Table B from Table A?
Table A
employee codeNameDepartment Codesalary
10010Ito Sachiko101200,000
10020Saito Eiji201300,000
10030Suzuki Yuichi101250,000
10040Honda Kazu102350,000
10050Yamada Goro102300,000
10060Wakayama Mari201250,000

Table B
Department Codeemployee codeName
10110010Ito Sachiko
10110030Suzuki Yuichi
10210040Honda Kazu
10210050Yamada Goro
20110020Saito Eiji
20110060Wakayama Mari

ASELECT * FROM TableA WHERE Department Code <> NULL
BSELECT Department Code,employee code,Name FROM TableA
CSELECT Department Code,employee code,Name FROM TableA GROUP BY Department Code
DSELECT Department Code,employee code,Name FROM TableA ORDER BY Department Code
Answer

 D

Explanation

1. Check the items shown in the table after SELECT.
 First, A is removed from the candidate list because it makes all items Table.

2. focus on the item being sorted.
 Since it is sorted by Department Code, D in ORDER BY Department Code is Answer.

This completes [Sort (ORDER BY)].