SELECT Basics
A query states which table (FROM) and which columns (SELECT) to read. You add WHERE to filter rows and ORDER BY to set the order. The examples use the customers and orders tables from the common lab environment.
Click Run on an example to execute it in the sandbox of the DB selected above. Open it with Edit, change it, and run it again with Ctrl+Enter.
Picking columns
List the columns to read after SELECT, separated by commas. * means all columns.
Picking columns
SELECT cust_id, cust_nm, grade, region
FROM customers
WHERE cust_id <= 10
ORDER BY cust_id
Filtering rows: WHERE
Only rows for which the WHERE condition is true stay in the result. Conditions are joined with AND and OR. Strings go in single quotes.
VIP customers in Seoul
SELECT cust_id, cust_nm, region, join_dt
FROM customers
WHERE grade = 'VIP'
AND region = 'SEOUL'
ORDER BY cust_id
Sorting and taking the first few rows
Without ORDER BY, the order of the result is undefined. The syntax for fetching only the first few rows differs by DB. Switch the DB above to see that DB's example.
| DB | Syntax |
|---|---|
| Oracle 12c+, PostgreSQL | FETCH FIRST n ROWS ONLY |
| PostgreSQL | LIMIT n |
| SQL Server | SELECT TOP (n) |
Oracle, PostgreSQL · 5 latest orders
SELECT ord_id, cust_id, ord_dt, amt
FROM orders
WHERE cust_id = 1
ORDER BY ord_dt DESC
FETCH FIRST 5 ROWS ONLY
SQL Server · 5 latest orders
SELECT TOP (5) ord_id, cust_id, ord_dt, amt
FROM orders
WHERE cust_id = 1
ORDER BY ord_dt DESC
Statements that do not run
NOTE The sandbox runs only queries (
SELECT,WITH … SELECT). Statements that change data are shown as code only, without a run button.
UPDATE customers SET grade = 'GOLD' WHERE cust_id = 1;