SQL vs NoSQL: Data Models, Guarantees and Migration Costs

SQL vs NoSQL starts with the data your application must keep consistent: separately related records, a document that changes as a unit, or items retrieved through known keys. The familiar claim that choosing NoSQL means abandoning transactions is wrong: MongoDB supports multi-document ACID transactions. For a product catalog, the practical choice is how to enforce identity and price rules while allowing attributes to vary, then how to read and migrate that data correctly.

Google · Preferred Sources

Don't miss new tech stories on Google

Add Tech Insider once in the Google app and our stories appear in your news suggestions.

Add Now

Survey usage spans both models

The Stack Overflow developer survey reports PostgreSQL use by 57.9% of respondents to its database question, compared with 19.0% for MongoDB. The 2026 question received 12,061 responses and asked which database environments people had used extensively during the preceding year. Respondents could select multiple products, so these are overlapping usage figures rather than shares of an exclusive database market.

DatabaseRespondentsUsage
PostgreSQL6,98457.9%
SQLite5,08342.1%
MySQL4,23535.1%
Redis3,41428.3%
Microsoft SQL Server3,27027.1%
MariaDB2,44620.3%
MongoDB2,29719.0%
DynamoDB1,1169.3%

Use this table to understand the technologies respondents encounter, then return to the workload. Choosing a document database still leaves questions about references, transactions and indexes.

Model the invariant, then the document

For a catalog, write down the rules before choosing a storage format: a source identifier must refer to a unique product, a SKU must not collide, and a price must be present and nonnegative. In PostgreSQL’s constraint model, primary keys enforce unique, non-null identifiers; unique constraints protect other keys; and foreign keys require a matching referenced row. A CHECK expression alone permits a null result, so a mandatory price also needs NOT NULL.

MongoDB’s data modeling documentation recommends organizing around access patterns. Documents in a collection can have different fields and types, while schema validation can enforce a fixed structure where needed. Relationships may be embedded or referenced. The decision is therefore where an application benefits from keeping data together and where separate records have independent lifecycles.

Catalog requirementPostgreSQL approachMongoDB approach
Stable product identityPrimary key on a product rowStable document identifier preserved by the application
Changing product attributesJSONB field beside typed columnsDifferent document fields and types within a collection
Related data read togetherRelated tables or a deliberately grouped JSON valueEmbed related data or reference another document
Mandatory structureColumn types, NOT NULL and CHECK constraintsSchema validation for the required document structure
Independent updatesSeparate rows for independently changing entitiesChoose references when embedding would couple their lifecycle

Our recommendation is to keep transaction-critical identifiers and prices explicit, and let genuinely variable descriptive attributes remain flexible. A department label copied into every product may make reads convenient, but changing that department then becomes an application-wide update problem. A referenced department and a product-specific snapshot serve different purposes.

Fresh reads and atomic writes are separate choices

MongoDB makes a single-document operation atomic. Its distributed transactions can cover multiple documents, collections, databases and shards, with changes committed together or rolled back. Read and write concern settings determine the guarantees, and MongoDB documents a higher performance cost for distributed transactions than for single-document writes. Embedding can avoid some transactions, but merely using documents does not remove the need to design for concurrent updates.

DynamoDB’s read consistency documentation makes the access path decisive. Tables and local secondary indexes support eventual or strong reads. Global secondary indexes and streams use eventual reads. On supported read operations, setting ConsistentRead to true returns data reflecting prior successful writes; using an alternate index cannot automatically inherit that behavior.

DynamoDB read pathAvailable consistencyApplication consequence
Table or local secondary indexEventual by default; strong reads availableRequest a strong read when the result must include prior successful writes
Global secondary index or streamEventually consistentDo not use this path as an immediate confirmation of a just-completed update
Global table using MRECMulti-Region eventual consistencyReplica visibility can lag the originating change
Global table using MRSCMulti-Region strong consistencyStrong reads on a replica return the latest item version

For example, after saving a catalog change, an editor may need to confirm the authoritative item immediately even if a secondary discovery view catches up later. Those are different reads with different requirements. Specify freshness independently from the atomicity of the write.

A product catalog can combine columns and JSON

PostgreSQL’s JSON type documentation describes JSONB indexing and its trade-offs. A catalog does not need to make its core identity flexible just because a camera and a shirt have different attributes. This schema keeps the imported identifier as text, constrains SKU and price, and leaves the attribute object adaptable:

CREATE TABLE products (
    source_id text PRIMARY KEY,
    sku text UNIQUE NOT NULL,
    name text NOT NULL,
    price_cents integer NOT NULL CHECK (price_cents >= 0),
    attributes jsonb NOT NULL DEFAULT '{}'::jsonb
);
CREATE INDEX products_attributes_gin
    ON products USING GIN (attributes);

SELECT sku, name
FROM products
WHERE attributes @> '{"color":"blue"}'::jsonb;

The GIN index supports the containment query shown here. Indexing the entire attribute value allows queries across its keys, while a targeted expression index can store only the attribute being searched. Choose the broader index because the application needs that flexibility, not simply because an index can be added.

