SQL Examples
Real, executable SQL examples for intermediate and advanced techniques, every query runs live against a sample database.
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
caseSort employees so a specific department appears first, then by salary.
CASE Expressions: Conditional Logic in SQL
caseUse CASE WHEN to bucket employees into salary bands, and inside COUNT() to conditionally tally rows.
CASE for Conditional Columns (Pivot)
caseUse CASE with COUNT to pivot order statuses into separate columns.
CASE Inside Aggregates for Buckets
caseBucket employees into salary bands and count how many fall in each.
COALESCE: Handling NULLs in Output
caseUse COALESCE to replace NULL manager names with a friendly placeholder.
CTEs
Common Table Expressions (CTEs) With WITH
cteUse 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
cteRewrite a nested subquery as a CTE to compute above-average-salary employees.
Multiple CTEs in One Query
cteChain several CTEs to compute department stats then rank departments by average salary.
Recursive CTE: Building a Number Series
cteUse a recursive CTE to generate a sequence of integers from 1 to 10.
Recursive CTE: Employee Hierarchy
cteWalk the manager tree recursively to list each employee and their management chain depth.
Subqueries
Correlated Subqueries: Comparing Each Row to Its Own Group
subqueryFind 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
subqueryWrap an aggregated subquery in FROM to rank products by total revenue.
Subqueries With ANY, ALL, and IN
subqueryCompare a value against a set using > ANY, > ALL, and IN subqueries.
Subquery in the SELECT List
subqueryAdd a per-row subquery column showing each employee's distance from the company average.
Subquery in the WHERE Clause
subqueryFilter employees whose salary exceeds the average salary of their department.
Window Functions
DENSE_RANK(): Ranking Without Gaps
windowRank employees by salary company-wide using DENSE_RANK, which never skips numbers after ties.
FIRST_VALUE() and LAST_VALUE()
windowShow each employee alongside the highest- and lowest-paid peer in their department.
LEAD() and LAG(): Accessing Neighboring Rows
windowUse LAG() to compare each employee's salary with the previous-highest-paid employee.
NTILE(): Splitting Rows Into Buckets
windowUse NTILE(4) to assign employees into salary quartiles.
RANK() Per Group With PARTITION BY
windowRank employees by salary within each department using RANK() OVER (PARTITION BY ...).
ROW_NUMBER(): Enumerating Rows Within Groups
windowAssign a sequential number to each employee within their department, ordered by salary.
Running Total With SUM() OVER
windowBuild a cumulative salary total across employees ordered by hire date.
Top-N Per Group With ROW_NUMBER
windowUse a CTE with ROW_NUMBER() to keep only the two highest-paid employees in each department.
Window Functions in a Filtered Query
windowCompute each employee's salary share of their department's total payroll.
Window Functions: RANK() and PARTITION BY
windowRank 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
joinUse FULL OUTER JOIN to see every department and every employee, surfacing mismatches on either side.
INNER JOIN: Combining Rows From Two Related Tables
joinUse INNER JOIN to attach department names to employee records, keeping only rows that match on both sides.
JOIN Followed by GROUP BY
joinJoin employees to departments, then aggregate to compute headcount and average salary per department.
LEFT JOIN to Find Missing Relationships
joinUse LEFT JOIN plus a NULL check to find customers who have never placed an order.
LEFT JOIN: Keeping Rows That Don't Match
joinUse 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
joinUse RIGHT JOIN to list every department, including ones with no employees, alongside any matching staff.
Self Join: Comparing Rows Within One Table
joinJoin the employees table to itself to pair each employee with their manager.
Three-Table JOIN: Customers, Orders, and Products
joinChain INNER JOINs across the store schema to show what each customer bought and for how much.
UNION: Stacking Result Sets
joinUse UNION to combine employees and department heads into a single name list with a role label.