SQL Cheat Sheet: Joins, Aggregates, Subqueries

Structured Query Language (SQL) is the universal standard for managing, querying, and manipulating relational databases. Whether you are building web backends, data analytics pipelines, or enterprise microservices, writing efficient database queries is an essential core competency for all software engineers.

This comprehensive, developer-focused SQL Cheat Sheet covers essential database querying patterns ranging from table definition and CRUD operations to multi-table joins, aggregate groupings, and subqueries.

1. Table Definition and CRUD Operations

Create relational tables, insert records, update values, and query data.

C
-- Create a relational table
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Insert records
INSERT INTO users (username, email) VALUES ('alex_dev', 'alex@codecrown.in');

-- Select and filter records
SELECT * FROM users WHERE username = 'alex_dev';

-- Update records
UPDATE users SET email = 'new_email@codecrown.in' WHERE id = 1;

-- Delete records
DELETE FROM users WHERE id = 1;

2. Multi-Table Joins (INNER, LEFT, RIGHT, FULL)

Combine rows from two or more tables based on related foreign key columns.

C
-- INNER JOIN: Returns records that have matching values in both tables
SELECT users.username, orders.total_amount 
FROM users
INNER JOIN orders ON users.id = orders.user_id;

-- LEFT JOIN: Returns all records from left table, and matched records from right table
SELECT users.username, orders.total_amount 
FROM users
LEFT JOIN orders ON users.id = orders.user_id;

3. Aggregate Functions and Grouping (COUNT, SUM, AVG, GROUP BY)

Summarize data across multiple rows using aggregate functions and conditional filtering with HAVING.

C
-- Count total users
SELECT COUNT(*) AS total_users FROM users;

-- Calculate average order amount grouped by user
SELECT user_id, AVG(total_amount) AS avg_spent
FROM orders
GROUP BY user_id
HAVING AVG(total_amount) > 100;

4. Subqueries and Common Table Expressions (CTEs)

Nest queries or structure complex datasets using readable temporary result sets (WITH clause).

C
-- Subquery in WHERE clause
SELECT * FROM users 
WHERE id IN (SELECT user_id FROM orders WHERE total_amount > 500);

-- Common Table Expression (CTE)
WITH HighValueOrders AS (
    SELECT user_id, SUM(total_amount) as total
    FROM orders
    GROUP BY user_id
    HAVING SUM(total_amount) > 1000
)
SELECT users.username, HighValueOrders.total
FROM users
JOIN HighValueOrders ON users.id = HighValueOrders.user_id;

Conclusion

Keep this SQL query reference cheat sheet handy to quickly construct optimal joins, aggregate groupings, and subqueries for your relational database systems and backend applications.