Skip to Content
SQL Cookbook, 2nd Edition
book

SQL Cookbook, 2nd Edition

by Anthony Molinaro, Robert de Graaf
November 2020
Intermediate to advanced
567 pages
11h 48m
English
O'Reilly Media, Inc.
Book available
Content preview from SQL Cookbook, 2nd Edition

Chapter 2. Sorting Query Results

This chapter focuses on customizing how your query results look. By understanding how to control how your result set is organized, you can provide more readable and meaningful data.

2.1 Returning Query Results in a Specified Order

Problem

You want to display the names, jobs, and salaries of employees in department 10 in order based on their salary (from lowest to highest). You want to return the following result set:

ENAME       JOB               SAL
----------  ---------  ----------
MILLER      CLERK            1300
CLARK       MANAGER          2450
KING        PRESIDENT        5000

Solution

Use the ORDER BY clause:

1 select ename,job,sal
2   from emp
3  where deptno = 10
4  order by sal asc

Discussion

The ORDER BY clause allows you to order the rows of your result set. The solution sorts the rows based on SAL in ascending order. By default, ORDER BY will sort in ascending order, and the ASC clause is therefore optional. Alternatively, specify DESC to sort in descending order:

select ename,job,sal
  from emp
 where deptno = 10
 order by sal desc

ENAME       JOB               SAL
----------  ---------  ----------
KING        PRESIDENT        5000
CLARK       MANAGER          2450
MILLER      CLERK            1300

You need not specify the name of the column on which to sort. You can instead specify a number representing the column. The number starts at 1 and matches the items in the SELECT list from left to right. For example:

select ename,job,sal
  from emp
 where deptno = 10
 order by 3 desc ENAME JOB SAL ---------- --------- ---------- KING PRESIDENT 5000 CLARK MANAGER 2450 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

SQL Cookbook

SQL Cookbook

Anthony Molinaro
MySQL Cookbook, 4th Edition

MySQL Cookbook, 4th Edition

Sveta Smirnova, Alkin Tezuysal
Head First SQL

Head First SQL

Lynn Beighley

Publisher Resources

ISBN: 9781492077435Errata Page