Lesson 1: Read data with SELECT
SQL describes the rows you want from a relational database. The examples use a table named orders with columns order_id, customer_id, order_date, and total. Put each clause on its own line so queries are easy to inspect.
Start by returning every column for a small number of rows, then select only the fields the task needs.
SELECT order_id, customer_id, total
FROM orders
ORDER BY order_date DESC
LIMIT 10;Query clause reference
| Clause | Purpose | Example |
|---|---|---|
| SELECT | Choose columns or expressions returned. | SELECT order_id, total |
| FROM | Choose the source table or view. | FROM orders |
| AS | Give a column or expression a readable alias. | total * 1.1 AS total_with_tax |
| DISTINCT | Return distinct selected rows. | SELECT DISTINCT customer_id FROM orders |
| ORDER BY | Sort result rows; ASC is default, DESC is descending. | ORDER BY order_date DESC |
| LIMIT | Cap result rows in PostgreSQL and several other systems. | LIMIT 10 |
| OFFSET | Skip rows; use stable ordering for paging. | LIMIT 20 OFFSET 40 |
| FETCH FIRST | Standard-style row limit supported by PostgreSQL. | FETCH FIRST 10 ROWS ONLY |
| Comments | Document intent without changing the result. | -- latest ten orders |
Copy a starter query: SELECT order_id, total FROM orders ORDER BY order_date DESC LIMIT 10;
Logical query order
Although SELECT appears first, a useful mental model is FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, then LIMIT. This explains why a SELECT alias is not always available in WHERE.
Progress stays in this browser.