PostgreSQL json_array_elements_text Guide and Usage
In this article
The json_array_elements_text function in PostgreSQL expands a JSON array into a set of text values. It transforms a single row containing a JSON array (e.g., ["red", "blue", "green"]) into multiple rows, where each row contains one element of that array as a standard PostgreSQL text data type. This is essential for filtering, joining, or aggregating data stored within JSONB or JSON columns.
What You'll Need
- A PostgreSQL database (version 9.4 or newer).
- A table containing a column with the
jsonorjsonbdata type. - Basic knowledge of SQL
SELECTstatements andCROSS JOIN LATERAL.
Step-by-Step
- Identify your JSON array column: Ensure your data is stored as a JSON array. For example, assume you have a table named
productswith a column namedtagsthat contains values like["electronics", "sale", "wireless"]. - Write a basic expansion query: To see the elements of a JSON array from a single record, call the function directly in the
SELECTlist.SELECT json_array_elements_text('["apple", "banana", "cherry"]'::json);
This will return three separate rows: "apple", "banana", and "cherry". - Apply the function to a table column: When working with a table, you cannot simply place the function in the
SELECTclause if you want to keep other column data associated with the array elements. You must use aCROSS JOIN LATERAL.SELECT p.product_name, tag FROM products p, LATERAL json_array_elements_text(p.tags) AS tag;
TheLATERALkeyword allows the function to reference columns from the preceding table in theFROMclause. - Filter results using the expanded text: Now that the array elements are converted to text rows, you can use standard
WHEREclauses.SELECT p.product_name FROM products p, LATERAL json_array_elements_text(p.tags) AS tag WHERE tag = 'electronics'; - Aggregate the results back: If you need to perform a count of how many times a specific tag appears across all products, use a
GROUP BYclause.SELECT tag, count(*) FROM products p, LATERAL json_array_elements_text(p.tags) AS tag GROUP BY tag ORDER BY count(*) DESC;
Common Mistakes
- Using
json_array_elementsinstead: The standardjson_array_elementsfunction returnsjsonobjects (which include double quotes around strings).json_array_elements_textis almost always preferred because it returns cleantextwithout the JSON formatting quotes. - Passing a JSON object instead of an array: This function only works on JSON arrays (indicated by
[ ]). If you pass a JSON object (indicated by{ }), PostgreSQL will throw an error stating that the function expects a JSON array. - Forgetting the LATERAL join: Trying to use the function in a
WHEREclause or a simpleSELECT` without a join often leads to unexpected row multiplication or syntax errors when referencing table columns.
Tips
- Use JSONB for Performance: If your column is
jsonb, usejsonb_array_elements_text. It is faster and more efficient than the standardjsonversion. - Handle NULLs: If a row has a
NULLvalue in the JSON column, theCROSS JOIN LATERALwill exclude that row from the results entirely. To keep rows that have no tags, use aLEFT JOIN LATERAL ... ON true. - Combine with DISTINCT: When expanding arrays, you often get duplicate values across different rows. Use
SELECT DISTINCTto get a unique list of all values present across all arrays in your table.
Troubleshooting
If the query does not go to plan, check the following:
- Error: "cannot extract elements from a scalar": This happens when the function encounters a JSON value that is not an array (like a single string or a number) instead of a list. Verify your data integrity using
SELECT * FROM table WHERE json_typeof(column) != 'array';. - Unexpected Double Quotes: If your output looks like
"value"instead ofvalue, you are likely usingjson_array_elements. Switch tojson_array_elements_text. - Missing Rows: If some rows from your main table are disappearing, it is because the JSON column is either
NULLor an empty array[]. Change yourCROSS JOINto aLEFT JOIN LATERALto ensure all parent rows are preserved.
Frequently Asked Questions
What is the difference between json_array_elements and json_array_elements_text?
json_array_elements returns a set of json values, meaning strings will still have surrounding double quotes. json_array_elements_text returns the actual text content of the element, removing the JSON quotes.
Can I use this function in a WHERE clause?
Not directly as a filter. You must expand the array in the FROM clause using LATERAL and then apply the WHERE filter to the resulting alias.
Does this function work with JSONB?
Yes, but PostgreSQL provides a specific version called jsonb_array_elements_text which is optimized for the jsonb binary format.
How do I handle empty arrays?
An empty array [] will result in zero rows being returned for that specific record when using a CROSS JOIN. Use a LEFT JOIN LATERAL to keep the record in your result set with a NULL value for the element.
Can I expand nested JSON arrays?
Yes, but you must chain the functions. You would use one LATERAL join to expand the first array, and a second LATERAL join to expand the arrays contained within those elements.