SQL is a declarative language: describe the information you want, and the database engine determines how to retrieve it. The real skill is not memorizing keywords. It is knowing what a row represents, how tables relate, how expressions transform data, and how to prove that the resulting query answers the intended question.
This guide uses a consistent fictional retail business. The exercises gradually progress from retrieving a customer to building analytical datasets, diagnosing bad joins, and designing a data pipeline. Every example using the practice dataset is small enough to inspect manually. SQL examples with an Output (SQLite practice data) table have been executed against the supplied setup; other dialect-specific examples have explicitly illustrative expected behavior. Examples that change data use disposable tables, transactions, or a fresh database. Numerical examples are synthetic, not measured production benchmarks.
Dialect convention. Most core queries use portable SQL and are runnable in SQLite 3.46 (or a recent SQLite release). SQL Server (T-SQL), PostgreSQL and MySQL alternatives are labeled. A client such as SQL Server Management Studio (SSMS), MySQL Workbench, pgAdmin, or VS Code with a database extension is a tool for communicating with the database, not the engine itself. Use a local practice environment, not a production database. This guide is about SQL, not the complete administration of any one database system.
Road map
| Part |
What you will learn |
| I |
SQL foundations, data types, queries, filters, sorting |
| II |
Database engineering, tables, keys, modifications, transactions, ER design |
| III |
Aggregation, joins, set operators, subqueries, CTEs |
| IV |
Text, numeric, date, NULL, type conversion and cleaning |
| V |
Window functions, ranking, time-series analysis and intermediate datasets |
| VI |
Procedures, triggers, indexes, plans and partitioning |
| VII |
ETL, warehousing and practical projects |
The practice database
A customer can place many orders; each order can contain multiple products. Employees belong to departments and may have a manager. We deliberately include a customer with no orders, an order without a customer, missing emails, a product with no sales, tied employee salaries and an empty department to expose important edge cases.
customers (1) ───< orders (N) ───< order_items (N) >─── (1) products
PK order_id PK (order_id, product_id)
departments (1) ───< employees (N)
employee.manager_id ──> employee.employee_id
Run the following once in a new SQLite database (for example using the sqlite3 shell or a SQLite client). The PRAGMA command enables foreign-key enforcement in that connection. SQLite accepts the declared types here but has its own dynamic typing/affinity rules; explicit NOT NULL is used on the key columns because an ordinary SQLite INT PRIMARY KEY or composite key can otherwise permit NULL; production MySQL, PostgreSQL and SQL Server enforce types differently. The IDs are assigned explicitly to keep the examples deterministic. Prices represent fictional monetary units; order amount and line totals match in this dataset. In real schemas, taxes, shipping, discounts and rounding may make them differ.
PRAGMA foreign_keys = ON;
CREATE TABLE departments (department_id INT NOT NULL PRIMARY KEY, department_name VARCHAR(30) NOT NULL UNIQUE);
CREATE TABLE employees (
employee_id INT NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL,
department_id INT REFERENCES departments(department_id),
manager_id INT REFERENCES employees(employee_id),
salary DECIMAL(10,2) CHECK (salary >= 0), hire_date DATE
);
CREATE TABLE customers (
customer_id INT NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL,
country VARCHAR(30), email VARCHAR(100), points INT DEFAULT 0
);
CREATE TABLE products (
product_id INT NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL,
category VARCHAR(30), price DECIMAL(8,2) CHECK (price >= 0)
);
CREATE TABLE orders (
order_id INT NOT NULL PRIMARY KEY, customer_id INT REFERENCES customers(customer_id),
order_date DATE NOT NULL, status VARCHAR(20) NOT NULL,
amount DECIMAL(10,2) CHECK (amount >= 0)
);
CREATE TABLE order_items (
order_id INT NOT NULL REFERENCES orders(order_id), product_id INT NOT NULL REFERENCES products(product_id),
quantity INT NOT NULL CHECK (quantity > 0), unit_price DECIMAL(8,2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'HR'),(4,'Finance');
INSERT INTO employees VALUES (1,'Alice',1,NULL,90000,'2022-01-10');
INSERT INTO employees VALUES (2,'Bob',1,1,70000,'2023-04-02'),(3,'Cara',1,1,70000,'2024-03-05'),(4,'Dan',2,NULL,60000,'2022-08-01');
INSERT INTO employees VALUES (5,'Eva',2,4,50000,'2024-01-15'),(6,'Finn',3,NULL,55000,'2023-06-10'),(7,'Gina',NULL,1,NULL,'2025-01-05');
INSERT INTO customers VALUES
(1,'Ada','USA','ada@example.com',1200), (2,'Ben','UK',NULL,400),
(3,'Cleo','USA','cleo@example.com',800), (4,'Dina','Germany','',0),
(5,'Eli',NULL,'eli@example.com',NULL);
INSERT INTO products VALUES (10,'Laptop','Tech',100),(11,'Mouse','Tech',20),(12,'Notebook','Office',10),(13,'Pen','Office',5),(14,'Monitor','Tech',150);
INSERT INTO orders VALUES
(101,1,'2025-01-10','Completed',120), (102,2,'2025-01-20','Completed',40),
(103,1,'2025-02-05','Completed',80), (104,3,'2025-02-11','Cancelled',50),
(105,3,'2025-03-01','Completed',150), (106,2,'2025-03-15','Completed',60),
(107,NULL,'2025-03-20','Completed',20), (108,1,'2025-04-01','Pending',100);
INSERT INTO order_items VALUES
(101,10,1,100),(101,11,1,20),(102,11,2,20),(103,11,4,20),
(104,12,5,10),(105,10,1,100),(105,12,5,10),(106,11,3,20),
(107,11,1,20),(108,10,1,100);
The baseline tables are shown below. Restore this setup in a fresh database if you change any baseline records.
customers
| customer_id |
name |
country |
email |
points |
| 1 |
Ada |
USA |
ada@example.com |
1200 |
| 2 |
Ben |
UK |
NULL |
400 |
| 3 |
Cleo |
USA |
cleo@example.com |
800 |
| 4 |
Dina |
Germany |
|
0 |
| 5 |
Eli |
NULL |
eli@example.com |
NULL |
orders
| order_id |
customer_id |
order_date |
status |
amount |
| 101 |
1 |
2025-01-10 |
Completed |
120 |
| 102 |
2 |
2025-01-20 |
Completed |
40 |
| 103 |
1 |
2025-02-05 |
Completed |
80 |
| 104 |
3 |
2025-02-11 |
Cancelled |
50 |
| 105 |
3 |
2025-03-01 |
Completed |
150 |
| 106 |
2 |
2025-03-15 |
Completed |
60 |
| 107 |
NULL |
2025-03-20 |
Completed |
20 |
| 108 |
1 |
2025-04-01 |
Pending |
100 |
products
| product_id |
name |
category |
price |
| 10 |
Laptop |
Tech |
100 |
| 11 |
Mouse |
Tech |
20 |
| 12 |
Notebook |
Office |
10 |
| 13 |
Pen |
Office |
5 |
| 14 |
Monitor |
Tech |
150 |
employees
| employee_id |
name |
department_id |
manager_id |
salary |
hire_date |
| 1 |
Alice |
1 |
NULL |
90000 |
2022-01-10 |
| 2 |
Bob |
1 |
1 |
70000 |
2023-04-02 |
| 3 |
Cara |
1 |
1 |
70000 |
2024-03-05 |
| 4 |
Dan |
2 |
NULL |
60000 |
2022-08-01 |
| 5 |
Eva |
2 |
4 |
50000 |
2024-01-15 |
| 6 |
Finn |
3 |
NULL |
55000 |
2023-06-10 |
| 7 |
Gina |
NULL |
1 |
NULL |
2025-01-05 |
departments
| department_id |
department_name |
| 1 |
Engineering |
| 2 |
Sales |
| 3 |
HR |
| 4 |
Finance |
order_items
| order_id |
product_id |
quantity |
unit_price |
| 101 |
10 |
1 |
100 |
| 101 |
11 |
1 |
20 |
| 102 |
11 |
2 |
20 |
| 103 |
11 |
4 |
20 |
| 104 |
12 |
5 |
10 |
| 105 |
10 |
1 |
100 |
| 105 |
12 |
5 |
10 |
| 106 |
11 |
3 |
20 |
| 107 |
11 |
1 |
20 |
| 108 |
10 |
1 |
100 |
Part I — SQL Foundations
Start by understanding the database, the shape of a table, and the clauses that select the information you need.
1. Introduction to SQL and databases
A database stores related data; a DBMS (database management system) creates, manages, protects and retrieves it. An RDBMS organizes data using relational tables and constraints. SQL is the language used to interact with these systems. A database is not the same as a database server, a DBMS, or a client application.
Application / dashboard / analyst
↓ SQL request
DBMS (parse → plan → execute)
↓ ↑
Stored database
↓ results
Client
Relational systems such as PostgreSQL, MySQL, SQLite and SQL Server share the relational model but implement different SQL dialects. Nonrelational families include document databases, key-value stores, graph databases and wide-column stores. Column-oriented analytical relational databases also exist; column storage is not synonymous with NoSQL. Relational tables resemble spreadsheets, but relationships, constraints, concurrency and query processing distinguish a DBMS from a simple file.
| Command family |
Job |
Typical statements |
| DQL |
Retrieve data |
SELECT |
| DDL |
Define objects |
CREATE, ALTER, DROP |
| DML |
Change records |
INSERT, UPDATE, DELETE |
| DCL |
Control access |
GRANT, REVOKE (conceptual here) |
| TCL |
Control transactions |
COMMIT, ROLLBACK |
CRUD means create, read, update and delete records: INSERT, SELECT, UPDATE, DELETE. It is different from creating or dropping a table.
Setup in other engines. Install the database server and appropriate client, connect to your local instance, create/select a practice database, and run an initialization script. MySQL uses USE database_name; SQL Server supports USE as well; PostgreSQL normally selects the database when connecting. SQL Server can also restore .bak files using its restore workflow. A local SQLite database is a file and does not require a separate server. Use strong credentials and keep them out of source control.
First query
Output (SQLite practice data):
How it works. The expression is evaluated even without a FROM clause.
Practical use. Check that the query editor is connected and can execute SQL.
Common mistakes. Confusing a client with the server; assuming every SQL dialect has identical syntax; running experimental DDL or DML against production.
Exercise. Retrieve the names of all customers.
Solution
SELECT name FROM customers ORDER BY customer_id;
Output (SQLite practice data):
| name |
| Ada |
| Ben |
| Cleo |
| Dina |
| Eli |
How it works. SELECT requests a column from the table, not a modification.
2. Database architecture and data types
A row is a record, a column is an attribute, and a cell is a value. A primary key identifies a row. A table has a schema: column names, types, constraints, and relationships. In SQL Server and PostgreSQL, a database can contain multiple named schemas; MySQL commonly treats schema and database as synonyms. A name such as Sales.Orders in SQL Server identifies an object within a schema.
| Type family |
Common types |
Typical use |
| Integer |
INT, BIGINT |
IDs, counts |
| Exact numeric |
DECIMAL(p,s), NUMERIC(p,s) |
Monetary amounts; p total digits, s fractional digits |
| Approximate numeric |
FLOAT, REAL |
Measurements, scientific computation |
| Text |
CHAR(n), VARCHAR(n), TEXT |
Fixed/variable length text |
| Boolean |
BOOLEAN, SQL Server BIT |
Flags |
| Date/time |
DATE, TIME, DATETIME, TIMESTAMP |
Dates and instants; meanings vary |
| Binary |
BLOB, VARBINARY, BYTEA |
Binary objects |
DECIMAL(5,2) means up to five total digits, two fractional digits (e.g. 999.99). Use exact numeric values for money in databases with fixed decimal types. Floating point is approximate; SQLite does not enforce fixed precision merely from DECIMAL(p,s). A date is not a time zone. PostgreSQL has TIMESTAMPTZ; SQL Server timestamp is a rowversion type, not a date/time. Choose text for telephone numbers or codes with leading zeroes, not arithmetic integers.
Physical storage and indexes are later topics; the logical table structure is what a query initially reasons about.
Inspect declared columns
PRAGMA table_info(customers);
Output (SQLite practice data):
| cid |
name |
type |
notnull |
dflt_value |
pk |
| 0 |
customer_id |
INT |
1 |
NULL |
1 |
| 1 |
name |
VARCHAR(50) |
1 |
NULL |
0 |
| 2 |
country |
VARCHAR(30) |
0 |
NULL |
0 |
| 3 |
email |
VARCHAR(100) |
0 |
NULL |
0 |
| 4 |
points |
INT |
0 |
0 |
0 |
How it works. SQLite-specific metadata inspection. MySQL has DESCRIBE customers; SQL Server and PostgreSQL expose information_schema and client object explorers.
Practical use. Check column names and types before constructing a query.
Common mistakes. Using strings for all numeric/date data; confusing precision and scale; assuming SQLite validates VARCHAR length or decimal scale; storing sensitive passwords as plaintext.
Exercise. Inspect the orders schema and identify the key.
Solution
PRAGMA table_info(orders);
Output (SQLite practice data):
| cid |
name |
type |
notnull |
dflt_value |
pk |
| 0 |
order_id |
INT |
1 |
NULL |
1 |
| 1 |
customer_id |
INT |
0 |
NULL |
0 |
| 2 |
order_date |
DATE |
1 |
NULL |
0 |
| 3 |
status |
VARCHAR(20) |
1 |
NULL |
0 |
| 4 |
amount |
DECIMAL(10,2) |
0 |
NULL |
0 |
How it works. The pk flag identifies order_id. This metadata syntax is SQLite-specific.
3. SELECT and FROM
SELECT defines the columns or expressions in the result; FROM identifies the data source. Aliases (AS) make result columns meaningful. * expands all columns, but explicit projection keeps output stable and avoids unnecessary data transfer. SQL keywords are generally case-insensitive; identifiers and string comparison rules depend on dialect, quoting and collation.
SELECT column1, expression AS alias
FROM table_name;
Use one clause per line, consistent aliases and semicolons between statements. -- starts a line comment (in MySQL include a following space); /* ... */ marks a block comment. Logical processing starts with FROM, not the first word SELECT.
Select particular columns
SELECT customer_id, name, points FROM customers ORDER BY customer_id;
Output (SQLite practice data):
| customer_id |
name |
points |
| 1 |
Ada |
1200 |
| 2 |
Ben |
400 |
| 3 |
Cleo |
800 |
| 4 |
Dina |
0 |
| 5 |
Eli |
NULL |
How it works. Only requested columns appear, in the order specified.
Practical use. Build a lightweight customer export.
Calculated columns
SELECT name, price, price * 1.10 AS new_price FROM products ORDER BY product_id;
Output (SQLite practice data):
| name |
price |
new_price |
| Laptop |
100 |
110.0 |
| Mouse |
20 |
22.0 |
| Notebook |
10 |
11.0 |
| Pen |
5 |
5.5 |
| Monitor |
150 |
165.0 |
How it works. The expression is evaluated per row without changing stored prices.
Practical use. Preview a proposed price increase.
Common mistakes. Omitting a comma between expressions; trailing comma before FROM; relying on SELECT * in production interfaces; using a SELECT alias in WHERE in most engines.
Exercise. Return each product name and the price after a 20% discount.
Solution
SELECT name, ROUND(price * 0.8, 2) AS discounted_price FROM products ORDER BY product_id;
Output (SQLite practice data):
| name |
discounted_price |
| Laptop |
80.0 |
| Mouse |
16.0 |
| Notebook |
8.0 |
| Pen |
4.0 |
| Monitor |
120.0 |
How it works. The discount is a derived result, not an UPDATE.
4. Filtering data and operators
WHERE retains rows for which the predicate evaluates TRUE. SQL uses three-valued logic: TRUE, FALSE and UNKNOWN. A comparison to NULL generally evaluates UNKNOWN, so use IS NULL or IS NOT NULL.
| Operator |
Meaning |
=, <>, !=, >, >=, <, <= |
Compare values |
AND, OR, NOT |
Combine or negate predicates |
BETWEEN a AND b |
Inclusive range |
IN (...), NOT IN (...) |
Membership (NULL caveat later) |
LIKE / NOT LIKE |
Pattern matching: % zero or more characters, _ one character |
IS NULL, IS NOT NULL |
Missing value checks |
NOT binds more tightly than AND, which binds more tightly than OR in common dialects; use parentheses for clarity. De Morgan's laws give NOT (A OR B) = NOT A AND NOT B. Negation does not turn UNKNOWN into TRUE. String literal values use single quotes; quote identifiers according to the engine rather than treating them as strings.
Compound filters
SELECT name, country, points
FROM customers
WHERE (country = 'USA' OR country = 'UK') AND points >= 800
ORDER BY customer_id;
Output (SQLite practice data):
| name |
country |
points |
| Ada |
USA |
1200 |
| Cleo |
USA |
800 |
How it works. Parentheses group the countries before applying the points condition.
Practical use. Segment eligible customers.
Range and list membership
SELECT order_id, amount, status
FROM orders
WHERE amount BETWEEN 40 AND 100 AND status IN ('Completed','Pending')
ORDER BY order_id;
Output (SQLite practice data):
| order_id |
amount |
status |
| 102 |
40 |
Completed |
| 103 |
80 |
Completed |
| 106 |
60 |
Completed |
| 108 |
100 |
Pending |
How it works. Both endpoints count. Each row must meet both predicates.
Practical use. Search a price band among selected statuses.
Wildcard and missing values
SELECT customer_id, name, email FROM customers
WHERE name LIKE 'A%' OR email IS NULL
ORDER BY customer_id;
Output (SQLite practice data):
| customer_id |
name |
email |
| 1 |
Ada |
ada@example.com |
| 2 |
Ben |
NULL |
How it works. A prefix pattern finds Ada; the missing-email predicate finds Ben.
Practical use. Find contact records requiring attention.
Common mistakes. Writing country = 'USA' OR 'UK' instead of two comparisons or IN; writing = NULL; using BETWEEN on timestamps without considering end-of-day; assuming LIKE is always case-sensitive.
Exercise. Find completed orders of at least 60 but less than 150.
Solution
SELECT order_id, amount FROM orders WHERE status = 'Completed' AND amount >= 60 AND amount < 150 ORDER BY order_id;
Output (SQLite practice data):
| order_id |
amount |
| 101 |
120 |
| 103 |
80 |
| 106 |
60 |
How it works. An explicit half-open range excludes 150.
5. Sorting, DISTINCT and pagination
ORDER BY determines result ordering. Use ASC (default) or DESC, with additional columns for tie-breaking. Without ORDER BY no row order is guaranteed. DISTINCT removes duplicate output rows, not duplicate values of each column independently. Pagination limits the returned rows, not necessarily the work required to find them.
| Engine |
Return first 3 rows |
Skip 3, return 3 |
| SQLite/PostgreSQL/MySQL |
LIMIT 3 |
LIMIT 3 OFFSET 3 |
| MySQL alternate |
LIMIT 3 |
LIMIT 3, 3 (offset, count) |
| SQL Server |
SELECT TOP (3) ... |
ORDER BY ... OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY |
SQL Server TOP and the LIMIT variants require deterministic ORDER BY when asking for a particular top N. Positional ORDER BY 2 is possible but brittle when projection changes. NULL ordering differs across engines.
SQL Server top-N syntax
Dialect: SQL Server.
SELECT TOP (3) name,salary FROM dbo.employees WHERE salary IS NOT NULL ORDER BY salary DESC,employee_id;
Expected behavior (illustrative): Alice 90000, Bob 70000, Cara 70000.
How it works. TOP limits the sorted result to three rows.
Distinct values
SELECT DISTINCT country FROM customers ORDER BY country;
Output (SQLite practice data):
| country |
| NULL |
| Germany |
| UK |
| USA |
How it works. DISTINCT collapses repeated USA and retains one NULL.
Practical use. List the countries present in the dataset.
Top 3 with a stable tie-break
SELECT name, salary FROM employees WHERE salary IS NOT NULL ORDER BY salary DESC, employee_id LIMIT 3;
Output (SQLite practice data):
| name |
salary |
| Alice |
90000 |
| Bob |
70000 |
| Cara |
70000 |
How it works. Salary is the primary sort; employee_id makes the tie reproducible.
Practical use. Retrieve the highest-paid employees.
Page two
SELECT order_id, order_date FROM orders ORDER BY order_date, order_id LIMIT 3 OFFSET 3;
Output (SQLite practice data):
| order_id |
order_date |
| 104 |
2025-02-11 |
| 105 |
2025-03-01 |
| 106 |
2025-03-15 |
How it works. Skip the first three sorted rows, then return three.
Practical use. Provide a small page of order history.
Common mistakes. Relying on physical row order; adding DISTINCT to hide a bad join; using LIMIT without ORDER BY for ranking; using large offsets without considering performance.
Exercise. Find the second and third most expensive products.
Solution
SELECT name, price FROM products ORDER BY price DESC, product_id LIMIT 2 OFFSET 1;
Output (SQLite practice data):
| name |
price |
| Laptop |
100 |
| Mouse |
20 |
How it works. Skip the first result, then return two.
Part II — Database Engineering
A useful query depends on a well-designed database. Now move from retrieving records to defining and maintaining their structure.
6. Creating and modifying databases and tables
DDL defines database objects. CREATE DATABASE shop; and USE shop; are MySQL/SQL Server examples (PostgreSQL connects to the chosen database; SQLite opens a file). DROP DATABASE removes an entire database and is destructive. MySQL also supports database read-only configuration in versions that implement it: ALTER DATABASE shop READ ONLY = 1; (reset to 0 before changing the practice database). Read-only modes and encryption settings are engine-specific administrative controls.
CREATE TABLE defines columns, types and constraints. ALTER TABLE changes a definition. DROP TABLE removes the table itself, including data. DELETE removes rows; TRUNCATE TABLE clears a table in engines that support it, with different identity, trigger and transaction behavior. SQLite has no TRUNCATE statement.
| Operation |
Example / dialect |
| Add column |
ALTER TABLE sandbox ADD COLUMN notes VARCHAR(100); (SQLite, PostgreSQL, MySQL) |
| Rename column |
ALTER TABLE sandbox RENAME COLUMN notes TO description; (SQLite, PostgreSQL, modern MySQL) |
| Rename table |
ALTER TABLE sandbox RENAME TO sandbox_new; (SQLite/PostgreSQL); MySQL RENAME TABLE sandbox TO sandbox_new |
| Modify type |
MySQL MODIFY COLUMN description VARCHAR(200); PostgreSQL ALTER COLUMN description TYPE VARCHAR(200) |
| Reorder column |
MySQL MODIFY COLUMN description VARCHAR(200) FIRST or AFTER other_column |
| Drop column |
ALTER TABLE sandbox DROP COLUMN description; (subject to dependencies/version) |
SQL Server uses different syntax for certain operations, including sp_rename and ALTER COLUMN. DDL can lock objects or implicitly commit in some engines. Use explicit column lists in inserts rather than relying on physical order.
Build and inspect a disposable table
SELECT id, label, notes FROM sandbox ORDER BY id;
Output (SQLite practice data):
| id |
label |
notes |
| 1 |
sample |
NULL |
How it works. The preparation creates the table, inserts one row and adds a nullable column. Existing rows have NULL for notes.
Practical use. Add a new optional attribute without manually recreating the table.
-- Run in a fresh practice database.
CREATE TABLE sandbox (id INT PRIMARY KEY, label VARCHAR(30));
INSERT INTO sandbox VALUES (1, 'sample');
ALTER TABLE sandbox ADD COLUMN notes VARCHAR(100);
SELECT id, label, notes FROM sandbox;
-- After inspection, clean up only this disposable table:
DROP TABLE sandbox;
Common mistakes. Confusing DROP, DELETE and TRUNCATE; dropping dependent columns; assuming all DDL can be rolled back; applying type conversions without validating existing data.
Exercise. Create a disposable two-column table and add a nullable integer quantity column. Inspect the result.
Run this preparation in a fresh practice connection:
CREATE TABLE stock_sandbox(id INT PRIMARY KEY, name VARCHAR(30));
ALTER TABLE stock_sandbox ADD COLUMN quantity INT;
Solution
PRAGMA table_info(stock_sandbox);
Output (SQLite practice data):
| cid |
name |
type |
notnull |
dflt_value |
pk |
| 0 |
id |
INT |
0 |
NULL |
1 |
| 1 |
name |
VARCHAR(30) |
0 |
NULL |
0 |
| 2 |
quantity |
INT |
0 |
NULL |
0 |
How it works. The new field appears in the schema. Execute the two preparation statements before the inspection.
7. Keys, relationships and constraints
A key identifies records or connects tables. A primary key is unique and non-null (one primary key constraint may cover multiple columns). A foreign key references an eligible unique parent key, often a primary key. Natural keys have meaning outside the database; surrogate keys are assigned identifiers. A composite key combines attributes. In order_items, neither order_id nor product_id is individually unique, but the pair is.
| Constraint / attribute |
What it does |
PRIMARY KEY |
Identifies the row |
FOREIGN KEY ... REFERENCES |
Rejects invalid non-null references |
NOT NULL |
Prevents missing values |
UNIQUE |
Prevents duplicate non-null key values; NULL behavior varies |
CHECK |
Rejects rows violating a condition (UNKNOWN can pass) |
DEFAULT |
Supplies a value when omitted |
MySQL AUTO_INCREMENT, SQL Server IDENTITY, PostgreSQL GENERATED ... AS IDENTITY |
Generates identifiers |
Define constraints at creation or use supported ALTER TABLE ... ADD CONSTRAINT operations later. SQLite often requires a table rebuild for new constraints. Name constraints to make maintenance and diagnostics easier. A default is not a replacement for an explicitly supplied NULL unless the engine has a special rule. Generated IDs need not be consecutive.
One-to-one relationships require uniqueness of the foreign key; one-to-many is implemented using a foreign key on the many side. Many-to-many uses a junction table. Self-referencing keys represent relationships such as employee → manager.
CREATE TABLE demo_pay (
id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE,
hourly_pay DECIMAL(5,2) NOT NULL,
CONSTRAINT chk_pay CHECK (hourly_pay >= 10)
);
Expected behavior. A row with hourly pay 15 is accepted. A row with 5 or NULL is rejected. Adding a second non-null email identical to an existing one violates UNIQUE. A nullable unique email may allow multiple NULLs depending on engine. A constraint enforces valid data at write time, instead of relying on every application to validate independently.
CREATE TABLE demo_parent (id INT PRIMARY KEY);
CREATE TABLE demo_child (
id INT PRIMARY KEY,
parent_id INT REFERENCES demo_parent(id) ON DELETE SET NULL
);
ON DELETE SET NULL retains child rows and clears a nullable reference. ON DELETE CASCADE deletes matching child rows. RESTRICT / NO ACTION prevents deletion while dependent references exist, subject to engine timing rules. Cascades should reflect business intent; a foreign key in a composite primary key does not automatically require CASCADE.
Show a many-to-many association
SELECT oi.order_id, p.name, oi.quantity
FROM order_items oi JOIN products p ON p.product_id = oi.product_id
WHERE oi.order_id = 101 ORDER BY p.product_id;
Output (SQLite practice data):
| order_id |
name |
quantity |
| 101 |
Laptop |
1 |
| 101 |
Mouse |
1 |
How it works. One order connects to two products through the junction table.
Practical use. Represent purchases without repeating customer or product attributes.
Common mistakes. Using names as identifiers when they are not unique; forgetting foreign-key enforcement; assuming a CHECK automatically rejects NULL; cascading deletions without understanding downstream effects.
Exercise. Predict and inspect the child row after deleting its parent with ON DELETE SET NULL.
Run this preparation in a fresh practice connection:
CREATE TABLE demo_parent(id INT PRIMARY KEY);
CREATE TABLE demo_child(id INT PRIMARY KEY, parent_id INT REFERENCES demo_parent(id) ON DELETE SET NULL);
INSERT INTO demo_parent VALUES(1);
INSERT INTO demo_child VALUES(10,1);
DELETE FROM demo_parent WHERE id=1;
Solution
SELECT * FROM demo_child;
Output (SQLite practice data):
How it works. The child remains and its parent_id becomes NULL. The preparation shown conceptually above uses a disposable database.
8. INSERT, UPDATE and DELETE
DML changes stored records. Always specify the column list when inserting partial rows; omitted columns receive defaults or NULL if allowed. Multirow VALUES is more concise than separate INSERT statements. INSERT INTO ... SELECT copies rows from a query. Use UPDATE ... SET for existing rows and DELETE FROM ... WHERE to delete matching rows, not columns.
INSERT INTO table_name (col1, col2) VALUES (value1, value2);
UPDATE table_name SET col2 = value WHERE condition;
DELETE FROM table_name WHERE condition;
Preview the exact WHERE predicate with SELECT first. A missing predicate updates or deletes every row. UPDATE can use expressions, multiple assignments and subqueries; a DELETE can use a subquery as well. Workbench safe-update mode may restrict operations not using appropriate key predicates or limits, but it is not a guarantee of safety.
CREATE TABLE demo_products AS SELECT * FROM products;
INSERT INTO demo_products(product_id,name,category,price) VALUES(15,'Cable','Tech',8),(16,'Bag','Office',30);
UPDATE demo_products SET price=price*1.1 WHERE category='Tech';
DELETE FROM demo_products WHERE product_id=16;
Inspect the modified copy
SELECT product_id,name,price FROM demo_products ORDER BY product_id;
Output (SQLite practice data):
| product_id |
name |
price |
| 10 |
Laptop |
110.0 |
| 11 |
Mouse |
22 |
| 12 |
Notebook |
10 |
| 13 |
Pen |
5 |
| 14 |
Monitor |
165 |
| 15 |
Cable |
8.8 |
How it works. Two records are inserted, the Tech rows increase by 10%, then Bag is deleted. This copy has no inherited constraints.
Practical use. Try changes without modifying the baseline products table.
Parent-child insertion (MySQL example). A generated parent ID must be reused in the same connection when inserting child rows. Use a transaction to commit both operations together. The following assumes a schema in which orders.order_id is AUTO_INCREMENT and the other fields match our practice schema. PostgreSQL can use INSERT ... RETURNING order_id; SQL Server can use OUTPUT INSERTED.order_id or SCOPE_IDENTITY() with appropriate care.
START TRANSACTION;
INSERT INTO orders (customer_id, order_date, status, amount)
VALUES (1, '2025-05-01', 'Completed', 40);
SET @order_id = LAST_INSERT_ID();
INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES (@order_id, 11, 2, 20);
COMMIT;
Expected: one new order and one child line referencing the generated ID, or rollback on failure. This example requires a MySQL-specific identity schema and is not run in SQLite. In application code, handle errors and roll back explicitly.
Common mistakes. Omitting WHERE; assuming CTAS preserves constraints; relying on consecutive generated IDs; concatenating user input into SQL instead of binding parameters.
Exercise. On a disposable copy, flag completed orders of at least 100 as Reviewed.
Run this preparation in a fresh practice connection:
CREATE TABLE orders_copy AS SELECT * FROM orders;
UPDATE orders_copy SET status='Reviewed' WHERE status='Completed' AND amount>=100;
Solution
SELECT order_id,status FROM orders_copy ORDER BY order_id;
Output (SQLite practice data):
| order_id |
status |
| 101 |
Reviewed |
| 102 |
Completed |
| 103 |
Completed |
| 104 |
Cancelled |
| 105 |
Reviewed |
| 106 |
Completed |
| 107 |
Completed |
| 108 |
Pending |
How it works. Only qualifying orders change; the baseline stays intact.
9. Transactions and safe data manipulation
A transaction groups changes into a unit of work. COMMIT makes changes durable according to the database's guarantees; ROLLBACK undoes uncommitted changes. Autocommit is commonly enabled, so separate statements may each commit automatically. In MySQL SET autocommit = 0 disables it for that session; PostgreSQL, SQLite and SQL Server have their own transaction syntax.
BEGIN → modifications → validation → COMMIT
└─ error → ROLLBACK
A useful mental model is that one purchase should not persist its order without its item rows. For transactional storage, the logical unit should succeed together or fail together. A commit is not a savepoint. Committed changes cannot be undone by ordinary ROLLBACK. This chapter covers the practical transaction basics, not a deep treatment of isolation, locking or deadlocks.
BEGIN TRANSACTION;
DELETE FROM order_items WHERE order_id = 108;
DELETE FROM orders WHERE order_id = 108;
SELECT COUNT(*) AS remaining_orders FROM orders;
ROLLBACK;
SELECT COUNT(*) AS remaining_orders FROM orders;
Output (executed in a fresh SQLite database):
| Stage |
orders count |
| Before |
8 |
| Before rollback |
7 |
| After rollback |
8 |
The child is deleted before the parent to satisfy the foreign key. The rollback restores both. In a real transaction, COMMIT would be used after validation. SQL Server BEGIN TRANSACTION and PostgreSQL BEGIN are suitable; MySQL uses START TRANSACTION. Do not rely on rolling back MySQL DDL that causes implicit commits.
Common mistakes. Expecting ROLLBACK to undo a committed statement; leaving transactions open; treating a transaction as a backup; failing to handle errors or foreign keys.
Exercise. Preview deleting all rows from a disposable copy and then restore them with a rollback.
Solution
Dialect: SQLite (run as a script in a fresh connection).
CREATE TABLE tx_demo AS SELECT * FROM customers;
-- Commit table creation first if your client has an open transaction.
BEGIN TRANSACTION;
DELETE FROM tx_demo;
SELECT COUNT(*) FROM tx_demo;
ROLLBACK;
SELECT COUNT(*) FROM tx_demo;
Expected behavior (illustrative): 0 during the transaction, 5 after rollback. The table creation is outside the transaction.
10. ER diagrams and relational database design
Start with business requirements, not with CREATE TABLE. Identify entities, attributes, keys, relationships, cardinality and participation. An entity represents an object such as customer; an attribute describes it. A relationship connects entities. Cardinality is the number of entities that can participate (one or many); participation indicates whether involvement is mandatory or optional.
| ER concept |
Example |
Relational mapping |
| Strong entity |
Customer |
Table with a primary key |
| Composite attribute |
Full name, address |
Separate atomic fields where appropriate |
| Multivalued attribute |
Customer phone numbers |
Child table with customer key and phone |
| Derived attribute |
Age from birth date |
Compute when needed |
| Weak entity |
Order line dependent on order |
Owner key plus identifying attribute(s) |
| Relationship attribute |
Quantity on order/product |
Store in junction table |
| 1:1 |
Employee and assigned locker |
FK with UNIQUE, or combine if appropriate |
| 1:N |
Customer and order |
FK on many side |
| M:N |
Order and product |
Junction table |
Separating customer details from orders avoids repeating the same address on every order when the address is a customer attribute. Historical shipping addresses may intentionally be stored on orders if they represent the address at the time of purchase. That is a business requirement, not needless duplication. This introduces normalization intuitively; formal normal forms are beyond this chapter.
Requirements → ER diagram → relational schema → constraints → test data → queries
Customer 0..N Orders; Order 0..N Items; Product 0..N Items
Each Item references exactly one Order and one Product (in a strict design).
In the practice schema, the order customer is optional (anonymous purchase); the item composite primary key identifies one product per order. A separate line ID would be needed if repeated identical products can appear on separate lines. ER diagrams often use rectangles for entities, ovals for attributes and diamonds for relationships, or crow's-foot notation for cardinality.
CREATE TABLE demo_supplier (supplier_id INT NOT NULL PRIMARY KEY, name VARCHAR(50));
CREATE TABLE demo_supply (
supplier_id INT NOT NULL REFERENCES demo_supplier(supplier_id),
product_id INT NOT NULL REFERENCES products(product_id),
cost DECIMAL(8,2) CHECK (cost >= 0),
PRIMARY KEY (supplier_id, product_id)
);
Expected: a supplier can supply multiple products and a product can have multiple suppliers. The junction table records a relationship-specific cost. A repeated pair is rejected.
Common mistakes. Storing multiple phone numbers in a comma-separated field; choosing the wrong grain for a fact table; confusing optional participation with cardinality; assuming FK alone enforces a mandatory or one-to-one relationship.
Exercise. Design a student/course enrollment relationship including a grade.
Solution
Dialect: Portable DDL (fresh practice database).
CREATE TABLE students (student_id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE courses (course_id INT PRIMARY KEY, title VARCHAR(100));
CREATE TABLE enrollments (
student_id INT NOT NULL REFERENCES students(student_id),
course_id INT NOT NULL REFERENCES courses(course_id),
grade DECIMAL(5,2), PRIMARY KEY (student_id, course_id)
);
Expected behavior (illustrative): One record per student/course pair; grade belongs to enrollment, not student or course. If retakes are allowed, include an attempt identifier.
Part III — Querying and Combining Data
Learn to summarize rows, combine related records, compare datasets and break complex questions into smaller queries.
11. Aggregation, GROUP BY and HAVING
Aggregate functions return a summary rather than a value per input row. COUNT(*) counts rows; COUNT(column) counts non-NULL values; COUNT(DISTINCT column) counts distinct non-null values. SUM, AVG, MIN and MAX ignore NULL inputs; with no non-null inputs they normally return NULL. AVG uses the number of non-null values, not the total row count.
GROUP BY defines the output grain. One group per country means one result row per country. WHERE filters input rows; HAVING filters groups after aggregation. Selected expressions that are neither aggregates nor grouped must satisfy the engine's grouping rules; portable queries group every nonaggregated column. Think of aggregation as collapsing rows, not adding a total to every row.
| Logical sequence (simplified) |
Purpose |
| FROM / JOIN / ON |
Build input rows |
| WHERE |
Filter rows |
| GROUP BY |
Form groups |
| HAVING |
Filter groups |
| SELECT (including windows after grouping) |
Compute output expressions |
| DISTINCT |
Remove duplicate output rows |
| ORDER BY |
Sort result |
| LIMIT / TOP / OFFSET-FETCH |
Limit result |
This is logical processing, not the physical execution plan. An optimizer can reorder operations while preserving query semantics.
Overall summary
SELECT COUNT(*) AS orders, COUNT(customer_id) AS identified_orders, SUM(amount) AS total, AVG(amount) AS mean_amount, MIN(amount) AS minimum, MAX(amount) AS maximum FROM orders;
Output (SQLite practice data):
| orders |
identified_orders |
total |
mean_amount |
minimum |
maximum |
| 8 |
7 |
620 |
77.5 |
20 |
150 |
How it works. COUNT(customer_id) excludes the anonymous order. Other aggregates summarize the amount column.
Practical use. Profile records before further analysis.
Group and filter
SELECT customer_id, COUNT(*) AS orders, SUM(amount) AS total
FROM orders
WHERE status = 'Completed'
GROUP BY customer_id
HAVING SUM(amount) >= 100
ORDER BY total DESC;
Output (SQLite practice data):
| customer_id |
orders |
total |
| 1 |
2 |
200 |
| 3 |
1 |
150 |
| 2 |
2 |
100 |
How it works. First discard noncompleted rows; group by customer; then filter the totals.
Practical use. Find valuable customers.
ROLLUP. Reporting queries often need both detail groups and a grand total. MySQL uses GROUP BY department_id WITH ROLLUP; SQL Server/PostgreSQL use GROUP BY ROLLUP(department_id). SQLite can emulate a one-level rollup with UNION ALL. A subtotal NULL is different from a genuine NULL grouping value; use GROUPING() where available or explicit labels.
One-level subtotal and total
SELECT COALESCE(CAST(department_id AS VARCHAR(10)), 'Unassigned') AS department,
SUM(salary) AS total_salary
FROM employees GROUP BY department_id
UNION ALL
SELECT 'Grand total', SUM(salary) FROM employees;
Output (SQLite practice data):
| department |
total_salary |
| Unassigned |
NULL |
| 1 |
230000 |
| 2 |
110000 |
| 3 |
55000 |
| Grand total |
395000 |
How it works. The second query aggregates all rows; UNION ALL appends the total. The unassigned employee has an unknown salary.
Practical use. Prepare a report with subtotals.
Common mistakes. Using WHERE SUM(...); averaging group averages without weighting; counting rows after a one-to-many join without checking grain; treating missing salary as zero by default.
Exercise. Find completed revenue by status-independent customer ID, but only customers with at least two completed orders.
Solution
SELECT customer_id, COUNT(*) AS n, SUM(amount) AS revenue
FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
GROUP BY customer_id HAVING COUNT(*) >= 2 ORDER BY customer_id;
Output (SQLite practice data):
| customer_id |
n |
revenue |
| 1 |
2 |
200 |
| 2 |
2 |
100 |
How it works. WHERE removes anonymous/noncompleted rows; HAVING tests the number of remaining orders per customer.
12. All JOIN types and join strategies
A join combines columns from related tables. Think in terms of matching row pairs, not a Venn diagram alone. If a customer has three orders, joining the customer to orders returns three customer/order pairs. If both sides have multiple matching rows, the counts multiply.
| Join |
Behavior |
| INNER |
Matching pairs only |
| LEFT OUTER |
All left rows; unmatched right columns become NULL |
| RIGHT OUTER |
All right rows; unmatched left columns become NULL |
| FULL OUTER |
Matching pairs and unmatched rows on both sides |
| CROSS |
Cartesian product (all pairs) |
| SELF |
A table joined to itself using different aliases |
| LEFT/RIGHT anti |
Rows from one side with no match, via outer join + NULL or NOT EXISTS |
| FULL anti |
Unmatched rows from both sides, via full join + filters |
MySQL does not have native FULL OUTER JOIN; combine a left join with a right-side anti join using UNION ALL. SQLite 3.39+ supports RIGHT and FULL. SQL Server, PostgreSQL and MySQL support CROSS JOIN; the self join is a pattern, not a keyword.
Inner join — orders with customers
SELECT o.order_id, c.name, o.amount
FROM orders o INNER JOIN customers c ON o.customer_id = c.customer_id
ORDER BY o.order_id;
Output (SQLite practice data):
| order_id |
name |
amount |
| 101 |
Ada |
120 |
| 102 |
Ben |
40 |
| 103 |
Ada |
80 |
| 104 |
Cleo |
50 |
| 105 |
Cleo |
150 |
| 106 |
Ben |
60 |
| 108 |
Ada |
100 |
How it works. The anonymous order cannot match a customer and is excluded.
Practical use. Attach customer information to transactions.
Left join — all customers, including those with no orders
SELECT c.name, o.order_id
FROM customers c LEFT JOIN orders o ON c.customer_id=o.customer_id
ORDER BY c.customer_id, o.order_id;
Output (SQLite practice data):
| name |
order_id |
| Ada |
101 |
| Ada |
103 |
| Ada |
108 |
| Ben |
102 |
| Ben |
106 |
| Cleo |
104 |
| Cleo |
105 |
| Dina |
NULL |
| Eli |
NULL |
How it works. Dina and Eli survive the join with NULL order IDs. Ada appears three times.
Practical use. Keep all customers in a retention report.
Right join — preserve all customers
SELECT c.name,o.order_id FROM orders o RIGHT JOIN customers c ON o.customer_id=c.customer_id ORDER BY c.customer_id,o.order_id;
Output (SQLite practice data):
| name |
order_id |
| Ada |
101 |
| Ada |
103 |
| Ada |
108 |
| Ben |
102 |
| Ben |
106 |
| Cleo |
104 |
| Cleo |
105 |
| Dina |
NULL |
| Eli |
NULL |
How it works. Swapping the table order and using RIGHT JOIN gives the same logical matching pairs as the earlier LEFT JOIN.
Practical use. Preserve the reference population.
Full outer join — reconcile both datasets
SELECT c.customer_id, c.name, o.order_id
FROM customers c FULL OUTER JOIN orders o ON c.customer_id=o.customer_id
ORDER BY c.customer_id, o.order_id;
Output (SQLite practice data):
| customer_id |
name |
order_id |
| NULL |
NULL |
107 |
| 1 |
Ada |
101 |
| 1 |
Ada |
103 |
| 1 |
Ada |
108 |
| 2 |
Ben |
102 |
| 2 |
Ben |
106 |
| 3 |
Cleo |
104 |
| 3 |
Cleo |
105 |
| 4 |
Dina |
NULL |
| 5 |
Eli |
NULL |
How it works. Customers without orders and the anonymous order all appear.
Practical use. Find unmatched source records.
Left anti join — customers without orders
SELECT c.customer_id, c.name
FROM customers c LEFT JOIN orders o ON o.customer_id=c.customer_id
WHERE o.order_id IS NULL ORDER BY c.customer_id;
Output (SQLite practice data):
| customer_id |
name |
| 4 |
Dina |
| 5 |
Eli |
How it works. Test a non-nullable key from the right table to distinguish unmatched rows from matched rows with missing attributes.
Practical use. Identify potential re-engagement targets.
Full anti join — unmatched rows on either side
SELECT c.name,o.order_id FROM customers c FULL OUTER JOIN orders o ON c.customer_id=o.customer_id WHERE c.customer_id IS NULL OR o.order_id IS NULL ORDER BY c.name,o.order_id;
Output (SQLite practice data):
| name |
order_id |
| NULL |
107 |
| Dina |
NULL |
| Eli |
NULL |
How it works. Keep only the rows without a partner on either side.
Practical use. Reconcile missing references and unused customer records.
Self outer join — employees and managers
SELECT e.name AS employee, m.name AS manager
FROM employees e LEFT JOIN employees m ON e.manager_id=m.employee_id
ORDER BY e.employee_id;
Output (SQLite practice data):
| employee |
manager |
| Alice |
NULL |
| Bob |
Alice |
| Cara |
Alice |
| Dan |
NULL |
| Eva |
Dan |
| Finn |
NULL |
| Gina |
Alice |
How it works. Aliases distinguish the two roles of the same table. Top-level employees remain.
Practical use. Create an organization directory.
Cross join — combinations
WITH sizes AS (SELECT 'Small' AS size UNION ALL SELECT 'Large'),
colors AS (SELECT 'Red' AS color UNION ALL SELECT 'Blue')
SELECT size,color FROM sizes CROSS JOIN colors ORDER BY size,color;
Output (SQLite practice data):
| size |
color |
| Large |
Blue |
| Large |
Red |
| Small |
Blue |
| Small |
Red |
How it works. Two sizes times two colors produce four rows.
Practical use. Generate possible product variations or parameter combinations.
Multiple joins and matching composite keys
SELECT o.order_id, c.name AS customer, p.name AS product, oi.quantity
FROM orders o LEFT JOIN customers c ON o.customer_id=c.customer_id
JOIN order_items oi ON oi.order_id=o.order_id
JOIN products p ON p.product_id=oi.product_id
ORDER BY o.order_id,p.product_id;
Output (SQLite practice data):
| order_id |
customer |
product |
quantity |
| 101 |
Ada |
Laptop |
1 |
| 101 |
Ada |
Mouse |
1 |
| 102 |
Ben |
Mouse |
2 |
| 103 |
Ada |
Mouse |
4 |
| 104 |
Cleo |
Notebook |
5 |
| 105 |
Cleo |
Laptop |
1 |
| 105 |
Cleo |
Notebook |
5 |
| 106 |
Ben |
Mouse |
3 |
| 107 |
NULL |
Mouse |
1 |
| 108 |
Ada |
Laptop |
1 |
How it works. The grain is now order line, not order. Joining orders to their items repeats order-level amounts.
Practical use. Create a line-level sales report.
For a compound relationship, match every component of the key. For example ON a.order_id=b.order_id AND a.product_id=b.product_id. In SQLite, PostgreSQL and MySQL JOIN ... USING (order_id, product_id) is a shorthand when names match; SQL Server uses ON. USING changes how common columns appear under SELECT *. NATURAL JOIN matches all identically named columns automatically and can silently change behavior if schemas change. Prefer explicit conditions. Implicit joins such as FROM customers c, orders o WHERE ... are legal in many engines but can accidentally become cross joins.
Cross-database joins: MySQL can refer to sql_store.order_items and sql_inventory.products on the same server; SQL Server supports database.schema.table. PostgreSQL requires an appropriate cross-database mechanism rather than simply another database prefix. In SQLite attached database files use schema-qualified names.
Important outer-join trap: placing o.status='Completed' in WHERE after a left join removes unmatched rows. Put the predicate in ON when the goal is to retain every customer while matching only completed orders.
USING with a shared column
SELECT customer_id,c.name,o.order_id FROM customers c JOIN orders o USING(customer_id) ORDER BY o.order_id;
Output (SQLite practice data):
| customer_id |
name |
order_id |
| 1 |
Ada |
101 |
| 2 |
Ben |
102 |
| 1 |
Ada |
103 |
| 3 |
Cleo |
104 |
| 3 |
Cleo |
105 |
| 2 |
Ben |
106 |
| 1 |
Ada |
108 |
How it works. The common key is specified once; the qualified columns distinguish the two tables.
Compound join — match the whole key
WITH item_notes(order_id,product_id,note) AS (SELECT 101,11,'Gift wrap' UNION ALL SELECT 105,12,'Urgent')
SELECT oi.order_id,oi.product_id,n.note FROM order_items oi JOIN item_notes n ON n.order_id=oi.order_id AND n.product_id=oi.product_id ORDER BY oi.order_id,oi.product_id;
Output (SQLite practice data):
| order_id |
product_id |
note |
| 101 |
11 |
Gift wrap |
| 105 |
12 |
Urgent |
How it works. Matching just the order ID would incorrectly attach each note to every item in that order.
Practical use. Join line-level attributes without multiplying rows.
Keep all customers while counting completed orders
SELECT c.name, COUNT(o.order_id) AS completed_orders
FROM customers c LEFT JOIN orders o
ON o.customer_id=c.customer_id AND o.status='Completed'
GROUP BY c.customer_id,c.name ORDER BY c.customer_id;
Output (SQLite practice data):
| name |
completed_orders |
| Ada |
2 |
| Ben |
2 |
| Cleo |
1 |
| Dina |
0 |
| Eli |
0 |
How it works. COUNT of the right key is zero for no match, unlike COUNT(*).
Practical use. Build customer activity features without losing inactive customers.
Common mistakes. Joining on names instead of stable keys; missing a composite-key condition; COUNT(*) after outer join; filtering the nullable side in WHERE; summing order-level amounts after expanding to line grain.
Exercise. Find products that have never appeared in an order item.
Solution
SELECT p.product_id,p.name FROM products p
LEFT JOIN order_items oi ON oi.product_id=p.product_id
WHERE oi.order_id IS NULL ORDER BY p.product_id;
Output (SQLite practice data):
| product_id |
name |
| 13 |
Pen |
| 14 |
Monitor |
How it works. The anti join returns products without any matching item.
13. Set operators
Joins combine columns; set operators combine rows from compatible result sets. Each branch must return the same number of columns, in the same semantic order, with compatible types. The first query generally defines output names. UNION, INTERSECT, and EXCEPT remove duplicate rows by default; UNION ALL preserves multiplicity. An ORDER BY at the end sorts the combined result. SQL Server and PostgreSQL support these four; SQLite does too. Older MySQL versions lack INTERSECT and EXCEPT; check the version.
| Operator |
Result when A = {1,2,2,3}, B = {2,4} |
| UNION |
1, 2, 3, 4 |
| UNION ALL |
1, 2, 2, 3, 2, 4 |
| INTERSECT |
2 |
| EXCEPT (A minus B) |
1, 3 |
Use UNION ALL for appending monthly extracts when rows should be retained; UNION for genuinely distinct rows. To compare two datasets' distinct contents, check EXCEPT in both directions. This does not verify duplicate multiplicities.
UNION — completed customers versus customers with high points
SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
UNION
SELECT customer_id FROM customers WHERE points>=800
ORDER BY customer_id;
Output (SQLite practice data):
How it works. Each branch selects a compatible identifier. The operator determines membership and multiplicity.
Practical use. Compare customer cohorts.
UNION ALL — completed customers versus customers with high points
SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
UNION ALL
SELECT customer_id FROM customers WHERE points>=800
ORDER BY customer_id;
Output (SQLite practice data):
| customer_id |
| 1 |
| 1 |
| 1 |
| 2 |
| 2 |
| 3 |
| 3 |
How it works. Each branch selects a compatible identifier. The operator determines membership and multiplicity.
Practical use. Compare customer cohorts.
INTERSECT — completed customers versus customers with high points
SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
INTERSECT
SELECT customer_id FROM customers WHERE points>=800
ORDER BY customer_id;
Output (SQLite practice data):
How it works. Each branch selects a compatible identifier. The operator determines membership and multiplicity.
Practical use. Compare customer cohorts.
EXCEPT — completed customers versus customers with high points
SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
EXCEPT
SELECT customer_id FROM customers WHERE points>=800
ORDER BY customer_id;
Output (SQLite practice data):
How it works. Each branch selects a compatible identifier. The operator determines membership and multiplicity.
Practical use. Compare customer cohorts.
Common mistakes. Using UNION when duplicate events are meaningful; mismatching column order; treating EXCEPT as symmetric; assuming UNION ALL guarantees branch order.
Exercise. Find customers who have never placed an order using EXCEPT.
Solution
SELECT customer_id FROM customers
EXCEPT
SELECT customer_id FROM orders
ORDER BY customer_id;
Output (SQLite practice data):
How it works. Subtract identifiers present in orders.
14. Subqueries and subquery operators
A subquery is a query embedded in another statement. It may return a single scalar, a list of values, or a table. A scalar subquery must return at most one row and one column in engines that enforce scalar cardinality; SQLite can take the first row, which can conceal mistakes. A derived table in FROM or JOIN needs an alias for portable code.
A noncorrelated subquery can be understood independently of the outer row. A correlated subquery references an outer column; conceptually it is evaluated for that row, although the optimizer may rewrite it. SQL engines may decorrelate, cache or otherwise optimize either form.
Scalar subquery — orders above average
SELECT order_id,amount FROM orders
WHERE amount > (SELECT AVG(amount) FROM orders)
ORDER BY amount DESC,order_id;
Output (SQLite practice data):
| order_id |
amount |
| 105 |
150 |
| 101 |
120 |
| 108 |
100 |
| 103 |
80 |
How it works. The inner aggregate returns one number; the outer WHERE compares each order to it.
Practical use. Identify larger-than-average transactions.
Subquery in SELECT — attach a global average
SELECT order_id,amount,(SELECT ROUND(AVG(amount),2) FROM orders) AS overall_avg FROM orders WHERE order_id IN (101,102) ORDER BY order_id;
Output (SQLite practice data):
| order_id |
amount |
overall_avg |
| 101 |
120 |
77.5 |
| 102 |
40 |
77.5 |
How it works. The independent scalar subquery supplies the same baseline for each selected row.
Derived table in JOIN
SELECT c.name,COALESCE(t.total,0) AS total FROM customers c LEFT JOIN (SELECT customer_id,SUM(amount) AS total FROM orders WHERE status='Completed' GROUP BY customer_id) t ON c.customer_id=t.customer_id ORDER BY c.customer_id;
Output (SQLite practice data):
| name |
total |
| Ada |
200 |
| Ben |
100 |
| Cleo |
150 |
| Dina |
0 |
| Eli |
0 |
How it works. Aggregate to customer grain before joining, preserving each customer exactly once.
Derived table — filter aggregated totals
SELECT t.customer_id,t.total FROM (
SELECT customer_id,SUM(amount) AS total FROM orders GROUP BY customer_id
) AS t WHERE t.total>100 ORDER BY t.customer_id;
Output (SQLite practice data):
| customer_id |
total |
| 1 |
300 |
| 3 |
200 |
How it works. The inner table establishes customer grain; the outer query filters that result.
Practical use. Build a reusable intermediate calculation within a statement.
SELECT o.order_id,o.customer_id,o.amount FROM orders o
WHERE o.amount > (SELECT AVG(i.amount) FROM orders i WHERE i.customer_id=o.customer_id)
ORDER BY o.order_id;
Output (SQLite practice data):
| order_id |
customer_id |
amount |
| 101 |
1 |
120 |
| 105 |
3 |
150 |
| 106 |
2 |
60 |
How it works. The average is for the outer order customer. NULL customer IDs do not match using equality.
Practical use. Compare each transaction with its customer baseline.
IN with a multirow subquery
SELECT name FROM customers WHERE customer_id IN (SELECT customer_id FROM orders WHERE status='Completed') ORDER BY customer_id;
Output (SQLite practice data):
How it works. The inner query supplies eligible IDs. Repeated IDs do not multiply outer rows.
EXISTS — customers with a completed purchase
SELECT c.customer_id,c.name FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o
WHERE o.customer_id=c.customer_id AND o.status='Completed')
ORDER BY c.customer_id;
Output (SQLite practice data):
| customer_id |
name |
| 1 |
Ada |
| 2 |
Ben |
| 3 |
Cleo |
How it works. EXISTS tests whether at least one matching row exists; it does not duplicate customers with many orders.
Practical use. Semijoin-style filtering.
NOT EXISTS — safe anti-match
SELECT c.customer_id,c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id=c.customer_id)
ORDER BY c.customer_id;
Output (SQLite practice data):
| customer_id |
name |
| 4 |
Dina |
| 5 |
Eli |
How it works. The anonymous order does not invalidate the test. In contrast, NOT IN (SELECT customer_id FROM orders) yields no matches because the subquery includes NULL.
Practical use. Identify inactive customers safely.
| Operator |
Meaning |
IN |
Equal to at least one returned value |
NOT IN |
Not equal to any value, with UNKNOWN risk if NULL is present |
> ANY (subquery) |
Greater than at least one returned value |
> ALL (subquery) |
Greater than every returned value |
EXISTS / NOT EXISTS |
At least one row / no rows |
ANY and ALL are supported in SQL Server, PostgreSQL and MySQL but not SQLite's quantified-comparison syntax. Empty sets and NULL values matter: comparison with ALL over an empty result is TRUE; ANY over an empty result is FALSE. A rewrite using MIN/MAX is equivalent only under appropriate nonempty and non-null assumptions.
Quantified comparison — greater than at least one Office price
Dialect: PostgreSQL / MySQL / SQL Server.
SELECT name,price FROM products WHERE price > ANY (SELECT price FROM products WHERE category='Office') ORDER BY product_id;
Expected behavior (illustrative): Laptop (100), Mouse (20), Notebook (10), Monitor (150).
How it works. The price must exceed at least one of the Office prices (5 and 10).
Quantified comparison — greater than all Office prices
Dialect: PostgreSQL / MySQL / SQL Server.
SELECT name, price FROM products WHERE price > ALL (SELECT price FROM products WHERE category='Office') ORDER BY product_id;
Expected behavior (illustrative): Laptop (100), Mouse (20), Monitor (150).
How it works. The largest Office price is 10; every returned product exceeds both Office prices.
Subqueries also work in DML. Example: UPDATE orders SET status='Reviewed' WHERE customer_id IN (SELECT customer_id FROM customers WHERE points>=800) AND status='Completed'; Preview and run on a copy; the same predicate can be used for a DELETE when that is the intended action.
Common mistakes. Using = with a multirow subquery; forgetting correlation conditions; NOT IN with NULL; expecting correlated subqueries to always be slower; neglecting to qualify ambiguous columns.
Exercise. Find employees whose salary is above the average of their own department.
Solution
SELECT e.name,e.salary FROM employees e
WHERE e.salary>(SELECT AVG(i.salary) FROM employees i WHERE i.department_id=e.department_id)
ORDER BY e.employee_id;
Output (SQLite practice data):
| name |
salary |
| Alice |
90000 |
| Dan |
60000 |
How it works. The inner aggregate compares each person with their own department, not the company average.
15. Common table expressions and recursion
A common table expression (CTE) names an intermediate query result for use in one statement. It is often easier to read than several nested subqueries. Define multiple CTEs separated by commas; later CTEs can reference earlier ones. A CTE can declare its output column names. It is not a persistent table, and materialization is an optimizer/dialect decision rather than a guarantee.
WITH first_step AS (...),
second_step AS (SELECT ... FROM first_step)
SELECT ... FROM second_step;
The ellipses are syntax placeholders. In SQL Server, terminate the previous statement with a semicolon before WITH. SQL Server does not use the RECURSIVE keyword; PostgreSQL, MySQL and SQLite use WITH RECURSIVE for recursive definitions.
Chained CTEs — sales and segments
WITH completed AS (
SELECT customer_id,amount FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
), totals AS (
SELECT customer_id,SUM(amount) AS revenue FROM completed GROUP BY customer_id
)
SELECT c.name,t.revenue FROM totals t JOIN customers c ON c.customer_id=t.customer_id
WHERE t.revenue>=100 ORDER BY t.revenue DESC;
Output (SQLite practice data):
| name |
revenue |
| Ada |
200 |
| Cleo |
150 |
| Ben |
100 |
How it works. Each named stage has one purpose: filter, aggregate, enrich.
Practical use. Build a readable multi-stage business query.
Recursive CTE — generate numbers
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n+1 FROM numbers WHERE n<5
)
SELECT n FROM numbers ORDER BY n;
Output (SQLite practice data):
How it works. The anchor emits 1; the recursive member consumes the previous level until the condition stops producing rows.
Practical use. Build small sequence datasets.
Employee hierarchy
WITH RECURSIVE hierarchy(employee_id,name,level) AS (
SELECT employee_id,name,0 FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id,e.name,h.level+1
FROM employees e JOIN hierarchy h ON e.manager_id=h.employee_id
WHERE h.level<10
)
SELECT * FROM hierarchy ORDER BY level,employee_id;
Output (SQLite practice data):
| employee_id |
name |
level |
| 1 |
Alice |
0 |
| 4 |
Dan |
0 |
| 6 |
Finn |
0 |
| 2 |
Bob |
1 |
| 3 |
Cara |
1 |
| 5 |
Eva |
1 |
| 7 |
Gina |
1 |
How it works. Anchor selects roots; recursive member finds direct reports of the prior level. Depth guard limits recursion, but a robust general graph traversal also needs cycle detection.
Practical use. Map organizational hierarchy.
Common mistakes. Trying to query a CTE in a later independent statement; assuming a CTE is stored on disk or always faster; using recursion without a termination condition; referencing CTEs out of order.
Exercise. Use two CTEs to count completed orders per customer and retain counts at least 2.
Solution
WITH completed AS (SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL),
counts AS (SELECT customer_id,COUNT(*) AS n FROM completed GROUP BY customer_id)
SELECT c.name,counts.n FROM counts JOIN customers c ON c.customer_id=counts.customer_id
WHERE counts.n>=2 ORDER BY c.customer_id;
Output (SQLite practice data):
How it works. The first step filters, the second groups, the final step enriches and filters.
SQL is not only a query language for retrieving data. Row-level functions prepare data for reporting, analysis and feature engineering.
16. String functions and regular expressions
Text functions transform a value without necessarily changing its stored representation. Use them to clean names, standardize codes and extract useful features. Function names and index positions differ between languages and engines; SQL substring positions are generally one-based.
| Operation |
SQLite |
PostgreSQL / MySQL / SQL Server notes |
| Length |
LENGTH(s) |
PG/MySQL LENGTH; MySQL CHAR_LENGTH counts characters; T-SQL LEN excludes trailing spaces |
| Upper/lower |
UPPER, LOWER |
Common |
| Strip spaces |
TRIM, LTRIM, RTRIM |
Common, optional trim syntax differs |
| Substring |
SUBSTR(s,2,3) |
SUBSTRING(s,2,3) widely available |
| Prefix/suffix |
SUBSTR(s,1,n) / SUBSTR(s,-n) |
LEFT(s,n) / RIGHT(s,n) |
| Replace |
REPLACE(s,a,b) |
Common |
| Search position |
INSTR(s,pattern) |
MySQL LOCATE, T-SQL CHARINDEX, PG POSITION |
| Concatenate |
a || b or recent SQLite CONCAT |
PG ||/CONCAT, MySQL CONCAT, T-SQL CONCAT |
CONCAT and concatenation operators differ in how they treat NULL. Check the dialect before assuming an unknown component becomes an empty string.
Clean and split text
WITH raw(label) AS (SELECT ' Ada-Smith ')
SELECT TRIM(label) AS clean, UPPER(TRIM(label)) AS uppercase,
LENGTH(label) AS raw_length, LENGTH(TRIM(label)) AS clean_length,
REPLACE(TRIM(label),'-',' ') AS standardized,
SUBSTR(TRIM(label),1,3) AS prefix,
INSTR(TRIM(label),'-') AS dash_position FROM raw;
Output (SQLite practice data):
| clean |
uppercase |
raw_length |
clean_length |
standardized |
prefix |
dash_position |
| Ada-Smith |
ADA-SMITH |
13 |
9 |
Ada Smith |
Ada |
4 |
How it works. TRIM removes the surrounding spaces; nested functions act on the cleaned value.
Practical use. Standardize names imported from spreadsheets.
Build a customer display label
SELECT name || ' (' || COALESCE(country,'Unknown') || ')' AS label FROM customers ORDER BY customer_id;
Output (SQLite practice data):
| label |
| Ada (USA) |
| Ben (UK) |
| Cleo (USA) |
| Dina (Germany) |
| Eli (Unknown) |
How it works. The NULL country is explicitly replaced before concatenation.
Practical use. Build readable labels for reports.
Regular expressions. LIKE supports % and _; regular expressions offer anchors, alternatives and character classes.
| Pattern |
Meaning |
smith |
Contains smith |
^A |
Starts with A |
son$ |
Ends with son |
smith|jones |
Either alternative |
[ae] |
One of the listed characters |
[a-h] |
One character in the range |
e[ru] |
er or eu |
MySQL uses REGEXP / REGEXP_LIKE; PostgreSQL uses ~ (case sensitive) or ~* (case insensitive). SQLite REGEXP requires a user-supplied implementation. SQL Server's regex capabilities depend on version; simple LIKE patterns remain portable. Regex flavor and collation can change results.
Match either A or B at the beginning
Dialect: MySQL.
SELECT name FROM customers WHERE name REGEXP '^[AB]' ORDER BY customer_id;
Expected behavior (illustrative): Ada, Ben.
How it works. The anchor starts matching at the first character; the character class allows either letter.
Common mistakes. Confusing LIKE and regex wildcards; trimming after comparison rather than before; using byte length as character count; assuming normalization fixes every spelling difference.
Exercise. Return the first three characters of each product name in lowercase.
Solution
SELECT name, LOWER(SUBSTR(name,1,3)) AS prefix FROM products ORDER BY product_id;
Output (SQLite practice data):
| name |
prefix |
| Laptop |
lap |
| Mouse |
mou |
| Notebook |
not |
| Pen |
pen |
| Monitor |
mon |
How it works. Extract first, then lowercase. SUBSTR is SQLite syntax.
17. Numeric functions and calculations
Arithmetic is a row-level transformation. Use +, -, *, / and modulo (% or MOD by dialect). Multiplication and division bind before addition and subtraction; parentheses make intent clear. SQL engines differ in integer division and numeric result types. With integer inputs, 5/2 can yield 2 rather than 2.5; cast or use a decimal operand. ROUND controls displayed precision, ABS returns magnitude. Round at the correct stage: rounding each line before summing can produce a different total from rounding the sum.
Calculate quantity × unit price
SELECT order_id,product_id,quantity,unit_price,
quantity*unit_price AS line_total FROM order_items
WHERE order_id=101 ORDER BY product_id;
Output (SQLite practice data):
| order_id |
product_id |
quantity |
unit_price |
line_total |
| 101 |
10 |
1 |
100 |
100 |
| 101 |
11 |
1 |
20 |
20 |
How it works. Each row produces a calculated line total.
Practical use. Build a revenue feature at line grain.
Division and rounding
SELECT 5/2 AS integer_division, 5.0/2 AS decimal_division, ROUND(10.0/3,2) AS rounded, ABS(-12) AS magnitude, 17%5 AS remainder;
Output (SQLite practice data):
| integer_division |
decimal_division |
rounded |
magnitude |
remainder |
| 2 |
2.5 |
3.33 |
12 |
2 |
How it works. SQLite integer division truncates; one real operand changes the result.
Practical use. Compute ratios and differences carefully.
Percentage of original price
SELECT name, price, ROUND(price*0.15,2) AS discount, ROUND(price*(1-0.15),2) AS final_price FROM products ORDER BY product_id;
Output (SQLite practice data):
| name |
price |
discount |
final_price |
| Laptop |
100 |
15.0 |
85.0 |
| Mouse |
20 |
3.0 |
17.0 |
| Notebook |
10 |
1.5 |
8.5 |
| Pen |
5 |
0.75 |
4.25 |
| Monitor |
150 |
22.5 |
127.5 |
How it works. The discount is 15% of the price, not a fixed subtraction.
Practical use. Compare pricing scenarios.
Common mistakes. Integer division in ratios; mixing approximate and exact amounts; ignoring division by zero; rounding away important precision too early.
Exercise. Calculate each line amount including a hypothetical 10% surcharge for order 105.
Solution
SELECT product_id,quantity*unit_price AS base, ROUND(quantity*unit_price*1.1,2) AS with_surcharge FROM order_items WHERE order_id=105 ORDER BY product_id;
Output (SQLite practice data):
| product_id |
base |
with_surcharge |
| 10 |
100 |
110.0 |
| 12 |
50 |
55.0 |
How it works. Multiplication occurs at order-item grain.
18. Date and time functions
Dates allow time-based filters, durations and reporting periods. Store date/time values using the appropriate engine types, not arbitrary formatted text. The SQLite practice dates use ISO 8601 YYYY-MM-DD text so date functions and chronological comparison work here. CURRENT_DATE gives today's date and CURRENT_TIMESTAMP a current timestamp; exact time-zone/transaction semantics differ. Use fixed dates in examples for reproducibility.
| Task |
SQLite |
MySQL |
PostgreSQL |
SQL Server |
| Current date |
date('now') |
CURRENT_DATE() |
CURRENT_DATE |
CAST(GETDATE() AS date) |
| Current time |
time('now') |
CURRENT_TIME() |
CURRENT_TIME |
CAST(GETDATE() AS time) |
| Timestamp |
datetime('now') |
NOW() |
CURRENT_TIMESTAMP |
GETDATE() |
| Extract year |
strftime('%Y',d) |
YEAR(d) |
EXTRACT(YEAR FROM d) |
YEAR(d) / DATEPART(year,d) |
| Month start |
date(d,'start of month') |
date functions / DATE_FORMAT |
date_trunc('month',d) |
DATETRUNC(month,d) (2022+) |
| Month end |
date(d,'start of month','+1 month','-1 day') |
LAST_DAY(d) |
month start + interval |
EOMONTH(d) |
| Add days |
date(d,'+7 days') |
DATE_ADD(d,INTERVAL 7 DAY) |
d + INTERVAL '7 days' |
DATEADD(day,7,d) |
| Days between |
julianday(b)-julianday(a) |
DATEDIFF(b,a) |
b-a for dates |
DATEDIFF(day,a,b) |
| Format |
strftime('%Y-%m',d) |
DATE_FORMAT(d,'%Y-%m') |
TO_CHAR(d,'YYYY-MM') |
FORMAT(d,'yyyy-MM') |
DATENAME in SQL Server returns a date part's name, such as month. CAST, CONVERT and FORMAT serve different tasks: converting types is different from formatting text for display. ISDATE tests convertibility to supported date/time values under SQL Server rules; do not assume it validates every business date format. MySQL STR_TO_DATE parses a specified pattern. PostgreSQL AT TIME ZONE converts between timestamp interpretations; the direction depends on the input type. Use a named zone where daylight-saving rules matter. Date addition must use calendar functions or intervals, not integer arithmetic on encoded dates.
Date extraction and calendar calculations
SELECT order_id,order_date,strftime('%Y-%m',order_date) AS month,
date(order_date,'+7 days') AS due_date,
date(order_date,'start of month','+1 month','-1 day') AS month_end
FROM orders WHERE order_id IN (101,103,105) ORDER BY order_id;
Output (SQLite practice data):
| order_id |
order_date |
month |
due_date |
month_end |
| 101 |
2025-01-10 |
2025-01 |
2025-01-17 |
2025-01-31 |
| 103 |
2025-02-05 |
2025-02 |
2025-02-12 |
2025-02-28 |
| 105 |
2025-03-01 |
2025-03 |
2025-03-08 |
2025-03-31 |
How it works. The functions extract the month and perform calendar-aware arithmetic.
Practical use. Calculate delivery dates or reporting periods.
Half-open date range
SELECT order_id,order_date,amount FROM orders WHERE order_date >= '2025-02-01' AND order_date < '2025-03-01' ORDER BY order_id;
Output (SQLite practice data):
| order_id |
order_date |
amount |
| 103 |
2025-02-05 |
80 |
| 104 |
2025-02-11 |
50 |
How it works. All February dates qualify; the next month is excluded. With timestamps, this also avoids excluding later times on the final day.
Practical use. Filter monthly transactions.
Parse a date string
Dialect: MySQL.
SELECT STR_TO_DATE('02/11/2025','%m/%d/%Y') AS parsed_date;
Expected behavior (illustrative): 2025-02-11.
How it works. Explicitly specifies the source date format instead of relying on implicit conversion.
Common mistakes. Hardcoding the year when asking for current year; grouping by month number without year; treating DATEDIFF as elapsed seconds in all cases; ignoring time zones and ambiguous formats; wrapping indexed dates in functions unnecessarily.
Exercise. Summarize completed revenue by year-month.
Solution
SELECT strftime('%Y-%m',order_date) AS month,SUM(amount) AS revenue
FROM orders WHERE status='Completed'
GROUP BY strftime('%Y-%m',order_date) ORDER BY month;
Output (SQLite practice data):
| month |
revenue |
| 2025-01 |
160 |
| 2025-02 |
80 |
| 2025-03 |
230 |
How it works. Group on a year-month key, not month alone. SQLite formatting syntax.
19. NULL handling and type conversion
NULL means absent, unknown or inapplicable; it is not 0, an empty string, or spaces. COALESCE(a,b,c) chooses the first non-null expression; SQL Server ISNULL(a,b) replaces NULL but has different type rules; MySQL ISNULL(x) is a predicate, not the same function. NULLIF(a,b) returns NULL when the values compare equal. Combine TRIM and NULLIF to standardize blank strings only when blank truly means missing.
| Expression |
Result |
COALESCE(NULL,10,20) |
10 |
NULLIF(10,10) |
NULL |
NULLIF(10,20) |
10 |
COALESCE(NULLIF(TRIM(' '),''),'Unknown') |
Unknown |
amount / NULLIF(quantity,0) |
NULL when quantity is zero |
Do not blindly impute a missing salary as zero: that changes the meaning of an average. If a missing value truly represents no activity, a zero after a left join can be appropriate. When joining on nullable keys, NULL does not equal NULL using ordinary equality; replacing both NULL keys with a sentinel can cause false matches.
CAST(expression AS type) is widely supported. SQL Server CONVERT(type,expression[,style]) handles conversions and formats; its safe conversion alternatives can be useful when checking messy data. PostgreSQL supports expression::type. SQLite's permissive conversion can turn invalid numeric text into 0, unlike stricter engines. Validate input before converting. A query result can also be sorted by a CASE expression to explicitly position NULLs.
Normalize blank and missing emails
SELECT name,email,COALESCE(NULLIF(TRIM(email),''),'Missing') AS clean_email,
CASE WHEN NULLIF(TRIM(email),'') IS NULL THEN 1 ELSE 0 END AS missing_flag
FROM customers ORDER BY customer_id;
Output (SQLite practice data):
| name |
email |
clean_email |
missing_flag |
| Ada |
ada@example.com |
ada@example.com |
0 |
| Ben |
NULL |
Missing |
1 |
| Cleo |
cleo@example.com |
cleo@example.com |
0 |
| Dina |
|
Missing |
1 |
| Eli |
eli@example.com |
eli@example.com |
0 |
How it works. Blank and NULL are mapped to a display label, with a separate flag preserving information about missingness.
Practical use. Audit contact-data completeness.
Prevent division by zero
SELECT 100.0/NULLIF(0,0) AS undefined_ratio,100.0/NULLIF(4,0) AS valid_ratio,CAST('42' AS INTEGER) AS parsed_integer;
Output (SQLite practice data):
| undefined_ratio |
valid_ratio |
parsed_integer |
| NULL |
25.0 |
42 |
How it works. The denominator becomes NULL instead of zero; the ratio remains undefined.
Practical use. Build safe KPI calculations.
Compare missing and filled counts
SELECT COUNT(*) AS total,COUNT(email) AS non_null,COUNT(NULLIF(TRIM(email),'')) AS usable FROM customers;
Output (SQLite practice data):
| total |
non_null |
usable |
| 5 |
4 |
3 |
How it works. COUNT(email) includes empty strings; the cleaned expression excludes them.
Practical use. Measure data quality before imputation.
Common mistakes. Comparing NULL with =; replacing unknown values with 0 without business justification; assuming blank and NULL mean the same thing; relying on implicit type conversions; dividing by zero.
Exercise. Return all employee salaries, unknown salaries last and highest known salaries first.
Solution
SELECT name,salary FROM employees ORDER BY CASE WHEN salary IS NULL THEN 1 ELSE 0 END,salary DESC,employee_id;
Output (SQLite practice data):
| name |
salary |
| Alice |
90000 |
| Bob |
70000 |
| Cara |
70000 |
| Dan |
60000 |
| Finn |
55000 |
| Eva |
50000 |
| Gina |
NULL |
How it works. Sort by a missingness flag before salary, independent of default NULL ordering.
20. CASE expressions and data cleaning
CASE is SQL's conditional expression. A searched CASE evaluates predicates in order and returns the first matching result; simple CASE compares a single expression to candidate values. If no branch matches and ELSE is absent, the result is NULL. CASE can appear in SELECT, ORDER BY, aggregations and other expression contexts. It returns a value, not a procedural statement.
CASE WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
ELSE fallback END
Arrange thresholds carefully, e.g. highest to lowest. For cleaning: stage a copy of raw data, inspect duplicates, standardize text and types, handle missing data using domain rules, remove unusable records if justified, and validate. Never overwrite the only source. Deduplication requires a business key and a deterministic rule, not just SELECT DISTINCT.
Customer segmentation
SELECT name,points,
CASE WHEN points IS NULL THEN 'Unknown'
WHEN points>=1000 THEN 'Gold'
WHEN points>=500 THEN 'Silver'
ELSE 'Bronze' END AS segment
FROM customers ORDER BY customer_id;
Output (SQLite practice data):
| name |
points |
segment |
| Ada |
1200 |
Gold |
| Ben |
400 |
Bronze |
| Cleo |
800 |
Silver |
| Dina |
0 |
Bronze |
| Eli |
NULL |
Unknown |
How it works. NULL is handled explicitly before thresholds.
Practical use. Convert numeric values into business categories.
Simple CASE — map a known category
SELECT order_id,status,CASE status WHEN 'Completed' THEN 'Recognized' WHEN 'Pending' THEN 'Open' ELSE 'Excluded' END AS report_status FROM orders ORDER BY order_id;
Output (SQLite practice data):
| order_id |
status |
report_status |
| 101 |
Completed |
Recognized |
| 102 |
Completed |
Recognized |
| 103 |
Completed |
Recognized |
| 104 |
Cancelled |
Excluded |
| 105 |
Completed |
Recognized |
| 106 |
Completed |
Recognized |
| 107 |
Completed |
Recognized |
| 108 |
Pending |
Open |
How it works. Simple CASE compares one expression against each listed value.
Practical use. Map operational status codes to reporting labels.
Simple CASE and conditional aggregation
SELECT SUM(CASE WHEN status='Completed' THEN amount ELSE 0 END) AS completed,
SUM(CASE WHEN status='Cancelled' THEN amount ELSE 0 END) AS cancelled,
SUM(CASE WHEN status='Pending' THEN amount ELSE 0 END) AS pending FROM orders;
Output (SQLite practice data):
| completed |
cancelled |
pending |
| 470 |
50 |
100 |
How it works. Each order contributes to the corresponding total.
Practical use. Produce multiple KPI columns in one scan.
CREATE TABLE raw_contacts(row_id INT,customer_id INT,email TEXT,updated_at TEXT);
INSERT INTO raw_contacts VALUES(1,1,' Ada@Example.com ','2025-01-01'),(2,1,'ada@example.com','2025-02-01'),(3,2,' ','2025-01-05'),(4,3,NULL,'2025-01-07');
Standardize and identify duplicates
WITH cleaned AS (
SELECT row_id,customer_id,NULLIF(LOWER(TRIM(email)),'') AS email,updated_at FROM raw_contacts
), ranked AS (
SELECT *,ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY updated_at DESC,row_id DESC) AS rn FROM cleaned
)
SELECT customer_id,email,updated_at FROM ranked WHERE rn=1 ORDER BY customer_id;
Output (SQLite practice data):
| customer_id |
email |
updated_at |
| 1 |
ada@example.com |
2025-02-01 |
| 2 |
NULL |
2025-01-05 |
| 3 |
NULL |
2025-01-07 |
How it works. The staging query normalizes email and retains the latest row for each customer. Window functions are explained in Part V.
Practical use. Create a reliable clean layer from duplicate imports.
A MySQL cleaning workflow can use CREATE TABLE staging LIKE raw_table; INSERT INTO staging SELECT * FROM raw_table; to preserve more structure than CTAS. Identify duplicate keys with ROW_NUMBER, create a second staging table including row number if needed, delete where rn > 1, then drop the helper column. MySQL cannot directly delete from every CTE result. To fill missing industry labels from known rows for the same company, first check that company-to-industry is unambiguous; use an update join or correlated lookup only when the known label is valid. Convert date strings with STR_TO_DATE before altering the column type. Reject or retain rows with missing metrics according to downstream requirements.
Common mistakes. Wrong CASE order; silently grouping NULL as Bronze; deleting duplicates using an incomplete key; filling every missing numeric field with zero; standardizing categories without checking meaning.
Exercise. Classify order amounts: at least 100 High, at least 50 Medium, otherwise Low.
Solution
SELECT order_id,amount,CASE WHEN amount>=100 THEN 'High' WHEN amount>=50 THEN 'Medium' ELSE 'Low' END AS band
FROM orders ORDER BY order_id;
Output (SQLite practice data):
| order_id |
amount |
band |
| 101 |
120 |
High |
| 102 |
40 |
Low |
| 103 |
80 |
Medium |
| 104 |
50 |
Medium |
| 105 |
150 |
High |
| 106 |
60 |
Medium |
| 107 |
20 |
Low |
| 108 |
100 |
High |
How it works. Highest threshold first; ELSE handles all remaining known amounts. If amounts can be NULL, add a distinct Unknown branch.
Part V — Advanced Analytics
Window functions preserve row detail while calculating across related records. Combine them with intermediate query stages to answer questions that ordinary GROUP BY cannot express conveniently.
21. Window functions and frames
GROUP BY reduces rows to groups; window functions normally preserve the rows entering the window stage. A window function calculates a value using a set of related rows. The OVER clause describes that set. It may contain a partition, an ordering and a frame.
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
PARTITION BY splits the input into independent groups without collapsing them. If absent, the whole result is one partition.
- Window
ORDER BY specifies calculation order, not final display order.
ROWS BETWEEN ... AND ... defines physical row offsets relative to the current row. UNBOUNDED PRECEDING starts at the partition's beginning; CURRENT ROW refers to the current row; n PRECEDING and n FOLLOWING set offsets; UNBOUNDED FOLLOWING ends at the partition's final row.
RANGE defines a logical range and can include peer rows with the same ordering value. Support for numeric/interval range offsets varies. Many engines default an ordered aggregate window to a peer-inclusive RANGE frame; explicit ROWS is safer for deterministic row-by-row totals.
Window results are not available to WHERE at the same query level; use a CTE or subquery to filter them. Window functions run logically after grouping/HAVING. You cannot generally nest one window function directly inside another at the same query level. Rank and offset functions have different frame rules from aggregate windows.
Compare detail to overall and customer totals
SELECT order_id,customer_id,amount,
SUM(amount) OVER() AS all_amount,
SUM(amount) OVER(PARTITION BY customer_id) AS customer_amount,
ROUND(AVG(amount) OVER(PARTITION BY customer_id),2) AS customer_avg
FROM orders ORDER BY order_id;
Output (SQLite practice data):
| order_id |
customer_id |
amount |
all_amount |
customer_amount |
customer_avg |
| 101 |
1 |
120 |
620 |
300 |
100.0 |
| 102 |
2 |
40 |
620 |
100 |
50.0 |
| 103 |
1 |
80 |
620 |
300 |
100.0 |
| 104 |
3 |
50 |
620 |
200 |
100.0 |
| 105 |
3 |
150 |
620 |
200 |
100.0 |
| 106 |
2 |
60 |
620 |
100 |
50.0 |
| 107 |
NULL |
20 |
620 |
20 |
20.0 |
| 108 |
1 |
100 |
620 |
300 |
100.0 |
How it works. No rows collapse. Each row includes the overall and per-customer totals. NULL customer IDs form a partition; decide whether that grouping has business meaning.
Practical use. Show transaction context beside every record.
Running total, moving average and extremes
SELECT order_id,amount,
SUM(amount) OVER(ORDER BY order_date,order_id ROWS UNBOUNDED PRECEDING) AS running_total,
ROUND(AVG(amount) OVER(ORDER BY order_date,order_id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW),2) AS moving_avg_3,
MIN(amount) OVER() AS minimum, MAX(amount) OVER() AS maximum
FROM orders WHERE status='Completed' ORDER BY order_date,order_id;
Output (SQLite practice data):
| order_id |
amount |
running_total |
moving_avg_3 |
minimum |
maximum |
| 101 |
120 |
120 |
120.0 |
20 |
150 |
| 102 |
40 |
160 |
80.0 |
20 |
150 |
| 103 |
80 |
240 |
80.0 |
20 |
150 |
| 105 |
150 |
390 |
90.0 |
20 |
150 |
| 106 |
60 |
450 |
96.67 |
20 |
150 |
| 107 |
20 |
470 |
76.67 |
20 |
150 |
How it works. A running total grows from the first row. The moving frame holds up to three consecutive records, not three calendar months. The first two frames have fewer than three rows.
Practical use. Monitor transaction trends and context.
Visualize a running window over amounts 20, 10, 30, 5, 40:
| Current row |
Running frame |
Running SUM |
Trailing 3-row frame |
Moving SUM |
| 1 |
20 |
20 |
20 |
20 |
| 2 |
20, 10 |
30 |
20, 10 |
30 |
| 3 |
20, 10, 30 |
60 |
20, 10, 30 |
60 |
| 4 |
20, 10, 30, 5 |
65 |
10, 30, 5 |
45 |
| 5 |
20, 10, 30, 5, 40 |
105 |
30, 5, 40 |
75 |
To calculate a moving average, divide by the number of non-null values in the frame. A centered frame ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING includes future rows, which would be inappropriate for a historical prediction feature.
Counts and percentage of total
SELECT order_id,amount,COUNT(*) OVER() AS row_count,
ROUND(100.0*amount/NULLIF(SUM(amount) OVER(),0),2) AS pct_total
FROM orders WHERE status='Completed' ORDER BY order_id;
Output (SQLite practice data):
| order_id |
amount |
row_count |
pct_total |
| 101 |
120 |
6 |
25.53 |
| 102 |
40 |
6 |
8.51 |
| 103 |
80 |
6 |
17.02 |
| 105 |
150 |
6 |
31.91 |
| 106 |
60 |
6 |
12.77 |
| 107 |
20 |
6 |
4.26 |
How it works. The denominator is the completed-order total, not the total across excluded statuses. NULLIF prevents division by zero.
Practical use. Measure each transaction contribution.
Common mistakes. Using GROUP BY when detail rows must remain; relying on default frame with ties; confusing window order with output order; using future rows in historical features; treating a row frame as a time interval.
Exercise. Calculate a running total of completed order amounts for each identified customer.
Solution
SELECT customer_id,order_id,amount,
SUM(amount) OVER(PARTITION BY customer_id ORDER BY order_date,order_id ROWS UNBOUNDED PRECEDING) AS running_total
FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
ORDER BY customer_id,order_date,order_id;
Output (SQLite practice data):
| customer_id |
order_id |
amount |
running_total |
| 1 |
101 |
120 |
120 |
| 1 |
103 |
80 |
200 |
| 2 |
102 |
40 |
40 |
| 2 |
106 |
60 |
100 |
| 3 |
105 |
150 |
150 |
How it works. Partition restarts the accumulation for every customer.
22. Ranking, segmentation and distributions
Ranking functions assign positions within each ordered partition. Ties determine which function is appropriate. ROW_NUMBER assigns distinct integers; RANK assigns the same rank to peers and skips following ranks; DENSE_RANK has no gaps. NTILE(n) divides ordered rows into up to n buckets, with larger buckets first when the count is not divisible; equal values can be split across buckets. PERCENT_RANK measures relative rank and CUME_DIST the fraction of rows at or before the current peer group.
For n rows, PERCENT_RANK = (RANK - 1)/(n-1) (0 for a single row), and CUME_DIST = number of rows preceding or tied with current row / n. These are relative positions, not the same as assigning a continuous percentile cutoff. The window ordering determines which values count as earlier.
Three ranking functions side by side
SELECT name,salary,
ROW_NUMBER() OVER(ORDER BY salary DESC,employee_id) AS row_num,
RANK() OVER(ORDER BY salary DESC) AS rank_num,
DENSE_RANK() OVER(ORDER BY salary DESC) AS dense_rank_num
FROM employees WHERE salary IS NOT NULL ORDER BY salary DESC,employee_id;
Output (SQLite practice data):
| name |
salary |
row_num |
rank_num |
dense_rank_num |
| Alice |
90000 |
1 |
1 |
1 |
| Bob |
70000 |
2 |
2 |
2 |
| Cara |
70000 |
3 |
2 |
2 |
| Dan |
60000 |
4 |
4 |
3 |
| Finn |
55000 |
5 |
5 |
4 |
| Eva |
50000 |
6 |
6 |
5 |
How it works. Bob and Cara tie in RANK and DENSE_RANK. ROW_NUMBER uses employee_id to break the tie; including that ID in RANK would change the peer groups.
Practical use. Choose exactly N people or top N distinct salary levels.
Quantile buckets and relative distributions
SELECT name,salary,
NTILE(3) OVER(ORDER BY salary,employee_id) AS bucket,
ROUND(PERCENT_RANK() OVER(ORDER BY salary),3) AS percent_rank,
ROUND(CUME_DIST() OVER(ORDER BY salary),3) AS cume_dist
FROM employees WHERE salary IS NOT NULL ORDER BY salary,employee_id;
Output (SQLite practice data):
| name |
salary |
bucket |
percent_rank |
cume_dist |
| Eva |
50000 |
1 |
0.0 |
0.167 |
| Finn |
55000 |
1 |
0.2 |
0.333 |
| Dan |
60000 |
2 |
0.4 |
0.5 |
| Bob |
70000 |
2 |
0.6 |
0.833 |
| Cara |
70000 |
3 |
0.6 |
0.833 |
| Alice |
90000 |
3 |
1.0 |
1.0 |
How it works. Six known salaries produce three buckets of two. Distribution functions retain ties in salary.
Practical use. Divide a population into ordered cohorts.
Top salaries per department
WITH ranked AS (
SELECT employee_id,name,department_id,salary,
DENSE_RANK() OVER(PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees WHERE salary IS NOT NULL AND department_id IS NOT NULL
)
SELECT department_id,name,salary,rnk FROM ranked WHERE rnk<=2 ORDER BY department_id,rnk,employee_id;
Output (SQLite practice data):
| department_id |
name |
salary |
rnk |
| 1 |
Alice |
90000 |
1 |
| 1 |
Bob |
70000 |
2 |
| 1 |
Cara |
70000 |
2 |
| 2 |
Dan |
60000 |
1 |
| 2 |
Eva |
50000 |
2 |
| 3 |
Finn |
55000 |
1 |
How it works. Filter in the outer query. DENSE_RANK can return more than two people per department when salaries tie.
Practical use. Find top performers or highest-paid employees by group.
To deduplicate, use ROW_NUMBER partitioned by the intended business key, ordered by a reliable latest timestamp and stable tie-break. Then select rn = 1. A ranking without unique ordering can select different survivors across executions. Use a GROUP BY count check to verify that the resulting business key is unique.
Common mistakes. Using RANK when exactly N rows are required; accidentally breaking ties with a unique ID in RANK; using NTILE as if all equal values stay together; filtering window values in WHERE.
Exercise. Select exactly one highest-paid employee in each nonempty department, breaking salary ties by employee ID.
Solution
WITH ranked AS (
SELECT employee_id,name,department_id,salary,
ROW_NUMBER() OVER(PARTITION BY department_id ORDER BY salary DESC,employee_id) AS rn
FROM employees WHERE department_id IS NOT NULL AND salary IS NOT NULL
)
SELECT department_id,name,salary FROM ranked WHERE rn=1 ORDER BY department_id;
Output (SQLite practice data):
| department_id |
name |
salary |
| 1 |
Alice |
90000 |
| 2 |
Dan |
60000 |
| 3 |
Finn |
55000 |
How it works. ROW_NUMBER ensures one survivor per partition.
23. LAG, LEAD and time-series analysis
LAG accesses an earlier ordered row; LEAD accesses a later row. FIRST_VALUE and LAST_VALUE access the first and last value in the current frame. Offset functions commonly accept an offset and a default for out-of-range rows. A missing previous row is different from a previous row whose value is NULL.
Time-series analysis often begins by aggregating transactions to a common period. If a month is absent, LAG returns the previous available row, not automatically the previous calendar month. Build a calendar spine and fill absent periods deliberately when the business definition requires it. In forecasting or ML, LEAD and frames containing following rows may leak future data.
Monthly revenue and growth
WITH monthly AS (
SELECT strftime('%Y-%m',order_date) AS month,SUM(amount) AS revenue
FROM orders WHERE status='Completed' GROUP BY strftime('%Y-%m',order_date)
), compared AS (
SELECT month,revenue,LAG(revenue) OVER(ORDER BY month) AS previous,
LEAD(revenue) OVER(ORDER BY month) AS next_month
FROM monthly
)
SELECT month,revenue,previous,next_month,revenue-previous AS change,
ROUND(100.0*(revenue-previous)/NULLIF(previous,0),2) AS growth_pct
FROM compared ORDER BY month;
Output (SQLite practice data):
| month |
revenue |
previous |
next_month |
change |
growth_pct |
| 2025-01 |
160 |
NULL |
80 |
NULL |
NULL |
| 2025-02 |
80 |
160 |
230 |
-80 |
-50.0 |
| 2025-03 |
230 |
80 |
NULL |
150 |
187.5 |
How it works. The first CTE produces month-level revenue. LAG compares consecutive available months. Growth is undefined for the first row or a zero denominator. LEAD is shown for retrospective analysis only.
Practical use. Compare monthly business performance.
First and last value across each partition
SELECT order_id,customer_id,amount,
FIRST_VALUE(amount) OVER(PARTITION BY customer_id ORDER BY order_date,order_id) AS first_amount,
LAST_VALUE(amount) OVER(PARTITION BY customer_id ORDER BY order_date,order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_amount
FROM orders WHERE customer_id IS NOT NULL ORDER BY customer_id,order_date,order_id;
Output (SQLite practice data):
| order_id |
customer_id |
amount |
first_amount |
last_amount |
| 101 |
1 |
120 |
120 |
100 |
| 103 |
1 |
80 |
120 |
100 |
| 108 |
1 |
100 |
120 |
100 |
| 102 |
2 |
40 |
40 |
60 |
| 106 |
2 |
60 |
40 |
60 |
| 104 |
3 |
50 |
50 |
150 |
| 105 |
3 |
150 |
50 |
150 |
How it works. LAST_VALUE uses the explicit full partition frame. With the default ordered frame, it may return the current row rather than the final partition value.
Practical use. Compare a customer’s first and most recent purchase.
Days since previous completed order
WITH history AS (
SELECT customer_id,order_id,order_date,
LAG(order_date) OVER(PARTITION BY customer_id ORDER BY order_date,order_id) AS prior_date
FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
)
SELECT customer_id,order_id,prior_date,order_date,
CAST(julianday(order_date)-julianday(prior_date) AS INTEGER) AS days_since_prior
FROM history ORDER BY customer_id,order_date,order_id;
Output (SQLite practice data):
| customer_id |
order_id |
prior_date |
order_date |
days_since_prior |
| 1 |
101 |
NULL |
2025-01-10 |
NULL |
| 1 |
103 |
2025-01-10 |
2025-02-05 |
26 |
| 2 |
102 |
NULL |
2025-01-20 |
NULL |
| 2 |
106 |
2025-01-20 |
2025-03-15 |
54 |
| 3 |
105 |
NULL |
2025-03-01 |
NULL |
How it works. The first purchase has no prior date, and its gap is NULL. The date subtraction uses SQLite julianday.
Practical use. Create a purchase frequency feature.
Common mistakes. Calculating period changes on raw transactions rather than aggregated periods; dividing by zero; treating missing periods as zero without defining the calendar; using LAST_VALUE with an inappropriate frame; leaking future records into predictors.
Exercise. Calculate a trailing two-month average of completed revenue for available months.
Solution
WITH monthly AS (
SELECT strftime('%Y-%m',order_date) AS month,SUM(amount) AS revenue
FROM orders WHERE status='Completed' GROUP BY strftime('%Y-%m',order_date)
)
SELECT month,revenue,ROUND(AVG(revenue) OVER(ORDER BY month ROWS BETWEEN 1 PRECEDING AND CURRENT ROW),2) AS moving_avg
FROM monthly ORDER BY month;
Output (SQLite practice data):
| month |
revenue |
moving_avg |
| 2025-01 |
160 |
160.0 |
| 2025-02 |
80 |
120.0 |
| 2025-03 |
230 |
155.0 |
How it works. The frame contains this and the preceding available monthly row. Add a calendar when months can be absent.
A named intermediate result helps isolate complexity. Choose its lifetime and storage intentionally.
| Technique |
Lifetime |
Storage / behavior |
| Derived table |
One statement |
Embedded query; optimizer decides |
| CTE |
One statement |
Named query; optimizer decides |
| Ordinary view |
Persistent definition |
Query abstraction, not a separate saved result |
| Temporary table |
Usually session/connection scoped |
Actual temporary object; can be indexed |
| CTAS / SELECT INTO |
Persistent table unless temporary |
Snapshot of query results at creation |
Views can expose only selected columns, provide consistent business definitions, and hide query complexity. Access control still requires appropriate privileges; a view alone is not a complete security boundary. A view can be updated only under engine-specific rules. Materialized views are a separate feature and not treated here. CREATE VIEW, DROP VIEW, and ALTER VIEW or CREATE OR REPLACE VIEW vary by engine. SQLite typically drops and recreates a view to redefine it.
SQLite/PostgreSQL/MySQL support CREATE TABLE copy AS SELECT ...; SQL Server uses SELECT ... INTO copy FROM .... CTAS does not preserve all keys, indexes, defaults or constraints. MySQL CREATE TABLE copy LIKE original creates a structural copy with its own limitations; INSERT INTO copy SELECT ... copies records. Temporary table syntax: SQLite CREATE TEMP TABLE, MySQL/PostgreSQL CREATE TEMPORARY TABLE, SQL Server SELECT ... INTO #temp or CREATE TABLE #temp. Temporary objects may use memory and/or disk; not guaranteed memory-only.
CREATE VIEW completed_orders AS SELECT order_id,customer_id,order_date,amount FROM orders WHERE status='Completed';
Query a view
SELECT customer_id,SUM(amount) AS total FROM completed_orders GROUP BY customer_id ORDER BY customer_id;
Output (SQLite practice data):
| customer_id |
total |
| NULL |
20 |
| 1 |
200 |
| 2 |
100 |
| 3 |
150 |
How it works. The view stores the definition of completed orders and the query aggregates the rows it exposes.
Practical use. Share a standard definition of completed revenue.
SQL Server physical snapshot
Dialect: SQL Server; target table must not exist.
SELECT order_id,customer_id,amount INTO dbo.completed_snapshot FROM dbo.orders WHERE status='Completed';
Expected behavior (illustrative): Six completed order rows copied into a new table. Source constraints and indexes are not copied automatically.
How it works. SELECT INTO creates a physical table, unlike a view.
CREATE TEMP TABLE customer_totals AS SELECT customer_id,SUM(amount) AS total FROM orders WHERE status='Completed' AND customer_id IS NOT NULL GROUP BY customer_id;
Use a session-scoped temporary table
SELECT c.name,t.total FROM customer_totals t JOIN customers c ON c.customer_id=t.customer_id ORDER BY t.total DESC;
Output (SQLite practice data):
| name |
total |
| Ada |
200 |
| Cleo |
150 |
| Ben |
100 |
How it works. The temporary table contains a snapshot of the intermediate result. Other independent statements in the same connection can reuse it.
Practical use. Inspect and reuse an intermediate dataset during analysis.
For a permanent archive, explicitly define schema and constraints if they are important. Example: CREATE TABLE archived_orders AS SELECT * FROM orders WHERE order_date < '2025-03-01'; creates a snapshot. Later source updates do not automatically propagate to that table; a normal view would reflect current data when queried.
Common mistakes. Assuming views cache results or always make queries faster; treating a temp table as visible to all sessions; expecting CTAS to preserve indexes; using CTEs as permanent objects; duplicating raw data without a refresh policy.
Exercise. Create a temporary table of completed March orders and sum its revenue.
Run this preparation in a fresh practice connection:
CREATE TEMP TABLE march_orders AS SELECT * FROM orders WHERE status='Completed' AND order_date>='2025-03-01' AND order_date<'2025-04-01';
Solution
SELECT COUNT(*) AS orders,SUM(amount) AS revenue FROM march_orders;
Output (SQLite practice data):
How it works. The temporary table contains March completed orders including anonymous purchases.
Part VI — Advanced Database Operations
Now consider reusable database-side logic and the physical behavior of a query. These chapters use engine-specific syntax where required.
25. Stored procedures and error handling
A stored procedure is a named routine stored by the database and invoked with parameters. It can combine multiple SQL statements, variables, conditions and error handling. This can centralize operations used by multiple callers. It is not the same as a view or a CTE: a procedure can perform writes, return result sets, or orchestrate several steps. Procedural languages and syntax differ substantially; SQLite has no native stored procedures.
SQL Server uses CREATE PROCEDURE, EXEC, DECLARE, SET, IF ... ELSE, and BEGIN ... END. MySQL uses CREATE PROCEDURE, CALL, parameters such as IN, and a client DELIMITER directive when defining a multi-statement body. DELIMITER is a client command, not ordinary SQL. PostgreSQL uses its own procedure/function language and CALL syntax.
The following examples assume the same logical tables have been created in the specified database engine. SQL Server GO separates client batches in SSMS; it is not a T-SQL statement sent directly through a driver.
Reusable customer revenue procedure
Dialect: SQL Server / SSMS.
CREATE PROCEDURE dbo.CustomerRevenue
@customer_id INT,
@status VARCHAR(20) = 'Completed'
AS
BEGIN
SET NOCOUNT ON;
SELECT customer_id, SUM(amount) AS revenue
FROM dbo.orders
WHERE customer_id = @customer_id AND status = @status
GROUP BY customer_id;
END;
GO
EXEC dbo.CustomerRevenue @customer_id = 1;
Expected behavior (illustrative): customer_id 1, revenue 200, assuming the practice records have been loaded into dbo.orders.
How it works. Parameters constrain the query, and the default status can be overridden.
Practical use. Expose a stable reporting operation to callers.
Equivalent procedure in MySQL
Dialect: MySQL client supporting DELIMITER.
DELIMITER //
CREATE PROCEDURE CustomerRevenue(IN p_customer_id INT)
BEGIN
SELECT customer_id,SUM(amount) AS revenue
FROM orders WHERE customer_id=p_customer_id AND status='Completed'
GROUP BY customer_id;
END//
DELIMITER ;
CALL CustomerRevenue(1);
Expected behavior (illustrative): customer_id 1, revenue 200.
How it works. The IN parameter is distinct from the column name. CALL executes the stored body.
Variables and control flow. A SQL Server routine may use DECLARE @total DECIMAL(12,2); SET @total = ...; IF @total > 100 BEGIN ... END ELSE BEGIN ... END. Inside a procedure, validate inputs and return clear failure information. Use TRY/CATCH to handle errors and avoid leaving a transaction open.
Error handling with transaction rollback
Dialect: SQL Server, fresh session without an enclosing transaction.
BEGIN TRY
BEGIN TRANSACTION;
UPDATE dbo.orders SET amount=amount+10 WHERE order_id=101;
-- Deliberately cause an error for this practice example.
THROW 50001, 'Practice rollback', 1;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
SELECT ERROR_NUMBER() AS error_number, ERROR_MESSAGE() AS error_message,
ERROR_LINE() AS error_line;
END CATCH;
Expected behavior (illustrative): Error 50001 is returned; order 101 remains 120 after rollback.
How it works. The CATCH block handles the deliberately raised error and rolls back the open transaction. In production choose whether to rethrow errors after logging.
Practical use. Make multi-statement write routines recover cleanly.
Remove a practice procedure when finished with DROP PROCEDURE dbo.CustomerRevenue; (SQL Server) or DROP PROCEDURE IF EXISTS CustomerRevenue; (MySQL). Use a fresh practice schema so the name does not collide with existing routines.
Common mistakes. Mixing dialect syntax; confusing parameter and column names; putting arbitrary dynamic SQL into routines; swallowing errors; leaving transactions open; assuming stored procedures are automatically faster.
Exercise. Write a procedure that lists employees from a requested department.
Solution
Dialect: SQL Server / SSMS.
CREATE PROCEDURE dbo.EmployeesByDepartment @department_id INT
AS
BEGIN
SET NOCOUNT ON;
SELECT employee_id,name,salary FROM dbo.employees
WHERE department_id=@department_id ORDER BY employee_id;
END;
GO
EXEC dbo.EmployeesByDepartment @department_id=2;
Expected behavior (illustrative): Dan (60000) and Eva (50000).
26. Triggers and scheduled events
A trigger runs automatically in response to a database event. It can enforce a rule, maintain derived data, or record an audit trail. Unlike a procedure, it is not explicitly called by the application. Keep triggers focused: they add hidden work to the original write and can complicate debugging.
| Operation |
OLD values |
NEW values |
| INSERT |
unavailable |
available |
| UPDATE |
available |
available |
| DELETE |
available |
unavailable |
MySQL and SQLite use row-level OLD/NEW in trigger bodies. MySQL supports BEFORE and AFTER triggers. SQL Server DML triggers run per statement and use inserted and deleted pseudo-tables, which can contain many rows. Never assume a statement affects only one row. SQL Server supports AFTER and INSTEAD OF triggers, not MySQL-style BEFORE syntax.
CREATE TABLE order_audit(order_id INT,old_status TEXT,new_status TEXT);
CREATE TRIGGER audit_order_status AFTER UPDATE OF status ON orders
FOR EACH ROW WHEN OLD.status<>NEW.status
BEGIN
INSERT INTO order_audit VALUES(NEW.order_id,OLD.status,NEW.status);
END;
UPDATE orders SET status='Completed' WHERE order_id=108;
Inspect the audit trail
SELECT * FROM order_audit;
Output (SQLite practice data):
| order_id |
old_status |
new_status |
| 108 |
Pending |
Completed |
How it works. The update causes an automatic insertion into order_audit. This example runs on a disposable practice database.
Practical use. Record changes for operational diagnostics.
Set-based audit trigger
Dialect: SQL Server / SSMS, disposable practice schema.
CREATE TABLE dbo.order_audit (
order_id INT, old_status VARCHAR(20), new_status VARCHAR(20)
);
GO
CREATE TRIGGER dbo.audit_order_status ON dbo.orders
AFTER UPDATE AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.order_audit(order_id,old_status,new_status)
SELECT i.order_id,d.status,i.status
FROM inserted i JOIN deleted d ON i.order_id=d.order_id
WHERE i.status<>d.status;
END;
GO
UPDATE dbo.orders SET status='Completed' WHERE order_id=108;
Expected behavior (illustrative): One audit record: 108, Pending, Completed. Multiple changed rows would generate multiple audit rows.
How it works. The inserted and deleted sets provide before-and-after values, and the join matches the same key.
A MySQL BEFORE trigger can set a derived annual salary using SET NEW.salary = NEW.hourly_pay * 2080; when the schema contains both fields and that annualization rule is valid. AFTER INSERT/DELETE/UPDATE can adjust a salary-expense summary by +NEW.salary, −OLD.salary, or NEW.salary−OLD.salary. Such derived totals require careful handling of NULL, concurrency and corrections; a query may be simpler than storing a redundant value.
Scheduled events (MySQL). Events run on a time schedule rather than responding to row writes. For example, a periodic cleanup of a disposable staging table can be written as follows. The event scheduler must be enabled and the user must have appropriate privileges; do not activate an event until the predicate and retention policy are reviewed.
CREATE EVENT cleanup_demo_stage
ON SCHEDULE EVERY 1 DAY
DO DELETE FROM demo_stage
WHERE created_at < CURRENT_TIMESTAMP - INTERVAL 30 DAY;
-- Assumes demo_stage exists; illustrative MySQL scheduled operation.
-- DROP EVENT cleanup_demo_stage;
Expected: once per scheduled execution, rows older than the chosen retention period are deleted from the demonstration staging table. Use SHOW EVENTS / SHOW TRIGGERS and DROP EVENT / DROP TRIGGER to inspect or remove practice objects in MySQL. An external scheduler is another option in systems without this feature.
Common mistakes. Writing single-row SQL Server triggers; forgetting OLD/NEW availability; automatically deleting production data without a reviewed predicate; assuming an event runs when scheduler is disabled; creating recursive or expensive trigger chains.
Exercise. Create an insert audit trigger that logs IDs of new customers on a disposable SQLite database.
Solution
Dialect: SQLite, fresh practice connection.
CREATE TABLE customer_audit(customer_id INT);
CREATE TRIGGER audit_customer_insert AFTER INSERT ON customers
BEGIN
INSERT INTO customer_audit VALUES(NEW.customer_id);
END;
INSERT INTO customers(customer_id,name) VALUES(6,'New customer');
SELECT * FROM customer_audit;
Expected behavior (illustrative): One row with customer_id 6.
27. Indexes and storage architecture
An index is an additional access structure that can speed up particular searches, joins and ordering operations at the cost of storage and write maintenance. A rowstore engine stores rows on pages; a heap has no clustered index organizing its rows. B-tree-like structures navigate from upper levels to leaf pages; a leaf entry may contain the row itself or a locator depending on the index type. An optimizer may choose a scan instead of an index seek when many rows qualify.
root / search keys
/ \
intermediate intermediate
/ \ / \
leaf leaf leaf leaf
This diagram represents the access structure, not the exact physical pages. SQL Server distinguishes clustered and nonclustered rowstore indexes; clustered index leaf pages contain the table data. A table can have only one clustered index. Nonclustered indexes store keys and row locators (plus optional included columns). Columnstore groups column values and can use compression and batch-mode processing in analytical workloads. Index categories may overlap: a composite index can also be unique or filtered.
| Type |
Appropriate use |
| Single-column |
Frequent selective lookups on one column |
| Composite |
Frequent combined predicates or useful ordering |
| Unique |
Enforce a unique key and support access |
| Filtered / partial |
Subset of rows (SQL Server / PostgreSQL / SQLite syntax differs) |
| Covering |
Contains the columns needed by a query, avoiding additional row lookups |
| Clustered (SQL Server) |
Organize table rowstore data at index leaves |
| Nonclustered (SQL Server) |
Additional access path |
| Columnstore (SQL Server) |
Large analytical scans and aggregations |
A B-tree on (customer_id, order_date) normally supports efficient lookups by customer_id or customer_id plus order_date. Searching by order_date alone may not benefit from a direct leftmost-prefix lookup. Some engines can use other access strategies, such as skip scans, so treat this as a common design principle rather than a universal prohibition. Column order and predicate selectivity matter. Primary/unique keys often have supporting indexes, but a foreign key may need an explicit index depending on the engine.
CREATE INDEX idx_orders_customer_date ON orders(customer_id,order_date);
SELECT order_id,amount FROM orders
WHERE customer_id=1 AND order_date>='2025-02-01';
Composite index lookup result
SELECT order_id,amount FROM orders WHERE customer_id=1 AND order_date>='2025-02-01' ORDER BY order_date,order_id;
Output (SQLite practice data):
| order_id |
amount |
| 103 |
80 |
| 108 |
100 |
How it works. The index key matches the equality prefix followed by the date range. It does not change which rows are returned.
Practical use. Accelerate customer order-history access when justified by the workload.
| SQL Server index examples (illustrative; use separate practice tables and review existing indexes) |
Purpose |
CREATE NONCLUSTERED INDEX idx_orders_date ON dbo.orders(order_date) INCLUDE(amount); |
Cover a date/amount query |
CREATE NONCLUSTERED INDEX idx_completed ON dbo.orders(customer_id) WHERE status='Completed'; |
Filtered index for a recurring subset |
CREATE CLUSTERED INDEX idx_id ON dbo.heap_orders(order_id); |
Cluster a heap table (requires no existing clustered index) |
CREATE COLUMNSTORE INDEX idx_analytics ON dbo.analytics_orders(order_date, amount); |
Nonclustered columnstore on an analytical table |
Inspect indexes with PRAGMA index_list('orders') (SQLite), SHOW INDEXES FROM orders (MySQL), or SQL Server system catalog views. Drop an index with DROP INDEX idx_orders_customer_date in SQLite/PostgreSQL; MySQL ALTER TABLE orders DROP INDEX idx_orders_customer_date; SQL Server DROP INDEX idx_orders_customer_date ON dbo.orders. Avoid redundant or unused indexes, but measure their actual usage and constraints before removing them.
Common mistakes. Indexing every column; ignoring composite order; assuming a seek always wins; using indexes to solve incorrect query grain; dropping unique/constraint-supporting indexes without understanding dependencies.
Exercise. Create an index on product_id for repeated order-item lookups. Inspect the result for product 11.
Run this preparation in a fresh practice connection:
CREATE INDEX idx_item_product ON order_items(product_id);
Solution
SELECT order_id,quantity FROM order_items WHERE product_id=11 ORDER BY order_id;
Output (SQLite practice data):
| order_id |
quantity |
| 101 |
1 |
| 102 |
2 |
| 103 |
4 |
| 106 |
3 |
| 107 |
1 |
How it works. The existing composite key starts with order_id; a product-leading index provides another access path. Execute CREATE INDEX idx_item_product ON order_items(product_id) before the SELECT in a practice database.
28. Execution plans, optimization and partitioning
SQL is declarative: the optimizer chooses a physical plan using metadata, available indexes and statistics. Logical clause order is a correctness model; the physical plan may push down predicates, reorder joins, select a hash join or scan a table. Inspect real plans instead of assuming how the query ran.
SQL text → parse / bind → optimize using statistics and access paths
↓
execution plan
↓
physical operators → result
| Operator |
Meaning |
| Table scan |
Read table data without a selective index access path |
| Index scan |
Read a range or all of an index structure |
| Index seek |
Navigate to a key or key range |
| Nested loops |
Repeatedly find matching rows for outer input |
| Hash join |
Build a hash table on one input and probe with the other |
| Merge join |
Match two suitably ordered inputs |
| Sort |
Order rows; can consume memory and spill |
| Aggregate |
Compute summaries using suitable physical strategy |
Actual SQL Server plans include runtime observations; estimated plans do not execute the query. Inspect estimated vs actual rows, operator costs (estimates, not measured timings), scans/seeks, residual filters, lookups, sorts and spills. SSMS can display both plan types. PostgreSQL EXPLAIN shows the estimated plan; EXPLAIN ANALYZE actually runs the query. MySQL EXPLAIN / EXPLAIN ANALYZE have engine-specific output. SQLite uses EXPLAIN QUERY PLAN. Be careful with actual plans for DML because the statement executes.
Plan before an index
EXPLAIN QUERY PLAN SELECT order_id,amount FROM orders WHERE customer_id=1 AND order_date>='2025-02-01';
Output (SQLite practice data):
| id |
parent |
notused |
detail |
| 2 |
0 |
0 |
SCAN orders |
How it works. SQLite chooses a scan on the baseline with no customer/date index. Plan details and choices are version/data-dependent.
Plan after an index
EXPLAIN QUERY PLAN SELECT order_id,amount FROM orders WHERE customer_id=1 AND order_date>='2025-02-01';
Output (SQLite practice data):
| id |
parent |
notused |
detail |
| 3 |
0 |
0 |
SEARCH orders USING INDEX idx_orders_customer_date (customer_id=? AND order_date>?) |
How it works. SQLite can now search using the composite index. This is a plan demonstration, not a benchmark; the toy dataset is too small to establish a speedup.
Practical use. Verify that a proposed access path is considered.
Performance workflow. Establish the correct result and a baseline; identify a slow query from measurements; inspect plans and statistics; form a hypothesis; change one factor; retest correctness and performance; monitor regression. Useful SQL Server diagnostics include SET STATISTICS IO ON; SET STATISTICS TIME ON; and the execution plan. Turn diagnostics off after use. Plan caching can reuse earlier compiled plans, but parameter distributions and changing data can affect plan suitability.
Practical guidelines:
- Select required columns and filter unnecessary rows; avoid applying functions to indexed filter columns when an equivalent range is possible. E.g.
order_date >= '2025-02-01' AND order_date < '2025-03-01' rather than extracting the month of every row.
- Use correct data types and matching join-key types to avoid implicit conversions.
- Aggregate to the appropriate grain before joining when it avoids unnecessary row expansion. Do not preaggregate if it changes the business result.
- Prefer UNION ALL when deduplication is not needed, and EXISTS for membership when returning all matching pairs is unnecessary.
- Avoid unnecessary sorting, DISTINCT, and repeated computations; investigate correlated subqueries, but don't assume their optimizer implementation.
- Maintain statistics and monitor usage; evaluate fragmentation and page density against the actual workload. SQL Server
ALTER INDEX ... REORGANIZE and ... REBUILD and UPDATE STATISTICS are maintenance commands, not a universal fixed weekly rule. Rebuilds consume resources; use evidence before scheduling.
- SQL Server query hints (e.g.
OPTION (HASH JOIN)) can override optimizer choices; use sparingly after measurement, not as a default.
OLTP vs OLAP. Transactional workloads favor reliable small reads/writes and targeted indexes. Analytical workloads often scan and aggregate large datasets and can benefit from column-oriented storage or partitioning. The same design is not optimal for every workload.
Partitioning. Divide a large table into logical segments by a partition key, often a date. Partition pruning/elimination means the engine can skip irrelevant partitions if the predicate and partition layout permit it. Partitioning also assists lifecycle management; it does not guarantee faster queries, nor automatically distribute data across servers. Parallelism and file placement depend on platform and configuration.
orders by date
├─ before 2025
├─ 2025
└─ 2026 onward
Query 2025 range → potentially access only the 2025 partition
SQL Server uses a partition function to define ranges and a partition scheme to map ranges onto filegroups. A partition key is included in the table/index layout as appropriate. Use a disposable database for the following illustrative DDL; ALL TO PRIMARY keeps the example simple, not a recommendation for physical distribution.
CREATE PARTITION FUNCTION pf_order_date (DATE)
AS RANGE RIGHT FOR VALUES ('2025-01-01','2026-01-01');
CREATE PARTITION SCHEME ps_order_date
AS PARTITION pf_order_date ALL TO ([PRIMARY]);
CREATE TABLE dbo.partitioned_orders (
order_id INT NOT NULL,
order_date DATE NOT NULL,
amount DECIMAL(10,2)
) ON ps_order_date(order_date);
-- Load data, then inspect a plan for the range predicate:
SELECT order_id,amount FROM dbo.partitioned_orders
WHERE order_date>='2025-01-01' AND order_date<'2026-01-01';
Expected behavior: rows with dates in 2025 belong to the middle partition. If rows are loaded and the engine can eliminate partitions, the query need not scan other date ranges. The empty table as created returns no rows; no performance claim is made. PostgreSQL declarative partitioning and MySQL partition syntax are different.
Common mistakes. Optimizing before validating output; interpreting estimated costs as measured latency; testing on unrepresentative data; overindexing; wrapping filter keys in expressions unnecessarily; assuming partitioning or hints always improve performance.
Exercise. Rewrite a query using strftime on the order_date column to use a sargable February date range, then inspect the plan with an index.
Run this preparation in a fresh practice connection:
CREATE INDEX idx_order_date ON orders(order_date);
Solution
EXPLAIN QUERY PLAN SELECT order_id,amount FROM orders
WHERE order_date>='2025-02-01' AND order_date<'2025-03-01';
Output (SQLite practice data):
| id |
parent |
notused |
detail |
| 3 |
0 |
0 |
SEARCH orders USING INDEX idx_order_date (order_date>? AND order_date<?) |
How it works. The range can use the date index. Execute CREATE INDEX idx_order_date ON orders(order_date) in your practice database before inspecting. Confirm equivalent result rows with and without the index.
Part VII — Real-World Applications
Bring the concepts together in data engineering and analysis workflows. The following small projects are intentionally synthetic and can be reproduced without downloading a large dataset.
29. ETL, data engineering and warehousing
Operational databases typically support applications and transactions (OLTP). A data warehouse integrates data from source systems for analytical queries (OLAP). A business may have separate CRM, ERP, sales and other systems; a warehouse can provide a consistent analytical view of the business. A data mart serves a subject area such as sales. Integration requires agreed identifiers, data quality rules, definitions and ownership.
| Concept |
Meaning |
| ETL |
Extract, transform, then load prepared data into a target |
| ELT |
Extract, load raw data, then transform in the target environment |
| Full load |
Replace or ingest a complete source snapshot |
| Incremental load |
Process new or changed records since a known boundary |
| Batch |
Process a defined collection of records at intervals |
| Streaming |
Process continuously arriving events with appropriate latency guarantees |
| Fact table |
Stores measurable events at a defined grain |
| Dimension table |
Stores descriptive context, such as product or customer |
| Slowly changing dimension |
Manages changes to descriptive attributes; overwrite or preserve history according to business needs |
A fact's grain answers “what does one row represent?” In a sales model, one row may represent an order line. Dimensions provide context for filtering and grouping that fact. A star schema places a fact at the center of related dimensions. A fact table can contain multiple measures and foreign keys; it need not be a single preaggregated KPI. A snowflake schema separates some dimension attributes into additional related tables.
dim_customer
|
dim_product — fact_sales — dim_date
|
dim_channel
The schema is conceptual; a small project need not build every dimension. Operational and dimensional models make different tradeoffs: an analytical model may intentionally denormalize descriptions for easier reporting, while operational schemas often reduce duplication to protect updates.
Data architectures include data warehouses (structured analytical data), data lakes (large collections of data in varied formats), lakehouses (lake storage with warehouse-like table and management capabilities), and data mesh (domain-oriented ownership and data products, not simply a storage engine). Warehouse design approaches include Inmon (enterprise warehouse before marts), Kimball (dimensional marts with conformed dimensions), Data Vault (historical integration with raw/business layers), and medallion (progressive refinement of data quality). These are broad descriptions; implementation details vary.
From raw to business-ready: medallion architecture
CRM / ERP / CSV extracts
↓ ingest
Bronze — raw records, source metadata, traceability
↓ validate, standardize, deduplicate
Silver — cleaned, typed, integrated records
↓ apply business logic and dimensional modeling
Gold — business-ready facts, dimensions, KPIs, ML-ready datasets
↓
Reports, analytics, models and downstream applications
Bronze preserves the original information; Silver handles cleaning and integration; Gold applies agreed business definitions. Define naming conventions and data grain, document transformations, test each layer, and version-control SQL scripts. A practical miniature demonstration follows. It is a teaching design, not a production-ready warehouse: the raw extract is synthetic, refresh is a full rebuild, and there is no scheduler, incremental merge or production monitoring.
Runnable miniature (SQLite). Here amount_text is deliberately restricted to known decimal strings or blank; general dirty numeric input must be validated before CAST. A duplicate is defined as a repeated source order ID, and the later raw ID wins. This assumption is valid only for this toy extract.
CREATE TABLE bronze_sales (raw_id INT PRIMARY KEY, source_order_id INT, customer_id INT, amount_text TEXT, status_text TEXT);
INSERT INTO bronze_sales VALUES
(1,201,1,' 25.00 ',' completed '),
(2,202,2,'40.00','COMPLETED'),
(3,202,2,'40.00','COMPLETED'),
(4,203,3,'15.00','cancelled'),
(5,204,1,'','completed');
CREATE TABLE silver_sales AS
WITH standardized AS (
SELECT raw_id,source_order_id,customer_id,
NULLIF(TRIM(amount_text),'') AS amount_text,
LOWER(TRIM(status_text)) AS status
FROM bronze_sales
), dedup AS (
SELECT *,ROW_NUMBER() OVER(PARTITION BY source_order_id ORDER BY raw_id DESC) AS rn
FROM standardized
)
SELECT source_order_id,customer_id,CAST(amount_text AS DECIMAL(10,2)) AS amount,status
FROM dedup WHERE rn=1 AND amount_text IS NOT NULL;
CREATE VIEW gold_customer_sales AS
SELECT c.customer_id,c.name,COUNT(s.source_order_id) AS completed_orders,
COALESCE(SUM(s.amount),0) AS revenue
FROM customers c LEFT JOIN silver_sales s ON c.customer_id=s.customer_id AND s.status='completed'
GROUP BY c.customer_id,c.name;
Inspect the Silver layer
SELECT * FROM silver_sales ORDER BY source_order_id;
Output (SQLite practice data):
| source_order_id |
customer_id |
amount |
status |
| 201 |
1 |
25 |
completed |
| 202 |
2 |
40 |
completed |
| 203 |
3 |
15 |
cancelled |
How it works. Five raw records become three clean order records: one duplicate and one blank amount are excluded. The raw records remain available.
Practical use. Check transformation decisions independently of reporting.
Inspect the Gold layer
SELECT * FROM gold_customer_sales ORDER BY customer_id;
Output (SQLite practice data):
| customer_id |
name |
completed_orders |
revenue |
| 1 |
Ada |
1 |
25 |
| 2 |
Ben |
1 |
40 |
| 3 |
Cleo |
0 |
0 |
| 4 |
Dina |
0 |
0 |
| 5 |
Eli |
0 |
0 |
How it works. Gold counts completed orders only and retains every customer. Cancelled orders are excluded; zero revenue is appropriate here for no qualifying sale.
Practical use. Provide a customer-level dataset for reporting.
Validate the layers
SELECT (SELECT COUNT(*) FROM bronze_sales) AS raw_rows,
(SELECT COUNT(*) FROM silver_sales) AS clean_rows,
(SELECT COUNT(DISTINCT source_order_id) FROM silver_sales) AS unique_orders,
(SELECT SUM(amount) FROM silver_sales WHERE status='completed') AS silver_completed,
(SELECT SUM(revenue) FROM gold_customer_sales) AS gold_revenue;
Output (SQLite practice data):
| raw_rows |
clean_rows |
unique_orders |
silver_completed |
gold_revenue |
| 5 |
3 |
3 |
65 |
65 |
How it works. The clean key should be unique, and completed revenue should reconcile between layers. This works because every valid completed source customer is present in the customer dimension.
For incremental loads, define a watermark or change-tracking mechanism; handle late arrivals and corrections; avoid reprocessing duplicates; and decide how deletes are represented. Re-running a load should not silently double-count facts. The illustrative pipeline uses CREATE TABLE and is intentionally executed once in a fresh database. Production refresh procedures must define repeatable load semantics. Slowly changing dimensions can overwrite current attributes (Type 1) or retain versioned historical rows (Type 2); for a historical join, choose the appropriate effective version. Those are design choices, not implemented here.
Import/export and orchestration. SQLite supports CSV import in its shell, MySQL and Workbench offer import tools, SQL Server has bulk load/restore workflows, and PostgreSQL supports COPY/client \copy. In psql, \copy table_name FROM 'local.csv' WITH (FORMAT csv, HEADER true); uses a local client file, whereas server-side COPY requires server-accessible files and permissions. Load into staging with the right column order, delimiter and encoding; inspect row counts and parse failures before promoting records. Avoid mixing a client command with an ordinary SQL driver API.
Common mistakes. Treating all source records as clean; overwriting Bronze; using incompatible facts/grains in one table; double-counting incremental loads; discarding records without an audit rule; expecting architectural labels to replace data validation.
Exercise. Check for duplicate source order keys in the Silver layer.
Solution
SELECT source_order_id,COUNT(*) AS n FROM silver_sales GROUP BY source_order_id HAVING COUNT(*)>1;
Output (SQLite practice data):
(0 rows; columns: source_order_id, n)
How it works. An empty result is the desired validation outcome. Run the warehouse setup above in a fresh SQLite connection.
30. Practical SQL projects and interview preparation
The point of a project is to answer a well-defined question from raw tables, not to demonstrate as many SQL functions as possible. For each analysis, identify the grain, define the metric, explore the inputs, construct the query incrementally, inspect the output and validate the result. The projects below combine the preceding concepts. All datasets are fictional; no result should be interpreted as a real market statistic.
Project A — Job-market and skill analytics
Business question. Which jobs pay most, which skills are common, and which skills balance demand and compensation? Use a fact table of job postings, company and skill dimensions, and a many-to-many junction linking jobs to skills. The salary is yearly; the data is synthetic. Skills are counted once per job.
CREATE TABLE company_dim (company_id INT NOT NULL PRIMARY KEY, name TEXT);
CREATE TABLE job_postings_fact (job_id INT NOT NULL PRIMARY KEY,company_id INT REFERENCES company_dim(company_id),job_title TEXT,salary_year_avg DECIMAL(12,2),job_location TEXT,posted_date TEXT);
CREATE TABLE skills_dim (skill_id INT NOT NULL PRIMARY KEY,skill TEXT);
CREATE TABLE skills_job_dim (job_id INT NOT NULL REFERENCES job_postings_fact(job_id),skill_id INT NOT NULL REFERENCES skills_dim(skill_id),PRIMARY KEY(job_id,skill_id));
INSERT INTO company_dim VALUES (1,'Northstar'),(2,'Atlas'),(3,'Orion');
INSERT INTO job_postings_fact VALUES
(1,1,'Data Analyst',80000,'Remote','2025-01-01'),
(2,2,'Data Analyst',100000,'Remote','2025-01-02'),
(3,1,'Data Analyst',60000,'Onsite','2025-01-03'),
(4,3,'Data Analyst',120000,'Remote','2025-02-01'),
(5,2,'Data Analyst',NULL,'Remote','2025-02-02'),
(6,3,'ML Engineer',140000,'Remote','2025-02-03');
INSERT INTO skills_dim VALUES (1,'SQL'),(2,'Python'),(3,'Excel'),(4,'Tableau'),(5,'Spark');
INSERT INTO skills_job_dim VALUES (1,1),(1,3),(2,1),(2,2),(3,1),(3,4),(4,1),(4,2),(4,5),(5,1),(5,4),(6,2),(6,5);
Analysis scope. Restrict to remote Data Analyst postings. Demand counts every eligible posting with the skill; salary averages count only postings with known salaries. A job with multiple skills contributes to each skill's average, not multiple times to the overall job average.
A1. Highest-paying eligible jobs
SELECT j.job_id,c.name AS company,j.salary_year_avg
FROM job_postings_fact j JOIN company_dim c ON j.company_id=c.company_id
WHERE j.job_title='Data Analyst' AND j.job_location='Remote' AND j.salary_year_avg IS NOT NULL
ORDER BY j.salary_year_avg DESC,j.job_id LIMIT 3;
Output (SQLite practice data):
| job_id |
company |
salary_year_avg |
| 4 |
Orion |
120000 |
| 2 |
Atlas |
100000 |
| 1 |
Northstar |
80000 |
How it works. Filter role and remote location before sorting known salaries.
Practical use. Find top-paying opportunities.
A2. Skills associated with the highest-paying jobs
WITH top_jobs AS (
SELECT job_id,salary_year_avg FROM job_postings_fact
WHERE job_title='Data Analyst' AND job_location='Remote' AND salary_year_avg IS NOT NULL
ORDER BY salary_year_avg DESC,job_id LIMIT 2
)
SELECT t.job_id,t.salary_year_avg,s.skill FROM top_jobs t
JOIN skills_job_dim sj ON sj.job_id=t.job_id JOIN skills_dim s ON s.skill_id=sj.skill_id
ORDER BY t.salary_year_avg DESC,s.skill;
Output (SQLite practice data):
| job_id |
salary_year_avg |
skill |
| 4 |
120000 |
Python |
| 4 |
120000 |
SQL |
| 4 |
120000 |
Spark |
| 2 |
100000 |
Python |
| 2 |
100000 |
SQL |
How it works. Select top jobs at job grain first, then expand to skills. Applying LIMIT after the join would select skill rows instead of jobs.
A3. Most in-demand skills
SELECT s.skill,COUNT(DISTINCT j.job_id) AS demand
FROM job_postings_fact j JOIN skills_job_dim sj ON j.job_id=sj.job_id
JOIN skills_dim s ON s.skill_id=sj.skill_id
WHERE j.job_title='Data Analyst' AND j.job_location='Remote'
GROUP BY s.skill_id,s.skill ORDER BY demand DESC,s.skill;
Output (SQLite practice data):
| skill |
demand |
| SQL |
4 |
| Python |
2 |
| Excel |
1 |
| Spark |
1 |
| Tableau |
1 |
How it works. Count distinct job IDs per skill, including jobs with missing salary. The junction key prevents repeated job/skill pairs.
A4. Highest average salary by skill
SELECT s.skill,COUNT(j.salary_year_avg) AS known_salaries,ROUND(AVG(j.salary_year_avg),2) AS avg_salary
FROM job_postings_fact j JOIN skills_job_dim sj ON j.job_id=sj.job_id
JOIN skills_dim s ON s.skill_id=sj.skill_id
WHERE j.job_title='Data Analyst' AND j.job_location='Remote' AND j.salary_year_avg IS NOT NULL
GROUP BY s.skill_id,s.skill ORDER BY avg_salary DESC,s.skill;
Output (SQLite practice data):
| skill |
known_salaries |
avg_salary |
| Spark |
1 |
120000.0 |
| Python |
2 |
110000.0 |
| SQL |
3 |
100000.0 |
| Excel |
1 |
80000.0 |
How it works. The average excludes unknown salaries. Report the sample count so one high-paying posting does not appear more reliable than it is.
A5. Balance demand and salary
WITH demand AS (
SELECT sj.skill_id,COUNT(DISTINCT j.job_id) AS demand
FROM job_postings_fact j JOIN skills_job_dim sj ON j.job_id=sj.job_id
WHERE j.job_title='Data Analyst' AND j.job_location='Remote' GROUP BY sj.skill_id
), salaries AS (
SELECT sj.skill_id,AVG(j.salary_year_avg) AS avg_salary,COUNT(j.salary_year_avg) AS n_salary
FROM job_postings_fact j JOIN skills_job_dim sj ON j.job_id=sj.job_id
WHERE j.job_title='Data Analyst' AND j.job_location='Remote' AND j.salary_year_avg IS NOT NULL GROUP BY sj.skill_id
)
SELECT s.skill,d.demand,ROUND(a.avg_salary,2) AS avg_salary,a.n_salary
FROM demand d JOIN salaries a ON d.skill_id=a.skill_id JOIN skills_dim s ON s.skill_id=d.skill_id
WHERE d.demand>=2 AND a.n_salary>=2 ORDER BY avg_salary DESC,d.demand DESC,s.skill;
Output (SQLite practice data):
| skill |
demand |
avg_salary |
n_salary |
| Python |
2 |
110000.0 |
2 |
| SQL |
4 |
100000.0 |
3 |
How it works. Demand and known-salary counts have different denominators. The thresholds are illustrative, not an industry recommendation.
Validate: Check for duplicate job IDs, duplicate junction keys, role/location filter consistency and missing salaries. Use larger samples before interpreting salary rankings. A salary associated with a skill does not establish that the skill caused the salary.
Project B — Cleaning and exploratory analysis of company layoffs
Business question. How many reported layoffs occurred by month, industry and company? Data may contain duplicates, blanks, inconsistent names, missing metrics and date text. Do not overwrite raw records or add percentages across companies. The following synthetic data uses ISO dates to keep SQLite examples runnable; if an input uses MM/DD/YYYY, parse it explicitly with the engine’s date conversion functions first.
CREATE TABLE layoffs_raw(row_id INT PRIMARY KEY,company TEXT,location TEXT,industry TEXT,total_laid_off INT,percentage_laid_off REAL,event_date TEXT,stage TEXT,country TEXT,funds_raised INT);
INSERT INTO layoffs_raw VALUES
(1,' Atlas ','Berlin','CryptoCurrency',100,0.1,'2025-01-10','Series B','Germany',80),
(2,'Atlas','Berlin','Crypto',100,0.1,'2025-01-10','Series B','Germany',80),
(3,'Beacon','New York','',40,0.2,'2025-01-20','Series A','United States.',20),
(4,'Beacon','New York','Retail',60,0.3,'2025-02-01','Series A','United States',20),
(5,'Cedar','London','Tech',150,1.0,'2025-02-10','Post IPO','UK',200),
(6,'Cedar','London','Tech',20,NULL,'2025-03-01','Post IPO','UK',200),
(7,'Delta','Paris','Retail',NULL,NULL,'2025-03-05','Series C','France',50),
(8,'Elm','Paris','Retail',50,0.1,'2025-03-09','Series C','France',40);
CREATE TABLE layoffs_clean AS
WITH normalized AS (
SELECT row_id,TRIM(company) AS company,TRIM(location) AS location,
CASE WHEN LOWER(TRIM(industry)) LIKE 'crypto%' THEN 'Crypto' ELSE NULLIF(TRIM(industry),'') END AS industry,
total_laid_off,percentage_laid_off,event_date,stage,RTRIM(TRIM(country),'.') AS country,funds_raised
FROM layoffs_raw
), ranked AS (
SELECT *,ROW_NUMBER() OVER(PARTITION BY company,location,industry,total_laid_off,percentage_laid_off,event_date,stage,country,funds_raised ORDER BY row_id) AS rn
FROM normalized
), dedup AS (SELECT * FROM ranked WHERE rn=1),
known_industry AS (
SELECT company,location,MAX(industry) AS industry FROM dedup WHERE industry IS NOT NULL
GROUP BY company,location HAVING COUNT(DISTINCT industry)=1
)
SELECT d.row_id,d.company,d.location,COALESCE(d.industry,k.industry) AS industry,
d.total_laid_off,d.percentage_laid_off,d.event_date,d.stage,d.country,d.funds_raised
FROM dedup d LEFT JOIN known_industry k ON d.company=k.company AND d.location=k.location
WHERE d.total_laid_off IS NOT NULL OR d.percentage_laid_off IS NOT NULL;
B1. Inspect cleaned records
SELECT company,industry,total_laid_off,percentage_laid_off,event_date,country FROM layoffs_clean ORDER BY event_date,company;
Output (SQLite practice data):
| company |
industry |
total_laid_off |
percentage_laid_off |
event_date |
country |
| Atlas |
Crypto |
100 |
0.1 |
2025-01-10 |
Germany |
| Beacon |
Retail |
40 |
0.2 |
2025-01-20 |
United States |
| Beacon |
Retail |
60 |
0.3 |
2025-02-01 |
United States |
| Cedar |
Tech |
150 |
1.0 |
2025-02-10 |
UK |
| Cedar |
Tech |
20 |
NULL |
2025-03-01 |
UK |
| Elm |
Retail |
50 |
0.1 |
2025-03-09 |
France |
How it works. Standardize before deduplication, rank on all relevant source fields, fill an industry only when company/location has one known industry, and retain rows with at least one metric. The known-industry rule is a business assumption for the synthetic data.
B2. Validate cleaning
SELECT (SELECT COUNT(*) FROM layoffs_raw) AS raw_rows,
(SELECT COUNT(*) FROM layoffs_clean) AS clean_rows,
(SELECT COUNT(*) FROM layoffs_clean WHERE industry IS NULL) AS missing_industry,
(SELECT SUM(total_laid_off) FROM layoffs_clean) AS reported_total;
Output (SQLite practice data):
| raw_rows |
clean_rows |
missing_industry |
reported_total |
| 8 |
6 |
0 |
420 |
How it works. Eight raw rows become six analytical rows: one duplicate and one unusable record are removed. The total is of known reported counts, not an estimate of all layoffs.
B3. Compare industry and country totals
SELECT industry,country,SUM(total_laid_off) AS reported_layoffs
FROM layoffs_clean GROUP BY industry,country ORDER BY reported_layoffs DESC,industry,country;
Output (SQLite practice data):
| industry |
country |
reported_layoffs |
| Tech |
UK |
170 |
| Crypto |
Germany |
100 |
| Retail |
United States |
100 |
| Retail |
France |
50 |
How it works. Group by both dimensions. Counts can be summed for distinct events, but percentages require compatible denominators.
B4. Monthly trend and rolling total
WITH monthly AS (
SELECT SUBSTR(event_date,1,7) AS month,SUM(total_laid_off) AS monthly_total
FROM layoffs_clean GROUP BY SUBSTR(event_date,1,7)
)
SELECT month,monthly_total,SUM(monthly_total) OVER(ORDER BY month ROWS UNBOUNDED PRECEDING) AS cumulative
FROM monthly ORDER BY month;
Output (SQLite practice data):
| month |
monthly_total |
cumulative |
| 2025-01 |
140 |
140 |
| 2025-02 |
210 |
350 |
| 2025-03 |
70 |
420 |
How it works. Aggregate event records to month grain, then accumulate monthly totals.
B5. Highest-layoff companies per year
WITH yearly AS (
SELECT SUBSTR(event_date,1,4) AS year,company,SUM(total_laid_off) AS total
FROM layoffs_clean GROUP BY SUBSTR(event_date,1,4),company
), ranked AS (
SELECT *,DENSE_RANK() OVER(PARTITION BY year ORDER BY total DESC) AS company_rank FROM yearly
)
SELECT year,company,total,company_rank FROM ranked WHERE company_rank<=2 ORDER BY year,company_rank,company;
Output (SQLite practice data):
| year |
company |
total |
company_rank |
| 2025 |
Cedar |
170 |
1 |
| 2025 |
Atlas |
100 |
2 |
| 2025 |
Beacon |
100 |
2 |
How it works. Aggregate before ranking. Ties can yield more than two companies. In a full EDA, also inspect date range, extremes, 100% layoffs and totals by funding stage and year.
Validate: Confirm that standardized labels reflect the same real category, not merely similar spelling; dates parse correctly; no duplicates remain at the chosen grain; missing total counts are not silently treated as 0. A 100% layoff is a company-level proportion and cannot be added to another company’s percentage. Without employee denominators, a population-wide layoff rate cannot be calculated reliably.
Project C — Build an analytical customer dataset
Business question. At the end of February 2025, create one row per customer with historical completed order count, revenue, average order value, most recent purchase, and a customer segment. This resembles a feature table for analytics or machine learning. The cutoff is exclusive and all features use only earlier observations.
C1. Customer-level snapshot
WITH historical AS (
SELECT customer_id,order_date,amount FROM orders
WHERE status='Completed' AND order_date<'2025-03-01' AND customer_id IS NOT NULL
), aggregated AS (
SELECT customer_id,COUNT(*) AS purchase_count,SUM(amount) AS revenue,
AVG(amount) AS avg_order_value,MAX(order_date) AS last_purchase
FROM historical GROUP BY customer_id
)
SELECT c.customer_id,c.name,COALESCE(a.purchase_count,0) AS purchases,
COALESCE(a.revenue,0) AS revenue,ROUND(a.avg_order_value,2) AS avg_order_value,
a.last_purchase,
CASE WHEN a.customer_id IS NULL THEN 'Inactive' WHEN a.revenue>=100 THEN 'High' ELSE 'Standard' END AS segment
FROM customers c LEFT JOIN aggregated a ON c.customer_id=a.customer_id ORDER BY c.customer_id;
Output (SQLite practice data):
| customer_id |
name |
purchases |
revenue |
avg_order_value |
last_purchase |
segment |
| 1 |
Ada |
2 |
200 |
100.0 |
2025-02-05 |
High |
| 2 |
Ben |
1 |
40 |
40.0 |
2025-01-20 |
Standard |
| 3 |
Cleo |
0 |
0 |
NULL |
NULL |
Inactive |
| 4 |
Dina |
0 |
0 |
NULL |
NULL |
Inactive |
| 5 |
Eli |
0 |
0 |
NULL |
NULL |
Inactive |
How it works. The CTE establishes an as-of cutoff and aggregates before joining, avoiding order-line expansion. No purchases legitimately means count/revenue zero; average and recency remain unknown for those customers.
Practical use. Build a reporting snapshot or an as-of-date ML feature table.
For a real model, dimension attributes such as points must also be available as of the cutoff; avoid using a current customer attribute if it changed after the observation date. Targets must use a distinct future horizon, and feature selection/preprocessing must respect the evaluation split. This is a small applied caveat, not a separate ML course.
Using AI assistance without surrendering correctness
An AI assistant can explain unfamiliar syntax, propose queries, generate synthetic test data, suggest troubleshooting steps, and review a plan. Give it the dialect/version, schema, grain, sample rows, required output, NULL/tie rules and constraints. Ask it to explain the query and identify edge cases. Do not provide real credentials, confidential customer records or other unnecessary sensitive data. Never run generated destructive statements without reviewing the affected rows and transaction behavior. Validate actual outputs and plans independently.
Example prompt: “Use SQL Server syntax. Given orders(order_id, customer_id, amount, status, order_date), return one row per customer with the top two distinct completed order amounts in 2025. Explain how ties and NULL values are handled. Show a CTE, expected output for a small synthetic dataset, and common mistakes. Do not write or delete data.”
The exact requirement “one row per customer with top two distinct amounts” needs either separate output columns or a nested/aggregated representation, not simply two ranked rows. A good assistant should identify that ambiguity rather than invent a result shape.
Common mistakes. Ignoring metric definitions, choosing the wrong grain, silently excluding NULLs, reporting unrepresentative sample findings as real results, letting a join duplicate facts, leaking future data into features, or accepting AI-generated SQL without verification.
Exercise. Interview challenge: return all customers, their number of completed orders, and completed revenue, then rank them by revenue (ties share a dense rank).
Solution
WITH summary AS (
SELECT c.customer_id,c.name,COUNT(o.order_id) AS completed_orders,
COALESCE(SUM(o.amount),0) AS revenue
FROM customers c LEFT JOIN orders o ON o.customer_id=c.customer_id AND o.status='Completed'
GROUP BY c.customer_id,c.name
)
SELECT name,completed_orders,revenue,DENSE_RANK() OVER(ORDER BY revenue DESC) AS revenue_rank
FROM summary ORDER BY revenue_rank,customer_id;
Output (SQLite practice data):
| name |
completed_orders |
revenue |
revenue_rank |
| Ada |
2 |
200 |
1 |
| Cleo |
1 |
150 |
2 |
| Ben |
2 |
100 |
3 |
| Dina |
0 |
0 |
4 |
| Eli |
0 |
0 |
4 |
How it works. The outer join keeps inactive customers, GROUP BY establishes the grain, and the window ranks summaries. The final tie-break orders equal ranks deterministically without changing their ranks.
Closing thought: learn to diagnose the query
A professional SQL workflow is less about memorizing the entire language than combining the right tools with a defensible understanding of the data. When a result looks wrong, first ask what a row means and whether a join has changed the grain. When a query is slow, measure and inspect its plan before adding indexes. When changing data, preview the affected rows and use appropriate transactions. When preparing analytical or ML data, define missingness and time cutoffs explicitly.
| Requirement |
Think first about |
| Retrieve rows/columns |
SELECT, WHERE, ORDER BY |
| Summarize records |
GROUP BY, aggregate functions, HAVING |
| Combine related tables |
JOIN, keys, cardinality, grain |
| Compare datasets |
UNION, INTERSECT, EXCEPT, anti joins |
| Break down complexity |
Subqueries, CTEs, views, temporary tables |
| Calculate across rows |
Window partitions, ordering, frames |
| Improve data quality |
Staging, text/date/NULL transforms, deterministic deduplication |
| Persist reliable changes |
Constraints, transactions, procedures |
| Improve performance |
Correct query, measured plan, targeted indexes, partitioning if justified |
| Build a data product |
Defined grain, transformations, validation and reproducibility |
Start with the baseline tables. Change one query at a time, predict its result before running it, and compare the actual output with the expected output. Once the mechanics become intuitive, practice combining several concepts to solve a real business question. That is how syntax becomes working SQL knowledge.
Scope boundary. This guide concentrates on everyday SQL through advanced analytical and database operations. It introduces transactions, security, dimensional modeling and architecture but does not attempt to be a full database administration manual; advanced isolation/locking, replication, recovery, formal normalization, vendor-specific security and specialized features are deliberately outside its detailed scope. The warehouse pipeline is an explicitly small teaching implementation rather than a complete enterprise warehouse.