Blog / PostgreSQL

Working with Arrays in PostgreSQL: How to Utilize and Search for Values within an Array

Hey there, fellow data wranglers! Ever found yourself tangled up in a mess of country codes, wishing you could stash 'em all in one comfy place? Today, we're going to tackle that very problem using the magic of PostgreSQL. Let's dive right in, shall we?

Create Your Kingdom (AKA Your Table)

First things first, we've gotta lay the groundwork. Let's build ourselves a neat little table:

CREATE TABLE globetrotters (
    name TEXT NOT NULL,
    country_codes TEXT[] NOT NULL

Check it out: we've got an id for each of our world wanderers, a name, and – drumroll please – a country_codes field, which is an ARRAY of TEXT. That's right, folks, PostgreSQL lets us store an array of country codes right in one column! Nifty, huh?

Populate Your Kingdom

A kingdom's no good without its citizens, right? Let's populate our table with some globe-trotting data:

INSERT INTO globetrotters (name, country_codes) 
('John', ARRAY['SE', 'GB', 'DE']), 
('Emily', ARRAY['FR', 'GB']), 
('David', ARRAY['US', 'DE']);

Boom! John's made his way through Sweden, Great Britain, and Germany, while Emily's been to France and GB. David? He's a fan of the US and Germany.

Searching the Kingdom Far and Wide

Now comes the fun part. Let's say you want to find everyone who's visited Germany ('DE'). Here's how you can do that:

SELECT * FROM globetrotters WHERE 'DE' = ANY (country_codes);

See what we did there? The ANY keyword is like our magic wand, checking 'DE' against the country_codes ARRAY in each row. Abracadabra – all the folks who've been to Germany appear! Wrapping Up

And just like that, you've transformed into a PostgreSQL globetrotting wizard! Country codes no longer have to be a headache; instead, they're all snuggled up in one tidy array.

Remember, though, with great power comes great responsibility. ARRAYs are super handy, but they can also lead to headaches if you're not careful. If you're dealing with a heap of data or need to pull off some complex queries, consider using a separate join table to store the relationships between your entities and countries.

But hey, that's a story for another time. For now, go forth and conquer your data with your newfound PostgreSQL prowess! Happy coding, adventurers!