TalentJR

🗄️ SQL for beginners · Class 12 · Lesson 17 of 18 · Free

SQL vs NoSQL Design – Tables or Documents for Your Data?

⏱ About 35 minutes · ▶ run real SQL here — nothing to install · no sign-in

In this lesson you will

  • Design the same data as related tables and as documents
  • Decide when to embed data in a document and when to reference it
  • Use a JSON column in SQL for flexible extra details

A tiffin service in your area takes orders for thalis, rolls and lassi. Should its app keep orders in tables with JOINs, or as documents like MongoDB (Lesson 4)? Both can work. The right choice depends on how the data is shaped and how it changes. This lesson builds the same orders both ways so you can compare.

What is the difference between SQL and NoSQL databases?

SQL (relational) databases keep data in tables with fixed columns. Each fact is stored once, and JOINs put facts together. NoSQL is a family of other designs. The common one, a document database like MongoDB, keeps each record as a JSON-like document.

Here is the tiffin service in four related tables, normalized as in Lesson 15. A dish's price lives only in dishes. The bill for each order comes from a JOIN and SUM (Lessons 7 and 8).

Try it: change the price of Lassi to 50 with an UPDATE before the SELECT and run again. Every bill that has Lassi changes.

📋 Tables in this example: customers, dishes, orders, order_items — tap to see how they are made
CREATE TABLE customers (
  id    INTEGER PRIMARY KEY,
  name  TEXT NOT NULL,
  phone TEXT NOT NULL,
  area  TEXT NOT NULL
);
CREATE TABLE dishes (
  id    INTEGER PRIMARY KEY,
  name  TEXT NOT NULL UNIQUE,
  price INTEGER NOT NULL
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  order_date  TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id INTEGER NOT NULL REFERENCES orders(id),
  dish_id  INTEGER NOT NULL REFERENCES dishes(id),
  qty      INTEGER NOT NULL CHECK (qty > 0),
  PRIMARY KEY (order_id, dish_id)
);
INSERT INTO customers VALUES (1, 'Riya Sharma', '90000 00001', 'Kothrud'), (2, 'Aman Verma', '90000 00002', 'Baner');
INSERT INTO dishes VALUES (1, 'Veg Thali', 120), (2, 'Dal Rice', 80), (3, 'Paneer Roll', 90), (4, 'Lassi', 40);
INSERT INTO orders VALUES (1, 1, '2026-11-30'), (2, 2, '2026-11-30'), (3, 1, '2026-12-01');
INSERT INTO order_items VALUES (1, 1, 2), (1, 4, 2), (2, 2, 1), (2, 3, 1), (3, 3, 2);
🗄️ SQL — you can edit this query
Result
┌──────────┬─────────────┬──────┐
│ order_id │ name        │ bill │
├──────────┼─────────────┼──────┤
│ 1        │ Riya Sharma │ 320  │
│ 2        │ Aman Verma  │ 170  │
│ 3        │ Riya Sharma │ 180  │
└──────────┴─────────────┴──────┘
(3 rows)

How is the same order stored in MongoDB?

In MongoDB the whole order is one document. The customer's details and the list of items sit inside it. This is called embedding.

Reading one order is easy: one document, no JOIN. The price is copied into the order, which is actually right for a bill: it keeps the price on the day of the order, even if the menu changes later.

📄 Example to read — MongoDB shell — shown, not run here
db.orders.insertOne({
  _id: 1,
  customer: { name: "Riya Sharma", phone: "90000 00001", area: "Kothrud" },
  date: "2026-11-30",
  items: [
    { dish: "Veg Thali", price: 120, qty: 2 },
    { dish: "Lassi",     price: 40,  qty: 2 }
  ]
})

db.orders.find({ "customer.name": "Riya Sharma" })

Can SQLite store documents like NoSQL?

Yes, in a simple way. SQLite can keep JSON text in a column and read inside it, as in Lesson 4. json_extract(doc, '$.customer.name') reads one value. json_each(doc, '$.items') turns the items list into rows.

So the same bills can be worked out from documents. CHECK (json_valid(doc)) makes sure only proper JSON gets stored.

