sql

How to Select and SubQuery in SQL Syntax

SQL has a small number of statements that combine to handle almost any data question. Here's a quick reference for the patterns I use most.

10 Apr 2024

SQL has a small number of statements that combine to handle almost any data question. Here's a quick reference for the patterns I use most.

SELECT everything

Sql
SELECT * FROM Customers

Returns all rows and columns. Fine for exploring. Never use SELECT * in production queries -- always name the columns you need.

Filtering with WHERE

Sql
SELECT name, city
FROM Customers
WHERE country = 'Germany'

WHERE filters rows before they're returned. Any column, any comparison operator.

Sorting with ORDER BY

Sql
SELECT name, city
FROM Customers
ORDER BY name ASC

ASC for ascending (A-Z, 0-9). DESC for descending. You can sort by multiple columns.

Grouping with GROUP BY

Sql
SELECT country, COUNT(*) AS customer_count
FROM Customers
GROUP BY country

Collapses rows into groups. Aggregate functions (COUNT, SUM, AVG) compute values per group.

Filtering groups with HAVING

Sql
SELECT country, COUNT(*) AS customer_count
FROM Customers
GROUP BY country
HAVING COUNT(*) > 5

HAVING filters after grouping. WHERE filters before. Use HAVING when you need to filter on aggregate results.

Subqueries

Sql
SELECT name
FROM Customers
WHERE country IN (
    SELECT country
    FROM Orders
    GROUP BY country
    HAVING SUM(amount) > 10000
)

A SELECT inside another SELECT. The inner query finds countries with high-value orders. The outer query returns customers from those countries.

The mental model

Every SQL query follows the same execution flow:

  1. FROM -- which table
  2. WHERE -- filter rows
  3. GROUP BY -- create groups
  4. HAVING -- filter groups
  5. SELECT -- choose columns
  6. ORDER BY -- sort results
  7. LIMIT -- cap the output

Memorize this order. It explains why you can't use a column alias from SELECT in your WHERE clause -- WHERE runs first.

Keep reading