I still use JSON datatypes in databases, and its proving to its worth. Postgresql loads the whole row during queries and this reduce access to other tables for join and retains data, instead of relying on dynamic changes of another table. JSONB type column is supported by Reportserver.net which I have mentioned in previous post.
Here is an example to use JSONB type column in Postgresql 12 and newer. Difference from previous post, here its saved as an object instead of an array. Use of JSON or JSONB type is very much determined by the data intended for storage and retrieval.
Points to note:
Symbol ->
meaning: Get JSON array element (indexed from zero, negative integers count from the end)
Or Get JSON object field by key
Symbol: ->>
meaning: Get JSON array element as text Or Get JSON object field as text
Symbol: @>
meaning: Does the left JSON value contain the right JSON path/value entries at the top level?
Step 1: Create the sample database
Step 2: Add sample data
Step 3: Run an SQL query
id|name |product |
--|-----------|-------------------------------------------------------------------------------------------------------|
3|Apple Pie |{"id": 5, "name": "Apple Pie", "details": {"value": "1All-1-1000-xzp", "source": "Malaysia"}} |
1|Orange Bod |{"id": 18, "name": "Orange Gala", "details": {"value": "1Bll-1-99-aaa", "source": "Malaysia"}} |
2|Chicken Pie|{"id": 4, "name": "Downtown Chicken Pie", "details": {"value": "1Bll-1-201-aaa", "source": "Malaysia"}}|
The WHERE clause
Lets retrieve rows where jsonb element key 'name' have a specific value.
SELECT id, name, product->'details' as details from products
where product->>'name'= 'Apple Pie'Retrieve rows where jsonb element key 'name' have a wildcard (%) value.
Retrieve rows where jsonb sub element key 'value' have a wildcard (%) value.
Retrieve rows where jsonb element have a specific key:value
No comments:
Post a Comment