Brightlane's device inventory system identifies products that include GPS functionality. The GPS feature is recorded as a JSONB boolean within each product's attributes.
Write a query to return the ID and name of every product whose 'gps' attribute is the boolean true value.
Assumptions:
- Some products have a
'gps'key inattributeswhose value is a JSONB boolean (trueorfalse). Other products have no'gps'key on record. - A GPS-enabled product has its
'gps'key set to JSONBtrue. The text representation of JSONBtrueis the string'true'. - Only GPS-enabled products should appear.
Output:
- One row per qualifying product, with columns
idandname.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
name
FROM
products
WHERE
attributes ->> 'gps' = 'true' The shape
JSONB booleans extract to the text strings 'true' and 'false' via ->>. So a filter for GPS-enabled products compares the text result against the literal 'true'. The comparison stays in text on both sides, which is the simpler shape than casting to boolean and comparing against the boolean literal.
Clause by clause
SELECT id, namereturns the product's ID and name. No JSONB extraction is needed in the output because the inventory system only wants the list of GPS-enabled products, not the GPS value itself.FROM productsreads the product catalog.WHERE attributes ->> 'gps' = 'true'extracts the value at the'gps'key as text and keeps the row only when that text is exactly'true'. Products with no'gps'key extract to NULL (filtered out by the equality), products with'gps'set to JSONBfalseextract to'false'(also filtered out), and only products with'gps'set to JSONBtruesurvive.
Why this and not (attributes ->> 'gps')::boolean = true
The cast version works, and on a single value the runtime cost is negligible. But it's more characters of SQL for no semantic gain — both forms produce the same result. The text comparison is also more forgiving: if the JSONB document happens to carry a text 'true' instead of a boolean true (a real possibility when JSONB is produced by several different upstream systems), the text comparison catches both representations while the boolean cast would raise an error on the text form.
The trap
The string 'true' is case-sensitive. PostgreSQL renders JSONB booleans as lowercase 'true' and 'false', so comparing against 'True' or 'TRUE' would never match anything coming out of ->>. The boolean cast (::boolean) is more permissive — it accepts 'TRUE', 't', 'yes', and a few others — but that permissiveness only kicks in when the cast is the comparison mechanism. With the text form chosen here, the literal on the right has to match exactly what ->> produces, which is always the lowercase form.
You practiced ->> against a JSONB boolean — ->> returns the text form ('true' or 'false'); equality against the string literal works correctly without an explicit cast to boolean.