SQL Practice Logo

SQLPractice Online

ORDER BY & Sorting: Functions

Module: SQL Fundamentals

SELECT * FROM employees

ORDER BY salary DESC;

SELECT * FROM employees

ORDER BY department ASC, salary DESC;

SELECT

first_name || ' ' || last_name AS full_name,

salary * 12 AS annual_salary

FROM employees

ORDER BY annual_salary DESC;

SELECT * FROM employees

ORDER BY bonus DESC NULLS LAST;

ORDER BY comes at end of query (after WHERE, GROUP BY, HAVING)

ASC is default (ascending), DESC for descending

Can sort by multiple columns: ORDER BY col1, col2

Can use column aliases from SELECT

Can sort by column position: ORDER BY 1, 2

NULL handling: NULLS FIRST or NULLS LAST

Core references in this topic include WHERE, =, IS NULL / IS NOT NULL. Learn what each one does, when to use it, and the execution or engine rules that matter.

WHERE

Filters rows before projection and sorting. It decides which rows continue through the query pipeline.

SELECT ... FROM table WHERE condition;

Most performance issues start with a weak WHERE clause or a missing supporting index.

=

Returns rows where the left and right values are exactly equal.

column = value

Use with exact matches. Do not use = NULL.

IS NULL / IS NOT NULL

Tests whether a value is missing. SQL NULL semantics require dedicated NULL predicates.

manager_id IS NULL

Never use = NULL or != NULL.

ANY / ALL

Compares one value against every or at least one value from a subquery result.

salary > ALL (SELECT salary FROM interns)

GROUP BY

Collects rows into groups so aggregate functions can compute one result per group.

GROUP BY department_id

HAVING

Filters groups after aggregation has been computed.

HAVING COUNT(*) > 5

ORDER BY comes at end of query (after WHERE, GROUP BY, HAVING)