Bird
0
0

You have a JSON column info in a dbt model with records like:

hard🚀 Application Q15 of 15
dbt - Advanced Patterns
You have a JSON column info in a dbt model with records like:
{"user": {"id": "U1", "tags": ["a", "b", "c"]}}

How would you write a dbt SQL expression to create a new row for each tag using PostgreSQL JSON functions?
ASELECT user_id, tag FROM table_name, json_array_elements_text(info->'user'->'tags') AS tag;
BSELECT user_id, unnest(info->'user'->'tags') AS tag FROM table_name;
CSELECT user_id, json_each_text(info->'user'->'tags') AS tag FROM table_name;
DSELECT user_id, explode(info->'user'->'tags') AS tag FROM table_name;
Step-by-Step Solution
Solution:
  1. Step 1: Identify function to expand JSON arrays in PostgreSQL

    PostgreSQL uses json_array_elements_text() to turn JSON arrays into a set of text rows.
  2. Step 2: Apply function to nested JSON array

    Extract the 'tags' array with info->'user'->'tags' and expand using comma syntax in FROM: SELECT user_id, tag FROM table_name, json_array_elements_text(info->'user'->'tags') AS tag.
  3. Final Answer:

    SELECT user_id, tag FROM table_name, json_array_elements_text(info->'user'->'tags') AS tag; -> Option A
  4. Quick Check:

    Use json_array_elements_text() to expand JSON arrays [OK]
Quick Trick: Use FROM table, json_array_elements_text(...) AS tag to explode JSON arrays in PostgreSQL [OK]
Common Mistakes:
MISTAKES
  • Using unnest() on JSON instead of arrays
  • Using json_each_text() which is for objects
  • Using explode() which is not PostgreSQL function

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More dbt Quizzes