Shard key
- SQL course
- Expert
- Lesson 28/45
- 5 min
Choose a shard key.
Shard key
The shard key is the column that decides which shard a row goes to. A good shard key spreads data evenly and keeps most queries within a single shard.
CREATE TABLE orders (id INT, created_at DATE)
PARTITION BY RANGE (created_at);The shard key drives distribution.
The table orders is created.
Shard key — details
A bad shard key (say, only true/false) piles data on two shards. A date shard key heaps old data on one shard. Customer ID usually spreads best.
Practice Shard key
Partition the orders table by date range with PARTITION BY RANGE (created_at).
Starter code
-- shard key
CREATE TABLE orders (id INT, created_at DATE)Sample solution
CREATE TABLE orders (id INT, created_at DATE) PARTITION BY RANGE (created_at);Expected output
CREATE TABLE
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Range partition
PARTITION BY ____ (created_at)
PARTITION BY RANGE (created_at)
Explanation: RANGE partitioning splits by a range of values such as created_at dates.
2 Shard key: match the terms
| Term | Meaning |
|---|---|
shard key |
shard key |
even |
even |
date |
date |
customer |
customer |
3 What makes a good shard key?
- It never changes
- It spreads data evenly Correct answer
- It has a single value
- It is historical
Explanation: A good shard key spreads data evenly.