Reading Room · SQL Catalog
LivePreparation SQL Engine · 48 Presets · 4 Databases

See SQL Execute One Clause at a Time

SQL reads top to bottom, but evaluates along relational order — FROM, JOIN, WHERE, GROUP BY, HAVING, WINDOW, SELECT, ORDER BY, LIMIT. Inspect each intermediate stage below or open any query inside the full Studio.

Live Client-Side Query Pipeline · Powered by LivePreparation SQL Engine

Evaluated Stage Order5 stages
SELECT u.name, d.name AS department, u.salary
FROM users u
INNER JOIN departments d ON u.department_id = d.id
WHERE u.salary >= 80000
ORDER BY u.salary DESC;
Working Relation

SOURCE: USERS

10 in → 10 out

Scanned 10 rows from table 'users'.

#idnamedepartment_idrolestate
11Alice Smith1Software Engineerkeep
22Bob Jones2Product Managerkeep
33Charlie Lee1Software Engineerkeep
44Diana Prince3UX Designerkeep
55Evan Wright2Data Analystkeep
66Fiona Gallagher1Tech Leadkeep
Showing top working rows for FROMAnimate this query
Select any logical stage on the left to observe real working-memory input counts, kept tuples, and discarded rows from the local company database.
Worked Examples · 48 Presets

Explore by Concept or Search Clauses

Basics

1. Pick columns and compute new ones

FROM reads the table first; SELECT only shapes the columns afterwards. Aliases are created at the very end.

SELECT name, salary, salary / 12 AS monthly
FROM users;
Basics

2. Filtering with WHERE

WHERE tests every row and drops the ones that are not TRUE, then ORDER BY sorts what is left.

SELECT name, role, salary, country
FROM users
WHERE salary >= 85000
ORDER BY salary DESC;
Basics

3. AND binds tighter than OR

Without parentheses this means: USA, or (UK and salary over 100k). Watch which rows survive.

SELECT name, country, salary
FROM users
WHERE country = 'USA' OR country = 'UK' AND salary > 100000;
Basics

4. IN, BETWEEN and LIKE

Three shortcuts for common tests: a list of values, an inclusive range, and a text pattern.

SELECT name, country, salary
FROM users
WHERE country IN ('UK', 'Canada')
  AND salary BETWEEN 70000 AND 140000
  AND name LIKE '%a%';
Basics

5. NULL is not equal to anything

George has no department. "department_id != 1" is unknown for him, and WHERE only keeps TRUE, so he vanishes.

SELECT name, department_id
FROM users
WHERE department_id != 1;
Basics

6. Finding NULLs with IS NULL

Use IS NULL (never = NULL) to find missing values.

SELECT name, role, department_id
FROM users
WHERE department_id IS NULL;
Basics

7. DISTINCT removes repeated rows

DISTINCT runs after SELECT, so it compares the final column values.

SELECT DISTINCT country
FROM users
ORDER BY country;
Basics

8. ORDER BY, LIMIT and OFFSET

Sort first, skip two rows, then take three. LIMIT is always the last step.

SELECT name, salary
FROM users
ORDER BY salary DESC
LIMIT 3 OFFSET 2;
Expressions

9. CASE: if/else inside SQL

CASE picks the first matching branch for each row, perfect for turning numbers into labels.

SELECT name, salary,
       CASE
         WHEN salary >= 130000 THEN 'Senior'
         WHEN salary >= 90000 THEN 'Mid'
         ELSE 'Junior'
       END AS level
FROM users
ORDER BY salary DESC;
Expressions

10. Text functions

UPPER, SUBSTR, LENGTH and || (concatenate) are evaluated row by row during SELECT.

SELECT UPPER(name) AS shout,
       SUBSTR(role, 1, 3) AS short_role,
       LENGTH(name) AS name_length,
       name || ' (' || country || ')' AS label
FROM users;
Expressions

11. COALESCE fills in NULLs

