Common table expressions (WITH) in SQL
Name a subquery and build on it step by step. Press Run to try it, then change the code and run it again.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
department TEXT,
salary INTEGER
);
INSERT INTO employees (name, department, salary) VALUES
('Asha', 'Engineering', 95000),
('Rohan', 'Engineering', 82000),
('Mei', 'Design', 70000),
('Karan', 'Sales', 64000),
('Priya', 'Design', 76000);
WITH dept_avg AS (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
)
SELECT e.name, e.department, e.salary, ROUND(d.avg_salary) AS dept_avg
FROM employees e
JOIN dept_avg d ON d.department = e.department
WHERE e.salary > d.avg_salary;
Output
Press Run to see the output.
More SQL examples
- Create a table and select rows · Make a table, add rows and read them back.
- INNER JOIN and LEFT JOIN · Combine rows from two tables.
- GROUP BY and HAVING · Summarise rows per group and filter the groups.
- Second highest salary · A classic interview question, solved two ways.
- Window functions · Rank rows within each group without collapsing them.