JSONB also changes representation: duplicate object keys collapse to their last value, and key order and whitespace are not preserved. Updating a JSON document locks its whole row. A growing attribute object containing unrelated, frequently changed state can therefore create contention even when individual fields appear independent. Keep separate entities in separate rows when their updates should proceed independently.

This hybrid design is the useful middle ground in MongoDB versus PostgreSQL: select the relational constraints you need without forcing every descriptive attribute into a dedicated column. It also makes the migration mapping visible rather than hiding conversions inside the application.

Cloud bills follow requests or running capacity

A managed database bill depends on the service configuration as well as the data model. For relational deployments, compare the selected Aurora configuration with the alternatives in our managed SQL services comparison. DynamoDB’s pricing documentation separates consumed on-demand requests from provisioned throughput, while Aurora’s pricing documentation separates instance or serverless capacity, storage and I/O configuration. Comparing a monthly server quote with a request rate requires an actual workload and Region.

Service configurationCompute or request billing unitOther cost behavior
DynamoDB on-demand readsPer 4 KB or part: 0.5 RRU eventual, 1 RRU strong, 2 RRUs transactionalRead consistency and item size change consumption
DynamoDB on-demand writesPer 1 KB or part: 1 WRU standard, 2 WRUs transactionalTransactional writes use a different request unit count
DynamoDB provisionedHourly provisioned read and write capacityCapacity is billed even when the application consumes less
Aurora provisionedDB instance-hoursAurora Standard additionally charges storage and per-request I/O
Aurora ServerlessACUs billed per second; about 2 GiB memory per ACUCapacity has corresponding CPU and networking
Aurora I/O-OptimizedDatabase instances and storageNo separate read/write I/O operation charges

For catalog reads, record the item size and the consistency mode alongside request volume. For a relational deployment, include the capacity that remains running and the selected I/O configuration. An application that needs strong confirmation reads, transactional writes and broad secondary queries should budget those operations explicitly. A lower advertised entry price cannot decide the architecture before that workload is described.

Backfill identifiers without losing the final batch

A MongoDB-to-PostgreSQL move exposes the model boundary directly. The example below copies a paused source catalog into the preceding schema using PyMongo and Psycopg. It accepts ObjectId identifiers, preserves their text representation as source_id, and uses Psycopg’s JSONB adapter for attributes. Supply connection strings through MONGO_URI and PG_DSN in the process environment; the source namespace is shop.products.

The importer requires integer price_cents and string SKU and name fields. Missing required fields, invalid prices and incompatible attribute values stop the copy instead of silently manufacturing values. A target SKU collision also fails rather than merging separate source products. The batch size of 1000 is an example memory-management choice, not a throughput promise.

import os
from bson import ObjectId
from pymongo import MongoClient
import psycopg
from psycopg.types.json import Jsonb

BATCH_SIZE = 1000
UPSERT = """
INSERT INTO products (source_id, sku, name, price_cents, attributes)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (source_id) DO UPDATE SET
    sku = EXCLUDED.sku,
    name = EXCLUDED.name,
    price_cents = EXCLUDED.price_cents,
    attributes = EXCLUDED.attributes
"""

def backfill(documents, pg):
    batch = []
    with pg.cursor() as cur:
        def flush():
            if batch:
                cur.executemany(UPSERT, batch)
                pg.commit()
                batch.clear()

        for doc in documents:
            if not isinstance(doc['_id'], ObjectId):
                raise ValueError('This importer requires ObjectId source IDs')
            price = doc['price_cents']
            if isinstance(price, bool) or not isinstance(price, int) or price < 0:
                raise ValueError('price_cents must be a nonnegative integer')
            sku, name = doc['sku'], doc['name']
            attrs = doc.get('attributes', {})
            if not isinstance(sku, str) or not isinstance(name, str):
                raise ValueError('sku and name must be strings')
            if not isinstance(attrs, dict):
                raise ValueError('attributes must be an object')
            batch.append((str(doc['_id']), sku, name, price, Jsonb(attrs)))
            if len(batch) >= BATCH_SIZE:
                flush()
        flush()

if __name__ == '__main__':
    with MongoClient(os.environ['MONGO_URI']) as mongo:
        with psycopg.connect(os.environ['PG_DSN']) as pg:
            with mongo.shop.products.find({}, batch_size=BATCH_SIZE) as docs:
                backfill(docs, pg)

The final flush matters: a catalog that does not end exactly on a batch boundary still writes its remaining rows. Each completed batch commits independently. If a later batch fails, those earlier commits remain, and rerunning against the unchanged source updates the same source identifiers. The connection context rolls back an uncommitted failed batch; the upsert does not remove target rows that disappeared from the source.

Treat this as a paused-source backfill, not an online replication system. Keep writes paused through reconciliation, compare source identities and representative attribute values with the target, and resolve rejected records before switching the application. Concurrent source edits, deletes and a production cutover need an explicit change-capture and reconciliation design beyond this example. Preserving identity and proving that the last partial batch arrived are the minimum useful guarantees of the copy itself.

Nadia Dubois

Nadia Dubois

AI, software and the business of tech

Nadia Dubois covers AI, software and the business of tech for Tech Insider: AI models and the products built on them, developer and productivity software, pricing, and the company decisions and regulation that shape the industry.

View all articles