SQL vs. NoSQL and Sharding
What this lesson covers
A SQL database stores a record as rows across tables mapped by foreign keys, and a NoSQL database stores it as one blob of JSON. In SQL a person's address sits in a separate table. In NoSQL the address is an object nested inside the person's object. NoSQL has four advantages. The relevant data is kept together, so no join is needed. The schema is flexible, so a new attribute such as salary is added straight away, where SQL adds a column under locks on the table. Horizontal partitioning is built in, with a focus on availability. And NoSQL is built for aggregations. The disadvantages are that not many updates are supported, ACID is not guaranteed, relations are not implicit, and joins are hard and manual. NoSQL fits data that is a block, with many writes and few updates. Sharding is horizontal partitioning: one attribute of the data is the key that breaks the data into pieces, and each database server gets one chunk. Tinder shards on location, so a query for the users in one city reads a single shard. Sharding brings three problems. A join across shards crosses the network, which is extremely expensive. The shards are inflexible in number, so hierarchical sharding breaks a shard with too much data into smaller pieces. And a shard can fail, so writes go to a master and reads are distributed across the slaves. If the master fails, the slaves choose a master among themselves.
- NoSQL stores a record as one blob, while SQL splits related data across tables linked by foreign keys
- NoSQL fits data that is a block, with many writes and few updates
- Sharding is horizontal partitioning of data across database servers using a shard key
- Joins across shards are expensive because data must be combined over the network
- In a master-slave architecture writes go to the master and reads are distributed across the slaves