Inserting JSON data in PostgreSQL - Time & Space Complexity
When inserting JSON data into a database, it's important to understand how the time taken grows as the amount of data increases.
We want to know how the insertion time changes when we add more JSON records.
Analyze the time complexity of the following code snippet.
INSERT INTO my_table (data_column)
VALUES
('{"name": "Alice", "age": 30}'),
('{"name": "Bob", "age": 25}'),
('{"name": "Carol", "age": 27}');
This code inserts multiple JSON records into a table's JSON column in one command.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Inserting each JSON record into the table.
- How many times: Once per JSON record being inserted.
As you add more JSON records to insert, the total work grows roughly in direct proportion to the number of records.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 insert operations |
| 100 | About 100 insert operations |
| 1000 | About 1000 insert operations |
Pattern observation: Doubling the number of JSON records roughly doubles the work done.
Time Complexity: O(n)
This means the time to insert grows linearly with the number of JSON records.
[X] Wrong: "Inserting multiple JSON records at once takes the same time as inserting just one."
[OK] Correct: Each record needs to be processed and stored, so more records mean more work and more time.
Understanding how insertion time grows helps you design efficient data loading and shows you can think about performance in real projects.
"What if we changed from inserting JSON records one by one to inserting them in a single batch? How would the time complexity change?"
Practice
json column named data?Solution
Step 1: Use single quotes for JSON string in SQL
In PostgreSQL, JSON data must be enclosed in single quotes as a string literal.Step 2: Use valid JSON format inside the string
The JSON must have double quotes around keys and string values, like {"name": "John", "age": 30}.Final Answer:
INSERT INTO table_name (data) VALUES ('{"name": "John", "age": 30}'); -> Option DQuick Check:
JSON string with single quotes and double quotes inside = D [OK]
- Using double quotes for the whole JSON string
- Using unquoted keys or single quotes inside JSON
- Trying to insert JSON without quotes
users with a jsonb column info?Solution
Step 1: Use jsonb type cast for jsonb columns
When inserting into a jsonb column, you can cast the string to jsonb usingjsonb '...'.Step 2: Use valid JSON string with double quotes inside single quotes
The JSON must be valid with double quotes around keys and string values.Final Answer:
INSERT INTO users (info) VALUES (jsonb '{"city": "NY", "zip": 10001}'); -> Option AQuick Check:
jsonb cast with valid JSON string = C [OK]
- Using double quotes for the whole JSON string
- Not casting to jsonb when required
- Using invalid JSON format without quotes
products with a json column details, what will be the result of this query?INSERT INTO products (details) VALUES ('{"color": "red", "size": "M"}');
SELECT details->>'color' FROM products WHERE details->>'size' = 'M';Solution
Step 1: Insert JSON with color and size keys
The insert adds a row with details containing color: red and size: M.Step 2: Select color where size equals 'M'
The SELECT filters rows where details->>'size' = 'M' and returns details->>'color', which is 'red'.Final Answer:
["red"] -> Option CQuick Check:
Filter by size 'M' returns color 'red' [OK]
- Using -> instead of ->> returns JSON, not text
- Expecting size value instead of color in output
- Not matching the filter condition correctly
INSERT INTO orders (info) VALUES ('{customer: "Alice", total: 50}');But it fails. What is the error and how to fix it?
Solution
Step 1: Identify invalid JSON format
JSON keys must be in double quotes, but here keys are unquoted (customer, total).Step 2: Fix JSON by adding double quotes around keys
Correct JSON is '{"customer": "Alice", "total": 50}'.Final Answer:
Missing double quotes around JSON keys; fix by adding double quotes around keys. -> Option BQuick Check:
JSON keys need double quotes = A [OK]
- Using unquoted keys in JSON
- Mixing single and double quotes incorrectly
- Assuming casting fixes invalid JSON format
events with a jsonb column payload. Which query correctly inserts two JSON objects in one statement?Solution
Step 1: Insert multiple rows with separate JSON objects
Use multiple VALUES tuples, each with a valid JSON string cast to jsonb.Step 2: Ensure JSON keys and strings are double-quoted
Each JSON object must have keys and string values in double quotes inside single quotes.Final Answer:
INSERT INTO events (payload) VALUES (jsonb '{"type": "click", "x": 10}'), (jsonb '{"type": "scroll", "y": 20}'); -> Option AQuick Check:
Multiple rows with valid JSON objects = A [OK]
- Trying to insert JSON array as one JSON object
- Using invalid JSON without quotes
- Not casting JSON string to jsonb when required
Ready to prove it?
Pass the test and this pattern moves unknown
