Creating JSON columns in PostgreSQL - Performance & Efficiency
When we create JSON columns in a database, we want to know how the time to add or access data changes as the data grows.
We ask: How does the work grow when we store more JSON data in a column?
Analyze the time complexity of creating a table with a JSON column and inserting data.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
info JSONB
);
INSERT INTO users (info) VALUES ('{"name": "Alice", "age": 30}');
INSERT INTO users (info) VALUES ('{"name": "Bob", "age": 25}');
This code creates a table with a JSONB column and inserts JSON data into it.
Look for repeated actions that affect time.
- Primary operation: Inserting JSON data into the JSONB column.
- How many times: Once per row inserted; each insert handles the JSON data size.
As the JSON data size grows, the time to process each insert grows roughly in proportion to the JSON size.
| Input Size (JSON size in KB) | Approx. Operations |
|---|---|
| 1 | Small, quick insert |
| 10 | About 10 times more work than 1 KB |
| 100 | About 100 times more work than 1 KB |
Pattern observation: The time grows roughly linearly with the size of the JSON data being inserted.
Time Complexity: O(n)
This means the time to insert grows in a straight line as the JSON data size increases.
[X] Wrong: "Inserting JSON data always takes the same time no matter how big it is."
[OK] Correct: Larger JSON data means more characters to process and store, so it takes more time.
Understanding how JSON data size affects insert time helps you explain database performance clearly and confidently.
"What if we changed the JSONB column to a plain text column? How would the time complexity of inserts change?"
Practice
JSON column in a PostgreSQL table?Solution
Step 1: Understand JSON column usage
JSON columns allow storing data that can have varying structure, unlike fixed columns.Step 2: Compare with other options
Options A, C, and D do not describe JSON columns' purpose; they relate to other database features.Final Answer:
To store flexible, structured data inside a single column -> Option DQuick Check:
JSON columns = flexible data storage [OK]
- Thinking JSON columns enforce strict types
- Confusing JSON with indexing features
- Assuming JSON speeds numeric calculations
data?Solution
Step 1: Recall JSON column syntax
In PostgreSQL, JSON columns are declared with type JSON or JSONB directly.Step 2: Check each option
CREATE TABLE mytable (id INT, data JSON); uses correct syntax. Options A, B, and C use invalid or mixed types.Final Answer:
CREATE TABLE mytable (id INT, data JSON); -> Option BQuick Check:
JSON column syntax = CREATE TABLE mytable (id INT, data JSON); [OK]
- Using STRING or TEXT with JSON incorrectly
- Combining JSON with other types in declaration
- Missing commas or parentheses
CREATE TABLE products (id SERIAL, info JSONB); and the insert statement:INSERT INTO products (info) VALUES ('{"name": "Pen", "price": 1.5}');What will be the result of the query:
SELECT info->>'name' FROM products WHERE id = 1;Solution
Step 1: Understand JSONB insert and query
The JSONB column stores the JSON object. The operator ->> extracts the text value of the key.Step 2: Analyze the query
The query selects the 'name' field as text from the JSONB column for id 1, which is 'Pen'.Final Answer:
Pen -> Option CQuick Check:
info->>'name' = 'Pen' [OK]
- Using -> instead of ->> returns JSON, not text
- Expecting full JSON instead of single value
- Not matching the correct id in WHERE clause
CREATE TABLE users (id INT, profile JSONB DEFAULT {});But get a syntax error. What is the problem?
Solution
Step 1: Check default value syntax for JSONB
Default JSON values must be valid JSON strings, so '{}' must be in single quotes.Step 2: Identify the error cause
Using {} without quotes causes syntax error. Correct is DEFAULT '{}'.Final Answer:
Missing quotes around the default JSON value -> Option AQuick Check:
Default JSON must be quoted [OK]
- Using unquoted braces {} as default
- Assuming JSONB cannot have defaults
- Confusing data types in table definition
orders with a JSONB column details that stores order info. You also want to ensure each order has a customer_id and a details JSON with a total field as a number. Which approach correctly creates the table and enforces the total field presence?Solution
Step 1: Understand JSONB constraints
To ensure 'total' key exists and is not null, use a CHECK with details->>'total' IS NOT NULL.Step 2: Evaluate options
CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT NOT NULL, details JSONB NOT NULL CHECK (details ? 'total')); checks only key presence (details ? 'total'), but does not check value is not null. CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT NOT NULL, details JSONB NOT NULL CHECK (details->>'total' IS NOT NULL)); checks both key and value presence correctly.Final Answer:
CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT NOT NULL, details JSONB NOT NULL CHECK (details->>'total' IS NOT NULL)); -> Option AQuick Check:
CHECK ensures 'total' key with value [OK]
- Using ? operator without checking value
- Not adding NOT NULL constraints
- Setting default empty JSON without validation
Ready to prove it?
Pass the test and this pattern moves unknown
