Sub topic 2
Storing JSON in a Table and Writing JSON Literals
This chapter assumes that you know basic SELECT, INSERT, UPDATE, WHERE, and JOIN statements. You should also understand JSON objects, arrays, strings, numbers, booleans, and null. The examples use PostgreSQL 12 or later.
Choosing `json` or `jsonb`
PostgreSQL provides two JSON data types:
jsonstores the original JSON text.jsonbstores a decomposed binary form that PostgreSQL can process more efficiently.
Both types validate JSON syntax when you insert a value. The difference is how PostgreSQL stores and works with the value.
| Type | Keeps input formatting | Supports efficient indexing | Typical use |
|---|---|---|---|
| `json` | Yes | Limited | Preserve the exact source text |
| `jsonb` | No | Yes | Query, filter, and index documents |
jsonb usually fits application data because it supports operators and indexes for searching inside documents. It can remove insignificant whitespace and does not preserve the order of object keys. Duplicate keys are also handled differently: the last value for a duplicate key is retained.
Use json when preserving the exact original representation matters, such as storing an incoming document for later reproduction. Use jsonb when the database needs to inspect or query the document.
Creating a table with a JSON column
A JSON column can store a complete object, an array, or another valid JSON value. In most business tables, an object is the useful top-level shape.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
details jsonb NOT NULL
);The details column is required, but this definition does not require a particular set of keys. PostgreSQL will reject invalid JSON syntax, but it will accept any valid JSON value, including [], "text", or 42.
You can make the intended shape clearer in application documentation or enforce parts of it with a CHECK constraint. Shape validation is covered later in the tutorial.
Writing JSON literals in SQL
A JSON object uses double quotes around its keys and string values. SQL string literals usually use single quotes. Therefore, this JSON can be inserted inside a SQL string:
INSERT INTO orders (customer, details) VALUES
('Ada', '{"status": "paid", "total": 42.50, "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}], "shipping": {"city": "Oslo"}}'),
('Grace', '{"status": "pending", "total": 10.00, "items": [{"sku": "A1", "qty": 1}], "shipping": {"city": "Bergen"}}');PostgreSQL converts the string to jsonb because details has that type. You can also make the conversion explicit:
INSERT INTO orders (customer, details)
VALUES (
'Lin',
'{"status": "paid", "total": 75.25}'::jsonb
);The ::jsonb notation is a cast. It tells PostgreSQL to interpret the value as jsonb before storing it.
For larger documents, dollar-quoted strings can make SQL easier to read. Dollar quoting allows the JSON to contain ordinary single quotes without doubling them.
INSERT INTO orders (customer, details)
VALUES (
'Mina',
$json$
{
"status": "pending",
"note": "Customer's requested delivery date",
"total": 18.00
}
$json$::jsonb
);The $json$ markers are SQL syntax, not part of the stored document. PostgreSQL still validates the content between them as JSON.
A practical storage boundary
Keep stable, frequently filtered attributes in ordinary columns when they are central to the table's purpose. Store flexible or rarely used attributes in jsonb.
For example, customer, created_at, and an order status used in many reports may deserve relational columns. A provider-specific shipping payload may fit better in details. A JSON column is not automatically a replacement for a relational design.
Exercise
Which type should you usually choose for application documents that PostgreSQL must query and index: json or jsonb?
Show answer
Choose jsonb. Choose json when preserving the exact original JSON text is the main requirement.