SQL Fundamentals
The Parts of SQL
SQL statements fall into a few families. Knowing which family a statement belongs to tells you how dangerous it is and who should be allowed to run it.
DDL, DML, DQL, DCL and TCL
| Family | Statements | Effect |
|---|---|---|
| DDL — definition | CREATE, ALTER, DROP, TRUNCATE | Changes structure; may take strong locks. |
| DML — manipulation | INSERT, UPDATE, DELETE, MERGE | Changes rows. |
| DQL — query | SELECT | Reads rows. |
| DCL — control | GRANT, REVOKE | Changes privileges. |
| TCL — transactions | BEGIN, COMMIT, ROLLBACK, SAVEPOINT | Groups changes into atomic units. |
Engines differ in details. In PostgreSQL most DDL is transactional and can be rolled back; in Oracle and MySQL, DDL commits the current transaction implicitly. Check your engine's behavior before relying on a rollback.
Standard SQL and Dialects
The ISO SQL standard defines the common core, and every engine adds a dialect on top. Prefer standard forms where they exist — FETCH FIRST n ROWS ONLY, GENERATED AS IDENTITY, CASE, COALESCE — because they survive migrations and are read the same way by every DBA. The examples below use a small shop schema like the one built in Data Modeling.
Defining Structures
DDL is cheap to write and expensive to undo. On a busy production table, the question is never only "is this statement correct?" but also "what does it lock, and for how long?"
Create and Alter Tables
CREATE TABLE product (
id integer PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price numeric(12,2) NOT NULL CHECK (price >= 0)
);
-- Adding a nullable column without a default is a fast, metadata-only change.
ALTER TABLE product ADD COLUMN discontinued_at timestamp;
Some changes rewrite the whole table or block writers while they run: changing a column's type, adding a constraint that must scan existing rows, or, on older engine versions, adding a column with a default. Test DDL against a production-sized copy and read the engine's documentation on lock levels before running it on a live system.
Drop and Truncate with Care
DROP TABLE removes the table and its data; TRUNCATE removes all rows instantly without logging each one. Neither can be filtered with WHERE, and in engines with non-transactional DDL neither can be rolled back. Reserve them for deliberate maintenance, run them from a reviewed script, and make sure a tested backup exists first — see Backup & Recovery.
Changing Data Safely
Most data disasters are an UPDATE or DELETE with a wrong or missing WHERE clause. A few habits make them rare.
Insert, Update and Delete
INSERT INTO product (id, sku, name, price) VALUES
(1, 'KB-01', 'Keyboard', 49.90),
(2, 'MS-01', 'Mouse', 19.90),
(3, 'MN-27', 'Monitor', 229.00);
-- RETURNING shows exactly which rows changed (PostgreSQL, SQLite 3.35+;
-- Oracle uses RETURNING ... INTO inside PL/SQL).
UPDATE product
SET price = price * 1.10
WHERE sku LIKE 'MS-%'
RETURNING id, sku, price;
Rehearse Changes in a Transaction
Run the WHERE clause as a SELECT first, check the row count, then apply the change inside an explicit transaction and confirm the count again before committing:
BEGIN;
SELECT count(*) FROM product WHERE discontinued_at IS NOT NULL; -- expect: 0
DELETE FROM product WHERE discontinued_at IS NOT NULL; -- reports rows deleted
-- If the reported count differs from the SELECT above: ROLLBACK;
COMMIT;
For large changes, work in batches of a few thousand rows so each transaction stays short, locks are released quickly, and replicas do not fall behind.
Insert or Update: Upsert and MERGE
Loading data that may already exist is a common task. PostgreSQL and SQLite provide INSERT ... ON CONFLICT; the SQL standard, Oracle, SQL Server and PostgreSQL 15+ provide MERGE.
-- Insert a new SKU, or update the price if the SKU already exists.
INSERT INTO product (id, sku, name, price)
VALUES (4, 'KB-01', 'Keyboard', 44.90)
ON CONFLICT (sku) DO UPDATE
SET price = excluded.price;
Writing Queries
A SELECT is evaluated logically in this order: FROM and joins, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, then limits. That order explains most surprises — for instance, why a column alias defined in SELECT cannot be used in WHERE.
Joins
-- Every order with its customer; orders without a known customer would be dropped.
SELECT o.id, c.full_name, o.status
FROM customer_order AS o
JOIN customer AS c ON c.id = o.customer_id;
-- Every customer, including those with no orders (order columns are NULL).
SELECT c.full_name, count(o.id) AS orders
FROM customer AS c
LEFT JOIN customer_order AS o ON o.customer_id = c.id
GROUP BY c.full_name;
An INNER JOIN keeps only matching rows; a LEFT JOIN keeps every row of the left table. A frequent bug is a LEFT JOIN followed by a WHERE condition on the right table, which silently turns it back into an inner join — put such conditions in the ON clause instead.
Aggregation and NULL
GROUP BY collapses rows into groups and HAVING filters the groups. SQL uses three-valued logic: a comparison with NULL is neither true nor false but unknown, so WHERE price = NULL matches nothing. Use IS NULL, and remember that count(*) counts rows while count(column) skips nulls.
CTEs and Window Functions
Common table expressions (WITH) name intermediate results so complex queries read top to bottom. Window functions compute over related rows without collapsing them — ideal for rankings, running totals and “latest row per group” reports:
-- The most recent order of each customer.
WITH ranked AS (
SELECT o.*,
row_number() OVER (PARTITION BY customer_id
ORDER BY ordered_at DESC) AS rn
FROM customer_order AS o
)
SELECT customer_id, id AS last_order_id, ordered_at
FROM ranked
WHERE rn = 1;
SQL for Administration
Administrators also query the database about itself. Every engine exposes its metadata as tables and views you can query with ordinary SQL.
Query the Catalog
The standard information_schema works across PostgreSQL, MySQL and SQL Server; engines also have richer native catalogs (pg_catalog in PostgreSQL, the DBA_/ALL_/USER_ views in Oracle).
-- Columns of a table, in order, with types and nullability (information_schema).
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'product'
ORDER BY ordinal_position;
Keep SQL Reviewable
Store operational SQL in version control, not in a personal scratch file. Format it consistently, qualify columns with table aliases in multi-table queries, avoid SELECT * in application code (a new column can break consumers), and never build SQL by concatenating user input — use parameters, as explained in Security & Access Control.
Practice Lab
Any SQL engine works for this lab; SQLite needs no installation and runs the portable examples above unchanged.
Answer Business Questions
- Create the
customer,product,customer_orderandorder_linetables and load a few dozen rows. - Write queries for: revenue per product, customers with no orders, and each customer's most recent order.
- Rewrite one query using a CTE and compare readability with the nested version.
Rehearse a Risky Change
- Write a price-increase
UPDATEfor one product category. - Run its
WHEREas aSELECT, then the update inside a transaction withRETURNING. - Roll back deliberately, confirm nothing changed, then run it for real and commit.