Sorting and Aliasing
Sorting and aliasing are two essential SQL techniques that help you control the presentation of query results and make your queries more readable and efficient.
Sorting (ORDER BY)
The ORDER BY
clause is used to sort the rows returned by a query in ascending or descending order.
Basic Syntax:
SELECT column1, column2
FROM table_name
ORDER BY column1 [ASC|DESC];
ASC
sorts in ascending order (default).DESC
sorts in descending order.
Example:
SELECT first_name, last_name, hire_date
FROM employees
ORDER BY hire_date DESC;
Key Points:
- You can sort by one or multiple columns.
- Sorting affects the order of results but not the underlying table.
- Numeric positions can be used in
ORDER BY
(ORDER BY 2 DESC
means order by the second column in theSELECT
).
Example with Multiple Columns:
SELECT first_name, last_name, department
FROM employees
ORDER BY department ASC, last_name ASC;
Aliasing (AS)
Aliases allow you to give a column or table a temporary name for the duration of a query. This makes results clearer and queries easier to read.
Column Aliases
Column aliases rename output columns.
Basic Syntax:
SELECT column_name AS alias_name
FROM table_name;
Example:
SELECT first_name AS "First Name", last_name AS "Last Name"
FROM employees;
- Quotes are required if the alias contains spaces or special characters.
- The
AS
keyword is optional in most databases:SELECT first_name "First Name"
also works.
Table Aliases
Table aliases give a temporary name to a table — especially useful when using joins or subqueries.
Basic Syntax:
SELECT e.first_name, d.name
FROM employees AS e
JOIN departments AS d
ON e.department_id = d.id;
- Here
e
andd
are table aliases. - Makes complex queries shorter and clearer.
Why Use Aliases?
- Simplify long or complex table names.
- Make output column names clearer and user-friendly.
- Required for derived columns or calculated fields.
Example with Expression Alias:
SELECT salary * 12 AS annual_salary
FROM employees;
Summary
Feature | Purpose | Example |
---|---|---|
ORDER BY | Sort rows | ORDER BY last_name DESC |
Column Alias | Rename output columns | SELECT salary * 12 AS annual_salary |
Table Alias | Shorten table names | FROM employees AS e |
Sorting and aliasing help you write cleaner, more understandable queries and produce results in the exact format you need.