Indexes
An index is a lookup structure, like the index at the back of a book: instead of reading every row to find customer 4821's orders, the database looks them up.
CREATE INDEX idx_orders_customer ON orders (customer_id)- Index the columns you filter and join on often: ids, foreign keys, dates.
- An index on several columns,
(order_date, status), helps filters on the first column, or on both; it doesn't help a filter onstatusalone. CREATE UNIQUE INDEXalso stops duplicates getting in, like aUNIQUEconstraint.- Indexes aren't free. Every
INSERTandUPDATEhas to keep them up to date, so don't index everything.
DuckDB is different here: it's built for analysis, stores data by column, and already skips blocks of rows it doesn't need, so it rarely needs indexes for reports. Its indexes mainly speed up looking up a few rows by key, and enforce uniqueness. In SQL Server, PostgreSQL and MySQL, which most companies use for their main systems, the right index can turn a minute-long query into a millisecond one. That's where this matters most.
CREATE INDEX idx_orders_customer ON orders (customer_id)Mostly for looking up a few rows by key, and for uniqueness: DuckDB skips unneeded data by itself.
CREATE INDEX idx_orders_customer ON orders (customer_id)Use EXPLAIN's cousin, the execution plan (Ctrl+M in SSMS), to see whether it's used.
CREATE INDEX idx_orders_customer ON orders (customer_id)CREATE INDEX idx_orders_customer ON orders (customer_id)EXPLAIN ANALYZE shows whether the plan uses it (an Index Scan).
CREATE TABLE orders_by_customer PARTITION BY order_date CLUSTER BY customer_id AS SELECT * FROM ordersNo indexes: partition a table by date and cluster it by the columns you filter on instead.