SQL Operation Order

FROM

SELECT *
FROM employees;


JOIN (and ON)

SELECT e.name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.department_id;


WHERE

SELECT name, salary
FROM employees
WHERE salary > 50000;


GROUP BY

SELECT department_id, COUNT(*)
FROM employees
GROUP BY department_id;


ROLLUP, CUBE, GROUPING SETS

// ROLLUP: Adds subtotal rows.
SELECT department_id, job_id, SUM(salary)
FROM employees
GROUP BY ROLLUP(department_id, job_id);

// CUBE: Adds subtotal rows for all combinations.
SELECT department_id, job_id, SUM(salary)
FROM employees
GROUP BY CUBE(department_id, job_id);

// GROUPING SETS: Allows custom grouping combinations.
SELECT department_id, job_id, SUM(salary)
FROM employees
GROUP BY GROUPING SETS ((department_id), (job_id), ());


HAVING

SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 60000;


OVER (e.g., Window Functions)

SELECT name, salary, 
       RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;


SELECT DISTINCT

SELECT DISTINCT job_id
FROM employees;


UNION, INTERSECT, EXCEPT

// UNION
SELECT name FROM employees
UNION
SELECT name FROM contractors;

// INTERSECT
SELECT name FROM employees
INTERSECT
SELECT name FROM contractors;

// EXCEPT
SELECT name FROM employees
EXCEPT
SELECT name FROM contractors;


ORDER BY

SELECT name, salary
FROM employees
ORDER BY salary DESC;


OFFSET, FETCH FIRST/NEXT ROWS ONLY

SELECT name, salary
FROM employees
ORDER BY salary DESC
OFFSET 10 ROWS
FETCH NEXT 5 ROWS ONLY;


LIMIT, TOP

// LIMIT
SELECT name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;

// TOP
SELECT TOP 5 name, salary
FROM employees
ORDER BY salary DESC;