This is how my orders table looks like :
-----------------------------------------------------------
| id | order
-----------------------------------------------------------
|1 |[{"order_quantity" : 2, "active" : TRUE, "price" : $100 }, {"order_quantity" : 4, "active" : FALSE, "price" : $200 }]
|2 |[{"order_quantity" : 2, "active" : TRUE, "price" : $170 }]
|3 |[{"order_quantity" : 2, "active" : TRUE, "price" : $120 }]
|4 |[{"order_quantity" : 2, "active" : TRUE, "price" : $150 }, {"order_quantity" : 3, "active" : TRUE, "price" : $200 }, {"order_quantity" : 5, "active" : TRUE, "price" : $200 }]
-----------------------------------------------------------
the results wanted when doing the count for the JSON
elements inside the brackets WHERE active == TRUE
in each element :
------------
id | counts
------------
|1 | 1
|2 | 1
|3 | 1
|4 | 3
------------
This is what I'm using but it doesn't give the data i'm looking for because it doesn't not look into each dictionary to see if active == TRUE
SELECT id, json_array_length(order::JSON)
FROM orders
------------
id | counts
------------
|1 | 2
|2 | 1
|3 | 1
|4 | 3
------------
The PostgreSQL COUNT function counts a number of rows or non-NULL values against a specific column from a table. When an asterisk(*) is used with count function the total number of rows returns. The asterisk(*) indicates all the rows.
The COUNT(*) function returns the number of rows returned by a SELECT statement, including NULL and duplicates. When you apply the COUNT(*) function to the entire table, PostgreSQL has to scan the whole table sequentially. If you use the COUNT(*) function on a big table, the query will be slow.
PostgreSQL COUNT SELECTSELECT COUNT ( [*], [DISTINCT] [column_name] ) FROM TABLE_NAME; Let's dig a little deeper into the syntax shown above: SELECT – This is used to select certain columns from the database. COUNT – This is used to count the number of records in this table.
CHAR_LENGTH() function The PostgreSQL char_length function or character_length function is used to count the number of characters in a specified string. The CHARACTER_LENGTH() function is similar to CHAR_LENGTH() function. A string whose length is to be retrieved.
Use json_array_elements()
which selects all elements of the json array, filter the elements and finally count remaining elements grouping by id
.
select id, count(id)
from orders
cross join json_array_elements(orders) elem
where (elem->>'active')::boolean
group by 1
order by 1;
Live demo in Db<>fiddle.
Notes:
json_array_elements()
) in FROM
clause as lateral join;true
(not TRUE
);money
type in json, use 300
instead of $300
;If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With