Skip to main content
Databases

SQL Relational Queries & Joins

Essential

Standard ANSI SQL queries, complex table joins, aggregate window functions, common table expressions (CTEs), and indexing.

Instant Copy & SearchProduction Flagged SyntaxCurrent Flag Reference

SQL Relational Queries & Joins Interactive Command Directory

Browse, search, and copy battle-tested commands & syntax recipes (17 Total Commands).

17+ Verified Recipes
JoinsINNER JOIN
SELECT u.id, u.name, o.total FROM users u INNER JOIN orders o ON u.id = o.user_id WHERE o.status = 'completed';

Return records having matching values in both tables.

Left JoinsLEFT JOIN
SELECT u.id, u.name, COUNT(o.id) AS order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.name;

Return all records from left table and matched records from right table.

Window FunctionsROW_NUMBER() OVER
SELECT emp_id, dept, salary, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) as rank FROM employees;

Calculate rank of rows within each partition without collapsing result set.

Window Running TotalsSUM() OVER (ORDER BY)
SELECT order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS running_total FROM sales;

Calculate cumulative running total across time-ordered records.

Common Table ExpressionsWITH <cte> AS
WITH RegionalRevenue AS ( SELECT region, SUM(amount) AS total_rev FROM sales GROUP BY region ) SELECT * FROM RegionalRevenue WHERE total_rev > 50000;

Define reusable temporary named result sets for modular readable queries.

Conditional LogicCASE WHEN ... THEN
SELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END AS grade FROM students;

Evaluate sequential conditional expressions within query projection.

Grouping FiltersHAVING
SELECT department, COUNT(*) AS head_count, AVG(salary) FROM employees GROUP BY department HAVING COUNT(*) > 10;

Filter grouped aggregate results after GROUP BY evaluation.

Set OperationsUNION ALL
SELECT email FROM customers UNION ALL SELECT email FROM newsletter_subscribers;

Combine rows from two queries preserving all duplicates without sorting overhead.

Analytical WindowingOVER, PARTITION BY, LAG
SELECT department_id, employee_name, salary, DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank, LAG(salary, 1) OVER (PARTITION BY department_id ORDER BY salary DESC) AS prev_salary FROM employees;

Compute dense intra-department ranking and lag value comparison without multi-pass self joins.

Multi-Dimensional AggregationCUBE, GROUP BY
SELECT DATE_TRUNC('month', created_at) AS month, status, COUNT(*) AS count FROM orders GROUP BY CUBE (DATE_TRUNC('month', created_at), status);

Generate multi-level subtotal combinations across multiple dimensional axes in a single scan.

Idempotent UpsertON CONFLICT, DO UPDATE
INSERT INTO customers (id, email, name) VALUES (1, 'user@domain.com', 'Alex') ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email;

Atomic insert with conflict detection updating specified fields on duplicate key collisions.

Subquery OptimizationWHERE EXISTS
SELECT o.id, o.amount FROM orders o WHERE EXISTS (SELECT 1 FROM line_items li WHERE li.order_id = o.id AND li.category = 'electronics');

Optimized semi-join evaluation terminating inner subquery scans on first matching record.

Cross-Table UpdatesUPDATE ... FROM
UPDATE inventory i SET stock = stock - sub.qty FROM (SELECT product_id, SUM(quantity) AS qty FROM pending_orders GROUP BY product_id) sub WHERE i.id = sub.product_id;

Bulk synchronize inventory counts from aggregated subquery results.

Abstraction ViewsCREATE VIEW
CREATE VIEW high_value_customers AS SELECT c.id, c.name, SUM(o.amount) AS lifetime_value FROM customers c JOIN orders o ON c.id = o.customer_id GROUP BY c.id, c.name HAVING SUM(o.amount) > 10000;

Encapsulate complex reporting aggregations into queryable database views.

JSON Transformationjson_agg, json_build_object
SELECT c.name, json_agg(json_build_object('order_id', o.id, 'total', o.total)) AS order_history FROM customers c JOIN orders o ON c.id = o.customer_id GROUP BY c.id, c.name;

Aggregate relational 1:N relations into nested JSON document arrays directly at the SQL layer.