COALESCE returns its first non-NULL argument, a clean way to supply defaults.

SELECT name,
       department_id,
       COALESCE(department_id, 0) AS dept_or_zero,
       IIF(department_id IS NULL, 'unassigned', 'assigned') AS status
FROM users;
Joins

12. INNER JOIN (Users & Departments)

Each user is paired with the department row whose id matches. Rows without a partner are dropped.

SELECT users.name, users.role, departments.name AS dept_name, departments.location
FROM users
JOIN departments ON users.department_id = departments.id
WHERE departments.budget > 300000;
Joins

13. LEFT JOIN (Users & Orders)

Every user is kept. Users with no orders get NULLs on the order side instead of disappearing.

SELECT users.name, orders.product_name, orders.amount, orders.status
FROM users
LEFT JOIN orders ON users.id = orders.user_id
ORDER BY orders.amount DESC;
Joins

14. RIGHT JOIN keeps the other side

Marketing has no employees, but a RIGHT JOIN keeps every department and fills the user side with NULL.

SELECT d.name AS department, u.name AS employee
FROM users u
RIGHT JOIN departments d ON u.department_id = d.id
ORDER BY d.name, u.name;
Joins

15. FULL JOIN keeps both sides

Unmatched rows from either table survive: George (no department) and Marketing (no staff).

SELECT u.name AS employee, d.name AS department
FROM users u
FULL JOIN departments d ON u.department_id = d.id;
Joins

16. Anti-join: who has no orders?

LEFT JOIN, then keep only the rows where the right side is NULL. A classic way to find "missing" things.

SELECT u.name
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE o.id IS NULL;
Joins

17. Chaining three tables

Joins run left to right. The result of the first join becomes the input of the second.

SELECT u.name, o.product_name, p.category, o.amount
FROM users u
JOIN orders o ON o.user_id = u.id
JOIN products p ON p.name = o.product_name
WHERE o.status = 'Completed';
Joins

18. Self join: pairs of teammates

A table can join itself by using two aliases. "a.id < b.id" stops each pair showing up twice.

SELECT a.name AS person, b.name AS teammate
FROM users a
JOIN users b ON a.department_id = b.department_id AND a.id < b.id;
Joins

19. CROSS JOIN: every combination

No condition at all: every department is paired with every product category (4 x 2 = 8 rows).

SELECT d.name AS department, c.category
FROM departments d
CROSS JOIN (SELECT DISTINCT category FROM products) c;
Aggregations

20. COUNT(*) vs COUNT(column)

COUNT(*) counts rows; COUNT(column) skips NULLs; COUNT(DISTINCT ...) skips repeats. No GROUP BY means one group.

SELECT COUNT(*) AS all_rows,
       COUNT(department_id) AS with_department,
       COUNT(DISTINCT country) AS countries
FROM users;
Aggregations

21. GROUP BY & Aggregations

Rows are sorted into buckets by department, then each bucket collapses into a single summary row.

SELECT department_id, COUNT(*) AS staff_count, AVG(salary) AS avg_salary, MAX(salary) AS top_salary
FROM users
WHERE department_id IS NOT NULL
GROUP BY department_id
ORDER BY avg_salary DESC;
Aggregations

22. HAVING filters groups

WHERE filters rows before grouping. HAVING filters whole groups after aggregation.

SELECT department_id, COUNT(*) AS total_staff, AVG(salary) AS avg_salary
FROM users
WHERE department_id IS NOT NULL
GROUP BY department_id
HAVING COUNT(*) > 1;
Aggregations

23. Grouping by two columns

A bucket is now each distinct (country, department) pair.

SELECT country, department_id, COUNT(*) AS people, SUM(salary) AS payroll
FROM users
GROUP BY country, department_id
ORDER BY country, department_id;
Aggregations

24. Conditional counting with CASE

Put a CASE inside SUM to count only some rows per group.

SELECT country,
       COUNT(*) AS people,
       SUM(CASE WHEN salary >= 90000 THEN 1 ELSE 0 END) AS high_earners
