Every product has a price and a stock. But a T-shirt has sizes, a mug has a volume, and a plush has a height. A column for each fact would leave most cells NULL.
A JSON column holds a small document in each row. Each row can have its own keys.
JSON
JSON (JavaScript Object Notation) is a text format for data:
{
"color": "purple",
"size_cm": 30,
"washable": true,
"tags": ["plush", "kraken"]
}| Part | Example | Rule |
|---|---|---|
| object | { "color": "purple" } | keys and values in braces; keys in double quotes |
| array | ["plush", "kraken"] | a list of values in square brackets |
| text | "purple" | always in double quotes |
| number | 30, 29.99 | no quotes |
true, false, null | true | no quotes |
Objects and arrays can hold other objects and arrays.
The jsonb type
ALTER TABLE products ADD COLUMN details jsonb;
UPDATE products
SET details = '{"color": "red", "tags": ["mug"]}'
WHERE id = 10;- Write a JSON value as text, in single quotes. PostgreSQL checks it and stores it.
- Text that is not valid JSON fails:
invalid input syntax for type json. jsonbstores the document in a parsed, binary form. It does not keep the order of the keys or the spaces. Queries on it are fast.jsonstores the text exactly as you wrote it. Usejsonbunless you must keep the text.
When to use it
A JSON column fits data that changes shape from row to row, or that you store and read as one piece: settings, extra attributes, a copy of an API response. Data that you join, filter and change often belongs in normal columns, where types and constraints protect it.