Questions
What is the `JSONB` data type and how do you use it in PostgreSQL?
The Scenario
You are a backend engineer at a social media company. You are building a new service that needs to store and query large amounts of JSON data.
You are considering using either a TEXT column or a JSONB column to store the JSON data.
The Challenge
Explain what the JSONB data type is in PostgreSQL and why it is a better choice than a TEXT column for storing JSON data. What are the key operators that you would use to query a JSONB column?
A junior engineer might try to store the JSON data in a `TEXT` column. This would work, but it would be very inefficient to query the data. They might not be aware of the `JSONB` data type or the special operators that can be used to query it.
A senior engineer would know that `JSONB` is the perfect tool for this job. They would be able to explain what `JSONB` is and how to use it to store and query JSON data efficiently.
Step 1: JSONB vs. TEXT
| Feature | TEXT | JSONB |
|---|---|---|
| Storage | Stores the JSON data as a string. | Stores the JSON data in a decomposed binary format. |
| Performance | Slow to query, because the entire string has to be parsed each time. | Fast to query, because the data is already in a binary format. |
| Indexing | Can be indexed with a full-text search index. | Can be indexed with a GIN index, which is much more efficient. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use a JSONB column. This is because we need to be able to query the JSON data efficiently.
Step 3: Code Examples
Here’s how we can create a table with a JSONB column:
CREATE TABLE my_table (
id SERIAL PRIMARY KEY,
my_data JSONB
);Here’s how we can insert some JSON data into the table:
INSERT INTO my_table (my_data) VALUES ('{"name": "John", "age": 30}');Here’s how we can query the JSON data:
-- Get the value of the "name" key
SELECT my_data->>'name' FROM my_table;
-- Check if the "age" key is greater than 25
SELECT * FROM my_table WHERE (my_data->>'age')::int > 25;
-- Check if the data contains a certain key
SELECT * FROM my_table WHERE my_data ? 'name'; Practice Question
You want to create an index on a `JSONB` column to speed up queries that use the `?` operator. Which type of index would you use?