FROM users
GROUP BY country;
Aggregations

25. Join first, then aggregate

LEFT JOIN keeps Marketing, and COUNT(u.id) correctly reports 0 because it ignores the NULL side.

SELECT d.name AS department, COUNT(u.id) AS staff, AVG(u.salary) AS avg_salary
FROM departments d
LEFT JOIN users u ON u.department_id = d.id
GROUP BY d.name
ORDER BY staff DESC, d.name;
Subqueries

26. Nested Subquery (IN)

The inner query runs once and produces a list. The outer query then keeps rows whose id is in that list.

SELECT name, role, salary
FROM users
WHERE id IN (SELECT user_id FROM orders WHERE amount >= 500);
Subqueries

27. Scalar subquery: above the average

A subquery that returns one value can be used like a number inside WHERE.

SELECT name, salary
FROM users
WHERE salary > (SELECT AVG(salary) FROM users)
ORDER BY salary DESC;
Subqueries

28. Correlated subquery

The inner query is re-run for every outer row, comparing each person with their own department.

SELECT name, department_id, salary
FROM users u
WHERE salary > (
  SELECT AVG(salary) FROM users x WHERE x.department_id = u.department_id
);
Subqueries

29. EXISTS and NOT EXISTS

EXISTS only asks "is there at least one row?", so it is true or false for each outer row.

SELECT name
FROM users u
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.user_id = u.id
);
Subqueries

30. The NOT IN trap with NULL

One NULL in the list makes NOT IN unknown for every row, so this returns nothing. Compare with NOT EXISTS.

SELECT name
FROM departments
WHERE id NOT IN (SELECT department_id FROM users);
Subqueries

31. Subquery in FROM (derived table)

The inner query becomes a temporary table that the outer query reads from and filters.

SELECT t.country, t.people
FROM (
  SELECT country, COUNT(*) AS people
  FROM users
  GROUP BY country
) AS t
WHERE t.people > 2;
Subqueries

32. Subquery inside SELECT

A correlated scalar subquery can compute one extra column per row.

