7

I have an array search in Postgres hat matches at least one tag as this:

SELECT * FROM users WHERE tags && ['fun'];

| id | tags      |
| 1  | [fun,day] | 
| 2  | [fun,sun] |

It is possible to match on prefixes? Something like:

SELECT * FROM users WHERE tags LIKE 'f%';

| id | tags      |
| 1  | [fun,day] | 
| 2  | [fun,sun] |
| 3  | [far]     | 
| 4  | [fin]     |

2 Answers 2

5

try this

create table users (id serial primary key, tags text[]);

insert into users (tags)
values
  ('{"fun", "day"}'),
  ('{"fun", "sun"}'),
  ('{"test"}'),
  ('{"fin"}');

select *
from users
where exists (select * from unnest(tags) as arr where arr like 'f%')

SQL FIDDLE EXAMPLE

Sign up to request clarification or add additional context in comments.

4 Comments

That EXISTS clause is incorrect -- look at the results. It is missing a reference to the outer query to associate the rows. Try adding AND id = u.id (is "u" is the alias for the outer table). Fiddle updated: sqlfiddle.com/#!12/a6940/10/0
I have not much expirience in PostgreSQL (mostly in SQL server), but I'm pretty sure you're wrong about it, and BTW my query returns correct result in sqlfiddle. Exists is already working on current row tags, so your id = u.id. SQLFIDDLE is down at the moment, so I'll check it later.
basically my query could be rewritten as select * from users as u where exists (select * from unnest(u.tags) as arr where arr like 'f%')
Hmmm, looks like you are correct about your SQL Fiddle example. I must have misused it when I tested it. My apologies.
3

Here's a working example that should get you more or less what you're after. Note that I am not claiming that this approach will scale...

create table users (
id      serial primary key,
tags    text[] not null
);

insert into users (tags) values
('{"aaaa","bbbb","cccc"}'::text[]),
('{"badc","dddd","eeee"}'::text[]),
('{"gggg","ffbb","attt"}'::text[]);

select *
from (select id,unnest(tags) arr from users) u
where u.arr like 'a%';

 id | arr  
----+------
  1 | aaaa
  3 | attt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.