Structured Primary Keys

30 points by giacomo_cavalieri


bjeanes

I've often pushed myself towards this style in my side projects for similar reasons but this is nicely articulated. I'm particularly motivated by thinking like "make invalid data unrepresentable" so making it impossible to associate an order with a shipping address belonging to a different customer has always felt like a good starting place (if that matches the domain, of course). The performance upsides here were quite secondary and not something I'd thought deeply about, so I appreciate learning more from this article :)

tomsmeding

I'm a bit of a database noob — took a course on SQL and worked with simple databases but nothing fancy. I don't understand the point of this article; it seems to carefully explain everything except the main point, which it just glances over: where does the performance benefit of the structured primary key come from?

The only thing I can think of, here, is that the select filters on customer_id, and since this is now the first part of the primary key of order_lines, no table scan of order_lines is necessary any more as there is an index we can use. This significantly reduces the number of redundant rows accessed and is thus good for performance. But then, the same performance benefit could have been got by adding an index on order_lines (or, indeed, on order) on (customer_id) or possibly more columns. So, it seems that the article assumes no additional indexes, which sounds odd to me.

But then the article goes:

With a structured primary key, the orders table does not need the id column at all. This often spares an index too.

So apparently we do implicitly assume some relevant indexes were created! But then that invalidates my understanding of the performance benefit.

Please help me: why is the query faster in the updated schema?

(Side note: because of the fetch first 1 row only, timings depend hugely on precisely where the first eligible row resides in the table, so the benchmark is suspect in my mind just for that!)