SELECT name,
       (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
FROM users u;
CTEs

33. Common Table Expression (CTE)

WITH gives a query a name so the main query can read it like a table.

WITH high_earners AS (
  SELECT name, department_id, salary
  FROM users
  WHERE salary >= 90000
)
SELECT high_earners.name, departments.name AS department, high_earners.salary
FROM high_earners
JOIN departments ON high_earners.department_id = departments.id;
CTEs

34. Two CTEs building on each other

Later CTEs can read earlier ones, so you can build an answer in readable steps.

WITH dept_pay AS (
  SELECT department_id, SUM(salary) AS payroll
  FROM users
  GROUP BY department_id
),
big_depts AS (
  SELECT department_id, payroll FROM dept_pay WHERE payroll > 250000
)
SELECT d.name, b.payroll
FROM big_depts b
JOIN departments d ON d.id = b.department_id
ORDER BY b.payroll DESC;
CTEs

35. Recursive CTE: counting to 8

A recursive CTE starts with one row, then keeps adding rows built from the previous ones until the condition stops it.

WITH RECURSIVE counter(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM counter WHERE n < 8
)
SELECT n, n * n AS square
FROM counter;
Set Operations

36. Set Operations (UNION ALL)

Run two queries and stack the results. UNION ALL keeps every row, duplicates included.

SELECT name, role AS detail, 'UK Employee' AS category
FROM users
WHERE country = 'UK'
UNION ALL
SELECT name, role AS detail, 'Design Lead' AS category
FROM users
WHERE department_id = 3;
Set Operations

37. UNION removes duplicates

Same stacking as UNION ALL, then identical rows are collapsed into one.

SELECT country AS place FROM users
UNION
SELECT location FROM departments
ORDER BY place;
Set Operations

38. INTERSECT: in both results

Keeps only the values that appear in both queries.

SELECT department_id FROM users
INTERSECT
SELECT id FROM departments;
Set Operations

39. EXCEPT: in the first but not the second

Which departments have no employees at all?

SELECT id FROM departments
EXCEPT
SELECT department_id FROM users;
Window Functions

40. Analytical Window Functions

ROW_NUMBER numbers the rows inside each department by salary. No rows are collapsed.

SELECT name, department_id, salary,
       ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_rank
FROM users;
Window Functions

41. RANK vs DENSE_RANK vs ROW_NUMBER

When rows tie, RANK leaves gaps, DENSE_RANK does not, and ROW_NUMBER always counts 1, 2, 3.

SELECT name, country,
       ROW_NUMBER() OVER (ORDER BY country) AS row_num,
       RANK() OVER (ORDER BY country) AS rnk,
       DENSE_RANK() OVER (ORDER BY country) AS dense_rnk
FROM users;
Window Functions

42. Running total

An aggregate with OVER (ORDER BY ...) accumulates row by row instead of collapsing.

SELECT id, name, salary,
       SUM(salary) OVER (ORDER BY id) AS running_payroll
FROM users;
Window Functions

43. LAG and LEAD: look at neighbours

LAG peeks at the previous row and LEAD at the next, ideal for comparing consecutive values.

SELECT name, salary,
       LAG(salary) OVER (ORDER BY salary) AS next_lower,
       LEAD(salary) OVER (ORDER BY salary) AS next_higher
FROM users;
Window Functions

44. Compare each row to its group

AVG over a partition adds the department average to every row, so you can subtract it right away.

SELECT name, department_id, salary,
       AVG(salary) OVER (PARTITION BY department_id) AS dept_avg,
       salary - AVG(salary) OVER (PARTITION BY department_id) AS vs_avg
FROM users
WHERE department_id IS NOT NULL;
Window Functions

45. Top earner per department

You cannot filter on a window function directly, so rank inside a subquery and filter outside.

SELECT name, department_id, salary
FROM (
  SELECT name, department_id, salary,
         ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
  FROM users
  WHERE department_id IS NOT NULL
) AS ranked
WHERE rn = 1;
Window Functions

46. Moving average with a frame

ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING averages each row with its two neighbours.

SELECT id, name, salary,
       AVG(salary) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS smoothed
FROM users;
Full Pipeline

47. Full Multi-Clause Pipeline

FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY and LIMIT in one query, in their real execution order.

SELECT departments.name AS department, COUNT(users.id) AS employee_count, AVG(users.salary) AS average_salary
FROM users
JOIN departments ON users.department_id = departments.id
WHERE users.salary >= 60000
GROUP BY departments.name
HAVING COUNT(users.id) >= 1
ORDER BY average_salary DESC
LIMIT 3;
Full Pipeline

48. Everything together

A CTE, two joins, a window function, ORDER BY and LIMIT: the whole toolbox in one query.

WITH paid AS (
  SELECT user_id, SUM(amount) AS spent
  FROM orders
  WHERE status = 'Completed'
  GROUP BY user_id
)
SELECT u.name, d.name AS department, p.spent,
       RANK() OVER (ORDER BY p.spent DESC) AS spend_rank
FROM users u
JOIN paid p ON p.user_id = u.id
JOIN departments d ON d.id = u.department_id
ORDER BY spend_rank
LIMIT 5;
Client-Side Sample Schemas

Switch Working Databases Anytime

Zero backend roundtrips required
4 tables · 48 queries

Company (default)

Employees, departments, orders and products. The data behind every built-in example.

4 tables · 5 queries

Online shop

Customers, products, orders and order lines. Great for chained joins and revenue sums.

3 tables · 5 queries

School

Students, courses and scores, with NULL scores for work not yet graded.

3 tables · 5 queries

Movies

Films, directors and audience reviews. Good for averages, ranks and missing data.

Navigation

LivePreparation

Client-side workspace · saved locally