Data Engineering

Splitting Strings: UNNEST and STRING_TO_ARRAY

SQL Mastery Team
April 14, 2026
6 min read

It's **Day 83**, and we're dealing with the "CSV inside a column" nightmare.

The Problem

A developer saved a user's interests as a single string: `"SQL, Python, Data, AI"`.

You want to know "How many people are interested in Python?" You can't easy group by that string!

The Solution: STRING_TO_ARRAY & UNNEST

In PostgreSQL, we can turn that string into a list, and then turn that list into **multiple rows**.

SELECT

user_id,

UNNEST(STRING_TO_ARRAY(interests, ', ')) as interest

FROM student_profiles;

Why this is a lifesaver

Once the interests are on different rows, you can use your Phase 2 skills:

SELECT interest, COUNT(*)

FROM (

-- Subquery with UNNEST here

)

GROUP BY interest;

Professional Tip

Saving data as comma-separated strings is "Bad Database Design" (It breaks First Normal Form). If you find yourself using `UNNEST` every day, شما should probably talk to your engineering team about a better table structure!

Your Task for Today

Take a comma-separated string and turn it into a list of individual rows.

*Day 84: Formatting Phone Numbers and IDs.*

Ready to put your knowledge into practice?

Join SQL Mastery and learn through interactive exercises.