SQL vs NoSQL: Query Optimization, Indexing Strategies, and Schema Design
TL;DR
An architectural deep dive into relational versus document databases. Learn indexing strategies, execution plans, ACID vs BASE guarantees, and formatting complex queries.
Try the Interactive Tool
Format a representative SQL join before using your database’s explain plan to examine its cost.
Start with the order list the application actually reads
An operations dashboard needs the five newest paid orders for one tenant. It does not need line items to render the queue. A common mistake is to index the timestamp alone because it appears in the ordering clause. That can leave the database scanning entries from other tenants and states to find a few eligible orders. Write down the filters, ordering, projected fields, and typical number of matching rows before choosing keys. A separate detail view can fetch the items for a selected order.
The same product requirement can fit a relational database or a document database. The decision starts with how orders and items are used and updated. There is no useful benchmark in comparing two empty collections or treating the two data models as mutually exclusive classes with fixed consistency behavior. Compare the actual query plans and transaction needs of the engines you run.
Observe a SQLite scan and sort, then add a matching index
Run this in a fresh SQLite database. The fixture deliberately distributes rows between tenants and states. Using a fixed data set makes the two plans comparable. Format a more complicated version of the query in SQL Formatter if it is hard to review. Run EXPLAIN QUERY PLAN in SQLite to see the access plan. The formatter does not connect to a database.
Worked example
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
tenant TEXT,
state TEXT,
created_at INTEGER
);
WITH RECURSIVE n(i) AS (
SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i<1000
)
INSERT INTO orders
SELECT i, CASE WHEN i%2=0 THEN 'west' ELSE 'east' END,
CASE WHEN i%3=0 THEN 'paid' ELSE 'open' END, i
FROM n;
EXPLAIN QUERY PLAN
SELECT id, created_at
FROM orders
WHERE tenant='west' AND state='paid'
ORDER BY created_at DESC
LIMIT 5;
SQLite 3.54.0 printed this before the index existed.
QUERY PLAN
|--SCAN orders
`--USE TEMP B-TREE FOR ORDER BY
The scan must look at rows to evaluate the predicates, and the temporary structure is used to produce the requested order. LIMIT alone does not allow it to stop after reading the first five rows in table order. Those rows might not belong to the requested tenant, and later rows might sort ahead of them.
Add a compound index and repeat exactly the same EXPLAIN QUERY PLAN statement.
CREATE INDEX orders_queue ON orders(tenant, state, created_at DESC);
QUERY PLAN
`--SEARCH orders USING COVERING INDEX orders_queue (tenant=? AND state=?)
The two equality conditions identify a region of the index ordered by created_at. SQLite can get both selected fields from this index for this table, where the integer primary key aliases the rowid. Selecting another field may require a table lookup and remove the covering-plan label. That can be a fine trade for a small result set. Avoid adding every column to the index simply to keep the label. Wider indexes take more space and add maintenance to writes.
This example's actual query returned the following rows. These rows are a useful check that changing the plan did not change the requested results. Add a stable tie-breaker when multiple orders can have the same timestamp, especially when paginating.
996|996
990|990
984|984
978|978
972|972
Apply equality, sort, range to a MongoDB order queue
Here is a mongosh example for a separate scratch collection named orders_example. It filters on exact tenant and state values, asks for descending creation order, and restricts amount to a range. Keep the query and index together in a review so the ordering choice is visible.
const orders = db.getCollection("orders_example");
orders.insertMany(Array.from({ length: 1000 }, (_, i) => ({
tenant: i % 2 === 0 ? "west" : "east",
state: i % 3 === 0 ? "paid" : "open",
createdAt: i,
amount: i % 200
})));
orders.createIndex({ tenant: 1, state: 1, createdAt: -1, amount: 1 });
const filter = { tenant: "west", state: "paid", amount: { $gte: 100 } };
orders.find(filter).sort({ createdAt: -1 }).limit(5).explain("executionStats");
On a fresh scratch collection with this fixture, MongoDB 8.0.5 selected the index and returned five orders. These are the relevant fields captured from the plan and execution statistics.
indexName: tenant_1_state_1_createdAt_-1_amount_1
nReturned: 5
totalKeysExamined: 5
The MongoDB ESR guideline puts equality fields first. Placing the sort field next keeps the selected region in queue order. The range field comes after it so it does not split that order into amount buckets. This is a candidate index for the query, and the choice still depends on data distribution and the available indexes. In the explain result, inspect the winning plan for the index name and whether it needs a separate sort. Compare keys and documents examined with the number returned. If the amount predicate is extremely selective, an equality, range, sort index can be worth testing even if it requires a sort after filtering.
A small test collection may favor a collection scan. To inspect this specific candidate, repeat the query with a hint naming the index, then remove the hint to see what the optimizer chooses under realistic data. Keep both results distinct in notes. A forced plan demonstrates an available access path but cannot establish which plan production would pick. The MongoDB Formatter can make the query readable while reviewing it. Collect execution statistics from MongoDB itself.
Choose where order line items live
In a relational design, give orders an ID and store line items in a separate table with an order foreign key. That makes it natural to join an order with its items for detail screens while reading only the order table for the queue. It also lets you query line items across orders for inventory reports. For immutable purchase history, store the price charged on each item rather than assuming the current catalog price is correct. A foreign key to a product can identify the item without making the historical price depend on the current listing.
In a document design, embedding a bounded set of order lines in each order can make the detail read a single document lookup. Keep the immutable price and quantity in each embedded item. If item counts are unbounded, items have their own write lifecycle, or many operations search items independently, consider a separate collection. Also check how the queue projection avoids returning every embedded line when the UI only needs an order summary. Compare the read plan and write pattern before assuming embedding makes every endpoint cheaper.
For either model, test with orders that have zero, one, and many items, plus a queue with skewed tenant sizes. Capture the query plan before and after schema or index changes. The plan tells you what the engine decided for that fixture. The production decision also needs representative data, observed resource usage, and a clear account of the additional index writes.