Chapter 12. SELECT Statement: The ORDER BY Clause

Introduction

What is actually the sequence in which the rows in the result of a SELECT statement are presented? If the SELECT statement has no ORDER BY clause, the sequence is unpredictable. When working through the examples or exercises, you might have found once or twice that the sequence of the rows in your result is different from the one in the book. The addition of an ORDER BY clause at the end of a SELECT statement is the only guarantee that the rows in the end result will be sorted in a certain way.

<order by clause> ::= ORDER BY <sorting> [ { , <sorting> }... ] <sorting> ::= <scalar expression> [ <sort direction> ] | <sequence number> [<sort direction> ] | <column heading> [ <sort direction> ...

Get Introduction to SQL: Mastering the Relational Database Language, Fourth Edition/20th Anniversary Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.