AlgoViz

SQL databases

easy 25 min

A SQL (relational) database keeps data in tables with declared columns, joins those tables by key when you ask a question, and enforces rules such as unique emails and valid references.

When it comes up

The moments this idea belongs in a design interview, and the moments it does not.

Signals

When to bring it up

You hearSayBecause
Payments, stock, bookingsRelational, with constraints and a transactionA wrong answer costs more than a slow one
Reports we have not defined yetNormalised tables and SQLNew questions need no new model
A few terabytes, a few thousand writes a secondOne primary with a standby, to be load testedIt is plausible on one machine and simpler
Millions of writes a second by deviceNot one relational primaryWrites must be spread by key
Search by words with rankingSQL for truth, a search index beside itRanking is another job

In the interview

  • Draw keys and the two or three tables that matter
  • Name the constraint that prevents the bad case
  • Name the index for each hot query
  • Give the number that ends the design

Avoid

  • Listing ten tables with every column
  • "SQL does not scale"
  • Checking uniqueness only in code
  • Sharding before counting

Options

Compare your moves

The order history page takes two seconds. What do you do?

BreaksMove orders to another kind of database
How
Migrate to a store that is said to be faster.
Limit
Months of work, and the same missing access path there.
Choose when
The query and index are right and one machine still cannot hold the load.
WorksCache the page
How
Keep the rendered result for a minute.
Limit
The first read is still slow, and new orders appear late.
Choose when
The same page is read often and may be old.
StrongRead the plan, add an index on customer and date, page the result
How
The index returns the newest 20 rows directly, already sorted.
Limit
One more index to maintain on every insert.
Choose when
Almost always first.