Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL json_array_elements_text Guide and Usage

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 json or jsonb data type.
  • Basic knowledge of SQL SELECT statements and CROSS JOIN LATERAL.

Step-by-Step

  1. Identify your JSON array column: Ensure your data is stored as a JSON array. For example, assume you have a table named products with a column named tags that contains values like ["electronics", "sale", "wireless"].
  2. Write a basic expansion query: To see the elements of a JSON array from a single record, call the function directly in the SELECT list.
    SELECT json_array_elements_text('["apple", "banana", "cherry"]'::json);
    This will return three separate rows: "apple", "banana", and "cherry".
  3. Apply the function to a table column: When working with a table, you cannot simply place the function in the SELECT clause if you want to keep other column data associated with the array elements. You must use a CROSS JOIN LATERAL.
    SELECT p.product_name, tag FROM products p, LATERAL json_array_elements_text(p.tags) AS tag;
    The LATERAL keyword allows the function to reference columns from the preceding table in the FROM clause.
  4. Filter results using the expanded text: Now that the array elements are converted to text rows, you can use standard WHERE clauses.
    SELECT p.product_name FROM products p, LATERAL json_array_elements_text(p.tags) AS tag WHERE tag = 'electronics';
  5. 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 BY clause.
    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_elements instead: The standard json_array_elements function returns json objects (which include double quotes around strings). json_array_elements_text is almost always preferred because it returns clean text without 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 WHERE clause or a simple SELECT` 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, use jsonb_array_elements_text. It is faster and more efficient than the standard json version.
  • Handle NULLs: If a row has a NULL value in the JSON column, the CROSS JOIN LATERAL will exclude that row from the results entirely. To keep rows that have no tags, use a LEFT JOIN LATERAL ... ON true.
  • Combine with DISTINCT: When expanding arrays, you often get duplicate values across different rows. Use SELECT DISTINCT to 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 of value, you are likely using json_array_elements. Switch to json_array_elements_text.
  • Missing Rows: If some rows from your main table are disappearing, it is because the JSON column is either NULL or an empty array []. Change your CROSS JOIN to a LEFT JOIN LATERAL to 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.