Courses / Databases for Backend Interviews / Chapter 12
Module 6 · SQL patterns: aggregation and filtering · Chapter 12 of 27
Filtering Patterns: Existence, Exclusion, Aggregate Filters and Top-N per Group
Builds on Aggregation Patterns: Tally Counts, Group Buckets and Rolling Totals. Next up: Comparison Patterns: Row Against Group, Neighbour and Earlier Period.
Part 1 · Row filters done right
Filtering is deciding which rows count
Most queries start by deciding which rows matter: orders from one month, customers in one city, products with a name. These simple filters hide the bugs that return a wrong answer without any error.
A filter is a condition in the WHERE clause. A row stays when the condition is true. A row is dropped when it is false or unknown, which is what a comparison with NULL produces.
This chapter uses seven tables from the patterns introduction, with a different dataset: nine orders in Pune across February to April 2026, six customers, and eight products in three categories. Order 3 is at 6.30 in the evening on 31 March, and order 4 is at exactly midnight on 1 April. They are there to break a careless date filter.
SET TIME ZONE 'Asia/Kolkata'; CREATE TABLE cities ( city_id int PRIMARY KEY, name text NOT NULL, state text NOT NULL ); CREATE TABLE stores ( store_id int PRIMARY KEY, city_id int NOT NULL REFERENCES cities (city_id), name text NOT NULL, opened_on date NOT NULL ); CREATE TABLE customers ( customer_id int PRIMARY KEY, name text NOT NULL, city_id int NOT NULL REFERENCES cities (city_id), signed_up_at timestamptz NOT NULL ); CREATE TABLE categories ( category_id int PRIMARY KEY, name text NOT NULL, parent_id int REFERENCES categories (category_id) ); CREATE TABLE products ( product_id int PRIMARY KEY, category_id int NOT NULL REFERENCES categories (category_id), name text NOT NULL, price numeric(10,2) NOT NULL );