ACID TransactionsBEGIN, SERIALIZABLE, COMMIT
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT;

Execute multi-statement atomic transfer under strict serializable isolation level.

Mutating Data PipelineRETURNING
DELETE FROM logs WHERE created_at < NOW() - INTERVAL '90 days' RETURNING id;

Batch purge aged historical records while returning deleted primary keys for archival audit pipelines.

Zero Setup100% In-Browser Execution

Companion Developer Tools & Playgrounds

Accelerate command execution and syntax debugging with HelloAIHub suite of interactive tools.

Explore all developer tools

SQL Relational Queries & Joins: Command Groups & Quick Index

17 indexed entries across 17 sections
Joins1 items
Left Joins1 items
Window Functions1 items
Window Running Totals1 items
Common Table Expressions1 items
Conditional Logic1 items
Grouping Filters1 items
Set Operations1 items
Analytical Windowing1 items
Multi-Dimensional Aggregation1 items
Idempotent Upsert1 items
Subquery Optimization1 items
Cross-Table Updates1 items
Abstraction Views1 items
JSON Transformation1 items
ACID Transactions1 items
Mutating Data Pipeline1 items

Highlighted Flags & Syntax Examples in SQL Relational Queries & Joins

SELECT u.id, u.name, o.total FROM users u INNER JOIN orders o ON u.id = o.user_id WHERE o.status = 'completed';

Return records having matching values in both tables.

Flags: INNER JOIN
SELECT u.id, u.name, COUNT(o.id) AS order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.name;

Return all records from left table and matched records from right table.

Flags: LEFT JOIN
SELECT emp_id, dept, salary, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) as rank FROM employees;

Calculate rank of rows within each partition without collapsing result set.

Flags: ROW_NUMBER() OVER
SELECT order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS running_total FROM sales;

Calculate cumulative running total across time-ordered records.

Flags: SUM() OVER (ORDER BY)

Frequently Asked Questions

Expert recommendations, common traps, and production best practices for SQL Relational Queries & Joins.

What is the difference between WHERE and HAVING in SQL?

WHERE filters individual rows before grouping and aggregate calculations are performed. HAVING filters groups of rows after GROUP BY and aggregate functions (like SUM, COUNT, AVG) have been calculated.

What is the difference between UNION and UNION ALL?

UNION combines result sets and performs an implicit DISTINCT sort to eliminate duplicate rows. UNION ALL appends the result sets directly without deduplication, making it significantly faster.

What are the four ANSI SQL transaction isolation levels and what anomalies do they prevent?

The levels are: 1. Read Uncommitted (allows dirty reads). 2. Read Committed (prevents dirty reads, allows non-repeatable reads). 3. Repeatable Read (prevents non-repeatable reads, may allow phantom reads depending on engine). 4. Serializable (strictly guarantees transactions execute as if run serially, preventing all concurrency anomalies).

What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER() in SQL window functions?

For tied values: ROW_NUMBER() assigns strictly unique incremental numbers (1, 2, 3, 4). RANK() assigns the same rank to ties and skips subsequent numbers (1, 2, 2, 4). DENSE_RANK() assigns the same rank to ties without skipping subsequent numbers (1, 2, 2, 3).

Why is index cardinality critical for query planner selectivity?

Cardinality measures the uniqueness of data values in a column. High cardinality (like UUID or email) allows the query planner to quickly narrow down rows via index seeks. Low cardinality (like boolean or gender) often causes the planner to bypass the index in favor of a full table sequential scan because reading index pages and heap pages incurs more I/O than a sequential scan.

What is an index covering query (Index-Only Scan) and how does it avoid table heap lookups?

An Index-Only Scan occurs when all columns requested in the SELECT, WHERE, and JOIN clauses exist entirely within the index B-tree (using composite keys or INCLUDE clauses). The database engine satisfies the entire query from index pages alone without touching the underlying table heap data blocks.

Cross-Hub Skill Acceleration

Combine command lookups with active coding interviews and complete career paths.

Need More Cheat Sheets?

Explore developer cheat sheets and syntax guides on HelloAIHub.

Browse All Cheat Sheets