SQL · Module 15 · Lesson 21 min read

Project: E-commerce & Sales Analytics

Schema

  • products (name, category, price, stock)
  • customers (name, city, signed_up_on)
  • orders (customer, status, ordered_at)
  • order_items (order, product, qty, unit_price snapshot)

Business rules to enforce

  • Stock can't go negative (CHECK (stock >= 0))
  • Placing an order = insert order + items + decrease stock in one transaction (a function)
  • Order status: pending → paid → shipped → delivered (or cancelled)
  • Prices are copied into order_items at purchase time

Questions to answer with SQL

  1. Revenue per month and month-over-month growth (window lag)
  2. Top 3 products per category (row_number + PARTITION BY)
  3. Best customers by lifetime value
  4. Average order value (AOV)
  5. Products that never sold (anti-join)
  6. Repeat customers vs one-time buyers
  7. Low-stock alert list
  8. Revenue share per category (sum() OVER ())

Skills practised

Joins across 4 tables, GROUP BY, window functions, CTEs, anti-joins, transactions, constraints, functions

Stretch goals

Discount codes, returns/refunds, product reviews with average ratings, a materialized view for the sales dashboard, full-text product search

Example

SQL
CREATE TABLE shop_products (
  id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name TEXT NOT NULL, category TEXT NOT NULL,
  price NUMERIC(10,2) NOT NULL CHECK (price > 0), stock INT NOT NULL CHECK (stock >= 0)
);
CREATE TABLE shop_customers (id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name TEXT NOT NULL, city TEXT);
CREATE TABLE shop_orders (
  id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id INT NOT NULL REFERENCES shop_customers(id),
  status TEXT NOT NULL DEFAULT 'paid' CHECK (status IN ('pending','paid','shipped','delivered','cancelled')),
  ordered_on DATE NOT NULL
);
CREATE TABLE shop_order_items (
  order_id INT REFERENCES shop_orders(id) ON DELETE CASCADE,
  product_id INT REFERENCES shop_products(id),
  qty INT NOT NULL CHECK (qty > 0),
  unit_price NUMERIC(10,2) NOT NULL,
  PRIMARY KEY (order_id, product_id)
);

INSERT INTO shop_products (name, category, price, stock) VALUES
  ('Momo steamer', 'Kitchen', 2500, 20), ('Pressure cooker', 'Kitchen', 4200, 8),
  ('Dhaka topi', 'Fashion', 800, 50), ('Pashmina shawl', 'Fashion', 6500, 5),
  ('Trekking pole', 'Outdoor', 1800, 30), ('Sleeping bag', 'Outdoor', 7500, 3);
INSERT INTO shop_customers (name, city) VALUES ('Asha', 'Kathmandu'), ('Ravi', 'Pokhara'), ('Sita', 'Kathmandu'), ('Bikash', 'Lalitpur');

-- Place an order atomically: insert order + items + reduce stock
CREATE FUNCTION place_order(p_customer INT, p_date DATE, p_items JSONB) RETURNS INT
LANGUAGE plpgsql AS $$
DECLARE v_order INT; item JSONB;
BEGIN
  INSERT INTO shop_orders (customer_id, ordered_on) VALUES (p_customer, p_date) RETURNING id INTO v_order;
  FOR item IN SELECT * FROM jsonb_array_elements(p_items) LOOP
    UPDATE shop_products SET stock = stock - (item->>'qty')::int
    WHERE id = (item->>'product')::int;                      -- CHECK stops overselling
    INSERT INTO shop_order_items (order_id, product_id, qty, unit_price)
    SELECT v_order, id, (item->>'qty')::int, price FROM shop_products WHERE id = (item->>'product')::int;
  END LOOP;
  RETURN v_order;
END $$;

SELECT place_order(1, '2026-09-10', '[{"product":1,"qty":1},{"product":3,"qty":2}]');
SELECT place_order(2, '2026-09-22', '[{"product":5,"qty":2}]');
SELECT place_order(1, '2026-10-05', '[{"product":4,"qty":1}]');
SELECT place_order(3, '2026-10-18', '[{"product":2,"qty":1},{"product":3,"qty":1}]');
SELECT place_order(2, '2026-11-02', '[{"product":6,"qty":1},{"product":5,"qty":1}]');
SELECT place_order(1, '2026-11-15', '[{"product":1,"qty":2}]');

-- ❌ Overselling is impossible (only 3 sleeping bags → 2 left after one sale)
DO $$ BEGIN PERFORM place_order(4, '2026-11-20', '[{"product":6,"qty":5}]');
EXCEPTION WHEN check_violation THEN RAISE NOTICE 'Order rejected: not enough stock'; END $$;

-- 1. Monthly revenue + growth
WITH monthly AS (
  SELECT date_trunc('month', o.ordered_on)::date AS month, sum(oi.qty * oi.unit_price) AS revenue
  FROM shop_orders o JOIN shop_order_items oi ON oi.order_id = o.id
  WHERE o.status <> 'cancelled' GROUP BY 1
)
SELECT to_char(month, 'Mon') AS month, revenue,
       round(100.0 * (revenue - lag(revenue) OVER (ORDER BY month)) / lag(revenue) OVER (ORDER BY month), 1) AS growth_pct
FROM monthly ORDER BY monthly.month;

-- 2. Best product per category by units sold
SELECT category, name, units FROM (
  SELECT p.category, p.name, sum(oi.qty) AS units,
         row_number() OVER (PARTITION BY p.category ORDER BY sum(oi.qty) DESC) AS rn
  FROM shop_order_items oi JOIN shop_products p ON p.id = oi.product_id
  GROUP BY p.category, p.name
) t WHERE rn = 1;

-- 3. Customer lifetime value + 4. average order value
SELECT c.name, count(DISTINCT o.id) AS orders, sum(oi.qty * oi.unit_price) AS lifetime_value,
       round(sum(oi.qty * oi.unit_price) / count(DISTINCT o.id), 2) AS avg_order_value
FROM shop_customers c
JOIN shop_orders o ON o.customer_id = c.id
JOIN shop_order_items oi ON oi.order_id = o.id
GROUP BY c.name ORDER BY lifetime_value DESC;

-- 5. Customers who never ordered + 7. low stock
SELECT name AS never_ordered FROM shop_customers c
WHERE NOT EXISTS (SELECT 1 FROM shop_orders o WHERE o.customer_id = c.id);        -- Bikash
SELECT name, stock FROM shop_products WHERE stock <= 5 ORDER BY stock;             -- low stock alert