Try it: change '$.customer.name' to '$.customer.area' and run again.

📋 Tables in this example: orders_doc — tap to see how they are made
CREATE TABLE orders_doc (
  id  INTEGER PRIMARY KEY,
  doc TEXT NOT NULL CHECK (json_valid(doc))
);
INSERT INTO orders_doc VALUES
 (1, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-11-30",
      "items": [{"dish": "Veg Thali", "price": 120, "qty": 2}, {"dish": "Lassi", "price": 40, "qty": 2}]}'),
 (2, '{"customer": {"name": "Aman Verma", "phone": "90000 00002", "area": "Baner"}, "date": "2026-11-30",
      "items": [{"dish": "Dal Rice", "price": 80, "qty": 1}, {"dish": "Paneer Roll", "price": 90, "qty": 1}]}'),
 (3, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-12-01",
      "items": [{"dish": "Paneer Roll", "price": 90, "qty": 2}]}');
🗄️ SQL — you can edit this query
Result
┌──────────┬─────────────┬──────┐
│ order_id │ name        │ bill │
├──────────┼─────────────┼──────┤
│ 1        │ Riya Sharma │ 320  │
│ 2        │ Aman Verma  │ 170  │
│ 3        │ Riya Sharma │ 180  │
└──────────┴─────────────┴──────┘
(3 rows)

When should I embed data and when should I reference it?

Embedding copies data into each document. That is great for things that belong to one order and should not change, like the price paid. It is risky for facts that change, like a phone number.

Riya gets a new phone. In the document design, her number is copied into every order she ever placed, so every copy must be found and changed. json_set changes a value inside the JSON. In the table design it is one row in customers.

Referencing means storing only an id, like customer_id, and looking it up (a JOIN). Try it: count how many documents still have the old number before the UPDATE.

📋 Tables in this example: orders_doc — tap to see how they are made
CREATE TABLE orders_doc (
  id  INTEGER PRIMARY KEY,
  doc TEXT NOT NULL CHECK (json_valid(doc))
);
INSERT INTO orders_doc VALUES
 (1, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-11-30",
      "items": [{"dish": "Veg Thali", "price": 120, "qty": 2}, {"dish": "Lassi", "price": 40, "qty": 2}]}'),
 (2, '{"customer": {"name": "Aman Verma", "phone": "90000 00002", "area": "Baner"}, "date": "2026-11-30",
      "items": [{"dish": "Dal Rice", "price": 80, "qty": 1}, {"dish": "Paneer Roll", "price": 90, "qty": 1}]}'),
 (3, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-12-01",
      "items": [{"dish": "Paneer Roll", "price": 90, "qty": 2}]}');
🗄️ SQL — you can edit this query
Result
2 rows updated.

┌────┬─────────────┐
│ id │ phone       │
├────┼─────────────┤
│ 1  │ 90000 09999 │
│ 2  │ 90000 00002 │
│ 3  │ 90000 09999 │
└────┴─────────────┘
(3 rows)

How do I choose between SQL and NoSQL?

Choose SQL tables when data is related and shared (students, marks, fees), when rules must always hold, and when money moves in transactions (Lesson 12). Choose documents when each record is mostly read whole, and records have very different shapes.

Many apps mix both. Here the core student columns are normal SQL columns. Extra details that differ per student sit in one JSON column, extras. The query finds everyone with chess as a hobby.

Try it: change 'chess' to 'cricket' and run again. Sara has no extras (NULL), so she never appears.

📋 Tables in this example: profiles — tap to see how they are made
CREATE TABLE profiles (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  class   INTEGER NOT NULL,
  extras  TEXT CHECK (extras IS NULL OR json_valid(extras))
);
INSERT INTO profiles VALUES
 (1, 'Riya Sharma', 12, '{"hobbies": ["chess", "coding"], "house": "Blue"}'),
 (2, 'Aman Verma', 12, '{"hobbies": ["cricket"], "sport_level": "district"}'),
 (3, 'Sara Khan', 12, NULL),
 (4, 'Dev Patil', 11, '{"hobbies": ["chess", "cricket", "music"]}');
