Aggregate JSON Data
In this step, we will explore how to aggregate data stored in JSONB
columns in PostgreSQL.
First, connect to the PostgreSQL database using the psql
command as the postgres
user:
sudo -u postgres psql
Aggregating JSONB
data often involves extracting values from the JSONB
objects and then applying aggregate functions like SUM
, AVG
, MIN
, MAX
, and COUNT
.
To calculate the average price of all products, you can use the following query:
SELECT AVG((data ->> 'price')::numeric) FROM products;
Here, we extract the price
as text using ->>
, cast it to a numeric type, and then calculate the average using the AVG
function.
Let's add a "category" field to our products:
UPDATE products SET data = jsonb_set(data, '{category}', '"Electronics"'::JSONB) WHERE id IN (1,4,5);
UPDATE products SET data = jsonb_set(data, '{category}', '"Accessories"'::JSONB) WHERE id IN (2,3);
UPDATE products SET data = jsonb_set(data, '{category}', '"Computers"'::JSONB) WHERE id IN (6);
Now, we can count the number of products in each category:
SELECT data ->> 'category', COUNT(*) FROM products GROUP BY data ->> 'category';
This query extracts the category
value as text and groups the rows based on this value.
Let's calculate the total price of all products in the "Electronics" category.
SELECT SUM((data ->> 'price')::numeric) FROM products WHERE data ->> 'category' = 'Electronics';
This query should return the sum of the prices of the Laptop, Monitor, and Gaming PC.
Finally, exit the psql
shell:
\q