Course contentsShow
← Databases & SQL
Lesson 143 of 1,9532. Querying and Data RetrievalFree lesson

Handling JSON Document Attributes

Deep dive into semi-structured JSON fields to extract and filter specific keys.

In this lesson, you will learn how to reach inside a semi-structured JSON field to pluck out specific information for your reports.

Understanding JSON in SQL

In many modern databases, we store data as "JSON blobs" (JavaScript Object Notation). While standard relational tables have rigid columns like user_id or price, a JSON field is like a tiny file stored inside a single cell. It contains keys and values, but because they live inside one column, SQL doesn't "see" them as individual data points by default.

To work with this data, we use "path operators." Think of these like a treasure map: you provide the key name, and the database navigates into the document to retrieve the value.

Extracting Attributes

Let’s imagine we have a table called orders with a column named metadata. Inside metadata, we store a JSON object like this: {"color": "blue", "size": "large"}.

If we want to see all orders where the color is "blue," we can’t just say WHERE metadata = 'blue'. We have to use the extraction operator (commonly ->> in many SQL dialects) to tell the database to look inside the JSON for the key color:

SELECT order_id
FROM orders
WHERE metadata->>'color' = 'blue';

Filtering with JSON

The ->> operator extracts the value as text. Once it is extracted, you can treat it exactly like any other column. You can use it in your WHERE clauses, GROUP BY statements, or even perform joins on it.

If you are dealing with a nested JSON (a document inside a document), you can chain your operators to drill down deeper, such as metadata->'shipping'->>'zipcode'. This allows you to treat a flexible, semi-structured document as if it were a perfectly organized table. By navigating these paths, you transform invisible data hidden inside a blob into actionable intelligence for your queries.

Key Takeaway: Use path operators (like ->>) to extract specific keys from JSON fields, allowing you to treat semi-structured document attributes as standard columns in your filtering and retrieval logic.