🗄️ SQL — you can edit this query
Result
┌─────────────┬───────┐
│ name        │ class │
├─────────────┼───────┤
│ Dev Patil   │ 11    │
│ Riya Sharma │ 12    │
└─────────────┴───────┘
(2 rows)

🤔 Predict the output

Think like SQL: read the code and choose what it prints. You get the reason straight away.

Question 1. Order 1 is 2 Veg Thalis (₹120) and 2 Lassis (₹40). What is the bill?

📋 The tables (tap to see them)
CREATE TABLE customers (
  id    INTEGER PRIMARY KEY,
  name  TEXT NOT NULL,
  phone TEXT NOT NULL,
  area  TEXT NOT NULL
);
CREATE TABLE dishes (
  id    INTEGER PRIMARY KEY,
  name  TEXT NOT NULL UNIQUE,
  price INTEGER NOT NULL
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  order_date  TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id INTEGER NOT NULL REFERENCES orders(id),
  dish_id  INTEGER NOT NULL REFERENCES dishes(id),
  qty      INTEGER NOT NULL CHECK (qty > 0),
  PRIMARY KEY (order_id, dish_id)
);
INSERT INTO customers VALUES (1, 'Riya Sharma', '90000 00001', 'Kothrud'), (2, 'Aman Verma', '90000 00002', 'Baner');
INSERT INTO dishes VALUES (1, 'Veg Thali', 120), (2, 'Dal Rice', 80), (3, 'Paneer Roll', 90), (4, 'Lassi', 40);
INSERT INTO orders VALUES (1, 1, '2026-11-30'), (2, 2, '2026-11-30'), (3, 1, '2026-12-01');
INSERT INTO order_items VALUES (1, 1, 2), (1, 4, 2), (2, 2, 1), (2, 3, 1), (3, 3, 2);
SELECT SUM(oi.qty * d.price)
FROM order_items oi
JOIN dishes d ON d.id = oi.dish_id
WHERE oi.order_id = 1;

Question 2. What does this read from order 1?

📋 The tables (tap to see them)
CREATE TABLE orders_doc (
  id  INTEGER PRIMARY KEY,
  doc TEXT NOT NULL CHECK (json_valid(doc))
);
INSERT INTO orders_doc VALUES
 (1, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-11-30",
      "items": [{"dish": "Veg Thali", "price": 120, "qty": 2}, {"dish": "Lassi", "price": 40, "qty": 2}]}'),
 (2, '{"customer": {"name": "Aman Verma", "phone": "90000 00002", "area": "Baner"}, "date": "2026-11-30",
      "items": [{"dish": "Dal Rice", "price": 80, "qty": 1}, {"dish": "Paneer Roll", "price": 90, "qty": 1}]}'),
 (3, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-12-01",
      "items": [{"dish": "Paneer Roll", "price": 90, "qty": 2}]}');
SELECT json_extract(doc, '$.items[1].dish')
FROM orders_doc
WHERE id = 1;

Question 3. How many rows does json_each produce over all three orders?

📋 The tables (tap to see them)
CREATE TABLE orders_doc (
  id  INTEGER PRIMARY KEY,
  doc TEXT NOT NULL CHECK (json_valid(doc))
);
INSERT INTO orders_doc VALUES
 (1, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-11-30",
      "items": [{"dish": "Veg Thali", "price": 120, "qty": 2}, {"dish": "Lassi", "price": 40, "qty": 2}]}'),
 (2, '{"customer": {"name": "Aman Verma", "phone": "90000 00002", "area": "Baner"}, "date": "2026-11-30",
      "items": [{"dish": "Dal Rice", "price": 80, "qty": 1}, {"dish": "Paneer Roll", "price": 90, "qty": 1}]}'),
 (3, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-12-01",
      "items": [{"dish": "Paneer Roll", "price": 90, "qty": 2}]}');
SELECT COUNT(*)
FROM orders_doc o, json_each(o.doc, '$.items') i;

🧩 Your challenge

From the documents in orders_doc, show each customer's name, the number of orders and the total spent, ordered by name. Expected: Aman Verma | 1 | 170 and Riya Sharma | 2 | 500.

