What About More Complex Expressions?

What if you want to sort by an expression in the SELECT list—something more complicated than a simple column name? SQL allows you to sort by

  • The expression's position in the SELECT list (represented with a number)

  • The expression's display label (also called alias or heading—see “Display Label Conventions” in Chapter 4)

Some systems also allow you to use the full expression in the ORDER BY clause.

Here's an example of a query with a SELECT list expression (price * ytd_sales) on which you might want to sort:

SQL
select title_id, pub_id, price * ytd_sales, price from titles where type in ('business', 'psychology') title_id pub_id titles.price*titles.ytd_sales price ======== ====== ============================= ...

Get Practical SQL Handbook, The: Using SQL Variants, Fourth 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.