SQL Examples
Real, executable SQL examples for intermediate and advanced techniques.
Aggregates
Aggregates With FILTER (Conditional Aggregation)
AggregateCount completed vs cancelled orders in one pass using FILTER clauses.
Aggregating DISTINCT Values
AggregateUse SUM(DISTINCT ...) and AVG(DISTINCT ...) to avoid double-counting repeated values.
Core Aggregate Functions: COUNT, SUM, AVG, MIN, MAX
AggregateA single query demonstrating all five core aggregates over the employees table.
COUNT(): Row Tallies and Distinct Counts
AggregateCompare COUNT(*), COUNT(column), and COUNT(DISTINCT column) on the customers table.
MIN() and MAX() Across Groups
AggregateFind the cheapest and most expensive product within each category.
String Aggregation With string_agg()
AggregateConcatenate related values into a single comma-separated list per group.
Group By
AVG() Aggregation With GROUP BY
Group ByCompute the average movie budget per genre using AVG() grouped by genre.
COUNT() Aggregation With GROUP BY
Group ByCount how many movies each director has made using COUNT() grouped by director.
GROUP BY Basics: Aggregating Rows Into Summaries
Group ByCollapse individual orders into one summary row per customer using GROUP BY, COUNT, and SUM.
GROUP BY Multiple Columns
Group ByGroup by both category and status to see order counts for every product-category/status combination.
GROUP BY with HAVING
Group ByUse HAVING to keep only departments whose average salary exceeds a threshold after aggregation.
Grouping by Date Parts
Group ByGroup store orders by order month to chart order volume over time.
SUM() Aggregation With GROUP BY
Group BySum total units ordered per product category using SUM() grouped by category.
CASE Expressions
CASE Expressions in ORDER BY
CASE ExpressionsSort employees so a specific department appears first, then by salary.
CASE Expressions: Conditional Logic in SQL
CASE ExpressionsUse CASE WHEN to bucket employees into salary bands, and inside COUNT() to conditionally tally rows.
CASE for Conditional Columns (Pivot)
CASE ExpressionsUse CASE with COUNT to pivot order statuses into separate columns.
CASE Inside Aggregates for Buckets
CASE ExpressionsBucket employees into salary bands and count how many fall in each.
COALESCE: Handling NULLs in Output
CASE ExpressionsUse COALESCE to replace NULL manager names with a friendly placeholder.
CTEs
Common Table Expressions (CTEs) With WITH
CTEsUse a WITH clause to compute total spend per customer as a named, reusable result set, then filter and join against it.
CTE vs Subquery: Same Result, Clearer Code
CTEsRewrite a nested subquery as a CTE to compute above-average-salary employees.
Multiple CTEs in One Query
CTEsChain several CTEs to compute department stats then rank departments by average salary.
Recursive CTE: Building a Number Series
CTEsUse a recursive CTE to generate a sequence of integers from 1 to 10.
Recursive CTE: Employee Hierarchy
CTEsWalk the manager tree recursively to list each employee and their management chain depth.
Subqueries
Correlated Subqueries: Comparing Each Row to Its Own Group
SubqueriesFind movies whose budget exceeds the average budget for their own genre, using a subquery that references the outer query's current row.
Derived Table: Subquery in the FROM Clause
SubqueriesWrap an aggregated subquery in FROM to rank products by total revenue.
Subqueries With ANY, ALL, and IN
SubqueriesCompare a value against a set using > ANY, > ALL, and IN subqueries.
Subquery in the SELECT List
SubqueriesAdd a per-row subquery column showing each employee's distance from the company average.
Subquery in the WHERE Clause
SubqueriesFilter employees whose salary exceeds the average salary of their department.
Window Functions
DENSE_RANK(): Ranking Without Gaps
Window FunctionsRank employees by salary company-wide using DENSE_RANK, which never skips numbers after ties.
FIRST_VALUE() and LAST_VALUE()
Window FunctionsShow each employee alongside the highest- and lowest-paid peer in their department.
LEAD() and LAG(): Accessing Neighboring Rows
Window FunctionsUse LAG() to compare each employee's salary with the previous-highest-paid employee.
NTILE(): Splitting Rows Into Buckets
Window FunctionsUse NTILE(4) to assign employees into salary quartiles.
RANK() Per Group With PARTITION BY
Window FunctionsRank employees by salary within each department using RANK() OVER (PARTITION BY ...).
ROW_NUMBER(): Enumerating Rows Within Groups
Window FunctionsAssign a sequential number to each employee within their department, ordered by salary.
Running Total With SUM() OVER
Window FunctionsBuild a cumulative salary total across employees ordered by hire date.
Top-N Per Group With ROW_NUMBER
Window FunctionsUse a CTE with ROW_NUMBER() to keep only the two highest-paid employees in each department.
Window Functions in a Filtered Query
Window FunctionsCompute each employee's salary share of their department's total payroll.
Window Functions: RANK() and PARTITION BY
Window FunctionsRank employees by salary within their own department using RANK() OVER (PARTITION BY ...), without collapsing rows the way GROUP BY does.
EXISTS
EXISTS and NOT EXISTS: Testing for Related Rows
EXISTSUse EXISTS with a correlated subquery to find authors who have published at least one book, and NOT EXISTS for the opposite.
EXISTS: Correlated Subquery for Membership
EXISTSFind customers who have at least one completed order using EXISTS.
NOT EXISTS: The Anti-Join Pattern
EXISTSFind employees who are not managers of anyone using NOT EXISTS.
Joins
FULL JOIN: Keeping Unmatched Rows From Both Sides
JoinsUse FULL OUTER JOIN to see every department and every employee, surfacing mismatches on either side.
INNER JOIN: Combining Rows From Two Related Tables
JoinsUse INNER JOIN to attach department names to employee records, keeping only rows that match on both sides.
JOIN Followed by GROUP BY
JoinsJoin employees to departments, then aggregate to compute headcount and average salary per department.
LEFT JOIN to Find Missing Relationships
JoinsUse LEFT JOIN plus a NULL check to find customers who have never placed an order.
LEFT JOIN: Keeping Rows That Don't Match
JoinsUse LEFT JOIN to list every movie alongside its audience rating, including movies that have never been rated.
RIGHT JOIN: Keeping All Rows From the Right Table
JoinsUse RIGHT JOIN to list every department, including ones with no employees, alongside any matching staff.
Self Join: Comparing Rows Within One Table
JoinsJoin the employees table to itself to pair each employee with their manager.
Three-Table JOIN: Customers, Orders, and Products
JoinsChain INNER JOINs across the store schema to show what each customer bought and for how much.
UNION: Stacking Result Sets
JoinsUse UNION to combine employees and department heads into a single name list with a role label.