Expected result :
┌─────────────┬────────┬───────┐
│ name        │ orders │ spent │
├─────────────┼────────┼───────┤
│ Aman Verma  │ 1      │ 170   │
│ Riya Sharma │ 2      │ 500   │
└─────────────┴────────┴───────┘
(2 rows)
📋 Tables in this example: orders_doc — tap to see how they are made
CREATE TABLE orders_doc (
  id  INTEGER PRIMARY KEY,
  doc TEXT NOT NULL CHECK (json_valid(doc))
);
INSERT INTO orders_doc VALUES
 (1, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-11-30",
      "items": [{"dish": "Veg Thali", "price": 120, "qty": 2}, {"dish": "Lassi", "price": 40, "qty": 2}]}'),
 (2, '{"customer": {"name": "Aman Verma", "phone": "90000 00002", "area": "Baner"}, "date": "2026-11-30",
      "items": [{"dish": "Dal Rice", "price": 80, "qty": 1}, {"dish": "Paneer Roll", "price": 90, "qty": 1}]}'),
 (3, '{"customer": {"name": "Riya Sharma", "phone": "90000 00001", "area": "Kothrud"}, "date": "2026-12-01",
      "items": [{"dish": "Paneer Roll", "price": 90, "qty": 2}]}');
🗄️ SQL — you can edit this query

⚠️ Common mistakes (and how to fix them)

❌ Wrong

SELECT json_extract(doc, '$.items.price') AS first_price
FROM orders_doc
WHERE id = 2;

Runs, but gives the wrong result: ┌─────────────┐ │ first_price │ ├─────────────┤ │ NULL │ └─────────────┘ (1 row)

✅ Right

SELECT json_extract(doc, '$.items[0].price') AS first_price
FROM orders_doc
WHERE id = 2;

items is a list, so you must say which item: [0] is the first. '$.items.price' finds nothing and gives NULL.

❌ Wrong

INSERT INTO orders_doc VALUES
 (4, '{customer: {name: ''Sara Khan''}, items: []}');

Error in statement 1 (INSERT): CHECK constraint failed: json_valid(doc)

✅ Right

INSERT INTO orders_doc VALUES
 (4, '{"customer": {"name": "Sara Khan"}, "items": []}');

SELECT json_extract(doc, '$.customer.name') FROM orders_doc WHERE id = 4;

JSON needs double quotes around every key and text value. The MongoDB shell accepts bare keys, but JSON does not, so the CHECK (json_valid(doc)) rejects it.

❌ Wrong

SELECT name FROM profiles
WHERE extras = 'chess'
ORDER BY name;

Runs, but gives the wrong result: (no rows) — columns: name

✅ Right

SELECT name FROM profiles p
WHERE EXISTS (
    SELECT 1 FROM json_each(p.extras, '$.hobbies') h
    WHERE h.value = 'chess'
)
ORDER BY name;

The column holds a whole JSON document, so = compares the full text and matches nothing. Look inside the list with json_each.

📌 Remember

  • SQL databases store related tables and JOIN them; document databases store whole records as JSON-like documents.
  • Embed data that belongs to one record and should stay fixed, like the price paid on a bill.
  • Reference (store an id) for shared facts that change, like a customer's phone number.
  • SQLite can store and query JSON with json_extract, json_each and json_set; json_valid keeps it clean.
  • Many real apps mix both: fixed SQL columns plus one JSON column for flexible extras.

Finished the quiz and the challenge?

Questions students ask

Is NoSQL faster than SQL?

Not by itself. A document database can be quick at reading a whole record in one go. A SQL database with good indexes can be just as quick at JOINs and reports. Speed depends on the design and the queries, not the label.

Can MongoDB do transactions?

Yes. Changes to a single document are all-or-nothing, and modern MongoDB versions also support transactions across several documents. Relational databases were built around transactions from the start.

Which should I learn first, SQL or NoSQL?

Most people start with SQL, because the ideas (keys, JOINs, normalization, transactions) help with every database. Document databases are then easy to pick up.

What are the other kinds of NoSQL databases?

Besides document stores, there are key-value stores (look up a value by its key), wide-column stores and graph databases (for networks like friends of friends). Each one suits a different shape of data.