SQL Query Patterns - WittyWriter

SQL Query Patterns

📘 Key Concepts and Definitions

🧮 The Structure of a SELECT Query

A SELECT statement retrieves data. The clauses are written in a specific order, but the database executes them in a different logical order.

Written Order

SELECT ...
FROM ...
JOIN ... ON ...
WHERE ...
GROUP BY ...
HAVING ...
ORDER BY ...
LIMIT ...;

Logical Execution Order

  1. FROM / JOIN: Gathers and joins the tables.
  2. WHERE: Filters rows based on conditions.
  3. GROUP BY: Groups rows into summary rows.
  4. HAVING: Filters groups based on conditions.
  5. SELECT: Selects the final columns.
  6. ORDER BY: Sorts the final result set.
  7. LIMIT: Restricts the number of rows returned.

🛠️ Core Commands & Clauses

Data Retrieval & Filtering

SELECT first_name, last_name, email
FROM users
WHERE country = 'Canada' AND age > 25;

Common Filtering Operators

Joining Tables

SELECT users.name, orders.order_date
FROM users
INNER JOIN orders ON users.id = orders.user_id;

Aggregation & Grouping

SELECT country, COUNT(id) AS user_count
FROM users
GROUP BY country
HAVING COUNT(id) > 10; -- 'HAVING' filters after grouping

Common aggregate functions: COUNT(), SUM(), AVG(), MIN(), MAX().

Sorting & Limiting

SELECT name, salary
FROM employees
ORDER BY salary DESC -- 'DESC' for descending, 'ASC' for ascending
LIMIT 10; -- Get the top 10 highest salaries

🧭 Workflow for Building a Complex Query

  1. Identify the goal: What question are you trying to answer? (e.g., "Who are our top 10 customers by total spending?").
  2. Find the tables: Locate the tables containing the required data (e.g., `customers`, `orders`).
  3. Start simple: Write a basic `SELECT ... FROM ...` query.
  4. Add JOINs: Join the tables together using primary and foreign keys. Use aliases for readability.
  5. Apply WHERE filters: Filter the rows to include only the data you need (e.g., completed orders).
  6. Add GROUP BY and aggregates: If you need to summarize data, add your `GROUP BY` clause and aggregate functions (e.g., `GROUP BY customer_id`, `SUM(order_total)`).
  7. Apply HAVING filters: If you need to filter the aggregated groups, use `HAVING`.
  8. Format the output: Use `ORDER BY` to sort the results and `SELECT` aliases to name your columns.
  9. Apply LIMIT: Restrict the final output to the desired number of rows.

⌨️ Productivity Tips

📊 Visualizing JOINs

Venn diagrams are a helpful way to understand how different JOINs work.

JOIN TypeDescription
INNER JOINReturns records that have matching values in both tables. (The intersection).
LEFT JOINReturns all records from the left table, and the matched records from the right table. The result is NULL from the right side if there is no match.
RIGHT JOINReturns all records from the right table, and the matched records from the left table. The result is NULL from the left side if there is no match.
FULL OUTER JOINReturns all records when there is a match in either the left or right table. (Not supported by all databases like MySQL).

🧪 Example: Finding Top Spending Customers

Goal: Get the names and total spending of the top 3 customers who have spent more than $1000 in total.

Tables: customers (id, name), orders (id, customer_id, amount)

SELECT
    c.name,
    SUM(o.amount) AS total_spent
FROM
    customers AS c
INNER JOIN
    orders AS o ON c.id = o.customer_id
GROUP BY
    c.id, c.name -- Group by both ID and name
HAVING
    SUM(o.amount) > 1000
ORDER BY
    total_spent DESC
LIMIT 3;

🧹 Troubleshooting Common Errors

📚 References and Further Reading

🍪 We use cookies to improve your experience. Learn more