Database Tutorial #3: PostgreSQL — Advanced Queries
Basic SELECT queries only get you so far. Real applications need joins, aggregations, and complex filtering. This tutorial covers the SQL features you will use every day. We assume you have PostgreSQL running. See PostgreSQL Setup and Basics if you need to set that up first. Sample Schema Let’s use a simple e-commerce schema for all examples: CREATE TABLE users ( id uuid DEFAULT gen_random_uuid() PRIMARY KEY, name text NOT NULL, email text UNIQUE NOT NULL, created_at timestamptz DEFAULT NOW() ); CREATE TABLE orders ( id uuid DEFAULT gen_random_uuid() PRIMARY KEY, user_id uuid REFERENCES users(id), status text NOT NULL DEFAULT 'pending', total decimal(10, 2) NOT NULL, created_at timestamptz DEFAULT NOW() ); CREATE TABLE order_items ( id uuid DEFAULT gen_random_uuid() PRIMARY KEY, order_id uuid REFERENCES orders(id), product text NOT NULL, quantity integer NOT NULL, price decimal(10, 2) NOT NULL ); JOINs JOINs combine rows from multiple tables based on a related column. ...