Brightlane's product merchandising system displays color attributes for catalog items.
Write a query to return the ID, name, and color attribute for product id = 7.
Assumptions:
- The
productstable has one row per product with anid, aname, and anattributesJSONB column. - Each product's
attributesvalue is a JSONB object whose keys depend on the product type. - Product
id = 7has a'color'key in itsattributes. The result should pull that value out as plain text.
Output:
- A single row with columns
id,name, andcolor.
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,
attributes ->> 'color' AS color
FROM
products
WHERE
id = 7 The shape
The ->> operator pulls a value out of a JSONB column and hands it back as plain text, which is exactly what the catalog display needs for the color field. With id = 7 already narrowing the read to a single row, the extraction runs once and the result is one row with three columns.
Clause by clause
SELECT id, name, attributes ->> 'color' AS colorreturns the product's ID and name straight from their columns, then reaches into theattributesJSONB object for the value stored under the'color'key and returns it as text. TheAS coloralias gives that extracted value a clean column name in the result.FROM productsreads the product catalog, where each row'sattributesis its own JSONB document with whatever keys that product type carries.WHERE id = 7filters the read down to the single row for product 7, so the JSONB extraction only runs against that one row and the result has exactly one row in it.
Why this and not attributes -> 'color'
Both operators read the same key, but -> keeps the result as JSONB and ->> strips it to text. For a display column where the consumer is the merchandising UI, text is what's wanted. A JSONB string carries its surrounding quotes as part of the value, so -> would return "Midnight" (quotes and all) instead of Midnight. The ->> form is the right one any time the next thing to do with the value is show it, compare it, or hand it to anything that isn't another JSONB operator.
You practiced attributes ->> 'key' — extract a JSONB object's value at a given key as a PostgreSQL text value.