SQL 101

    Ask the shop's database anything

    In Software Development 101, order 194 ended up as rows in Postgres. Now you'll ask those rows questions, in real Postgres running right here in your browser.

    
    SELECT name, price
    FROM products
    WHERE product_id = 3;
    

    Everyone should speak SQL

    • Developer"Which orders did the API save in the last hour?"Check what your code really did.
    • Founder or CEO"What was revenue last month, by product?"Answers in seconds, not next week.
    • Accountant"Which orders are still pending?"Check the source of truth directly.
    • Marketer"Which city buys the most?"Measure and segment it yourself.

    If you can read a spreadsheet, you can learn to read SQL.

    Meet the shop: four tables

    customers 50 rows

    • customer_id
    • full_name
    • email
    • city
    • signup_date

    orders 193 rows

    • order_id
    • customer_id → customers
    • order_date
    • status

    order_items 524 rows

    • order_item_id
    • order_id → orders
    • product_id → products
    • quantity
    • unit_price

    products 20 rows

    • product_id
    • name
    • category
    • price
    • Each table has an id column that names one row: its primary key.
    • An arrow is a foreign key: every order belongs to a customer, and every order item points to an order and a product.
    • Money lives in order_items: quantity * unit_price.

    Every query you'll write today

    SELECTWhich columns?"Show me name and price…"
    FROMWhich table?"…from products…"
    WHEREWhich rows?"…but only Electronics."
    
    SELECT name, price
    FROM products
    WHERE category = 'Electronics';
    

    SELECT: see your data

    
    SELECT full_name, city
    FROM customers
    LIMIT 5;
    
    • SELECT * means every column.
    • Start with LIMIT to peek before asking for everything.
    • SELECT only reads. It never changes the data.

    WHERE: filter the rows

    
    SELECT name, price
    FROM products
    WHERE price > 100;
    
    =equals
    <>not equal
    > < >= <=compare
    LIKE 'S%'starts with S
    IN ('a', 'b')any of a list
    AND, ORcombine
    IS NULLhas no value

    Without ORDER BY, rows come back in no promised order.

    ORDER BY and LIMIT: the top of anything

    
    -- The 5 most expensive products
    SELECT name, price
    FROM products
    ORDER BY price DESC
    LIMIT 5;
    
    • DESC puts the biggest first. ASC, the default, puts the smallest first.
    • Top 10 customers, latest 20 orders, worst 5 months: sort, then cut.

    COUNT, SUM, AVG: one-line answers

    193orders, everSELECT COUNT(*) FROM orders;
    $128,103.40in all order items, including pending and cancelled ordersSELECT SUM(quantity * unit_price) FROM order_items;
    $149.07average product priceSELECT ROUND(AVG(price), 2) FROM products;
    
    SELECT COUNT(*) AS orders, MIN(order_date) AS first, MAX(order_date) AS last
    FROM orders;
    

    Revenue only counts completed orders: $103,843.10. Getting it takes a JOIN.

    GROUP BY and HAVING: one answer per group

    
    SELECT city, COUNT(*) AS customers
    FROM customers
    GROUP BY city
    HAVING COUNT(*) >= 7
    ORDER BY customers DESC, city;
    
    • GROUP BY makes one row per city, per month, per anything.
    • WHERE filters rows before grouping. HAVING filters the groups after.
    • Every pivot table you've made was a GROUP BY.

    JOIN: connect the tables

    
    SELECT o.order_id, o.order_date, c.full_name, c.city
    FROM orders o
    JOIN customers c ON c.customer_id = o.customer_id
    ORDER BY o.order_id
    LIMIT 5;
    
    • ON says how rows match: the shared id.
    • o and c are short nicknames for the tables.
    • Orders only store a customer_id. JOIN fills in who that is.

    Put it together: revenue per month

    
    SELECT TO_CHAR(o.order_date, 'YYYY-MM') AS month,
           SUM(oi.quantity * oi.unit_price) AS revenue
    FROM orders o
    JOIN order_items oi ON oi.order_id = o.order_id
    WHERE o.status = 'completed'
    GROUP BY month
    ORDER BY month;
    

    INSERT: order 194 arrives

    
    BEGIN;
    INSERT INTO orders (customer_id, order_date)
    VALUES (7, CURRENT_DATE);
    
    INSERT INTO order_items
      (order_id, product_id, quantity, unit_price)
    VALUES (currval('orders_order_id_seq'), 3, 1, 89.00);
    COMMIT;
    
    SELECT order_id, product_id, quantity, unit_price
    FROM order_items
    WHERE order_id = (SELECT MAX(order_id) FROM orders);
    
    • Name the columns, then give the values in the same order.
    • order_id fills itself in, and currval reads the number it just got.
    • BEGIN and COMMIT make both rows land together, or neither.
    • This is what Buy did in Software Development 101.

    UPDATE and DELETE: change with care

    
    UPDATE orders
    SET status = 'cancelled'
    WHERE order_id = 194
    RETURNING order_id, status;
    

    The oldest mistake in the book

    
    -- No WHERE!
    UPDATE products SET price = 0;
    

    That sets every price to zero. Once it's committed, there's no undo button.

    The habit: write a SELECT with the same WHERE first, check the rows, then change the verb.

    SELECT reads, INSERT adds, UPDATE changes, DELETE removes.

    Where tables come from

    CREATE

    
    CREATE TABLE suppliers (
      supplier_id SERIAL PRIMARY KEY,
      name    TEXT NOT NULL,
      country TEXT
    );
    

    Columns, types and rules.

    ALTER

    
    ALTER TABLE products
    ADD COLUMN stock INT DEFAULT 0;
    

    Change the shape and keep the data.

    DROP

    
    DROP TABLE suppliers;
    

    Table and data, gone. No undo.

    
    -- The rules hold: products has CHECK (price >= 0)
    INSERT INTO products (name, category, price) VALUES ('Broken', 'Test', -5);
    

    Your one-slide cheat sheet

    SELECT … FROM …pick columns from a table
    WHEREfilter rows: =, <>, >, LIKE, IN, AND, OR
    ORDER BY … DESC LIMIT nsort, keep the top n
    COUNT, SUM, AVG, MIN, MAXcollapse rows into one answer
    GROUP BY … HAVINGone row per group, then filter the groups
    JOIN … ONconnect tables by their shared id
    INSERT INTO … VALUESadd rows
    UPDATE … SET … WHEREchange rows: WHERE first!
    DELETE FROM … WHEREremove rows: WHERE first!

    Your turn: five exercises

    1. ★Electronics, priciest firstSELECT, WHERE, ORDER BY
    2. ★Customers per cityGROUP BY
    3. ★★Revenue from completed ordersJOIN, SUM
    4. ★★Months over $10,000GROUP BY, HAVING
    5. ★★★Top 5 customers by spendingtwo JOINs, GROUP BY, LIMIT
    Open the practice page
    • Write a query, press Ctrl+Enter to run it.
    • Check answer says what's off: rows, order or values.
    • Broke something? Reset the shop.
    • Want Postgres on your laptop? Clone the repo and run docker compose up -d.

    Prefer point and click? SQL tools for your PC

    • pgAdminThe official Postgres tool. Free, and included in the Docker setup.
    • DBeaverOne free tool for Postgres, MySQL, SQLite and more.
    • DataGripJetBrains' SQL editor with the best autocomplete. Paid.
    • Beekeeper StudioClean and simple. A friendly first tool.

    They all send SQL to the same database, so what you learned works in every one.

    Keep going

    The best practice data is your own team's. Ask for read-only access this week.

    
    SELECT questions
    FROM audience;
    

    Thank you