Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Array Prefix Matching

Tags:

sql

postgresql

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]     |
like image 936
Kevin Sylvestre Avatar asked Jul 10 '13 01:07

Kevin Sylvestre


People also ask

What does ~* mean in PostgreSQL?

The tilde operator returns true or false depending on whether or not a regular expression can match a string or a part thereof. ~ (Matches regular expression, case sensitive) ~* (Matches regular expression, case insensitive)

What is Array_agg in Postgres?

PostgreSQL ARRAY_AGG() function is an aggregate function that accepts a set of values and returns an array where each value in the input set is assigned to an element of the array. Syntax: ARRAY_AGG(expression [ORDER BY [sort_expression {ASC | DESC}], [...]) The ORDER BY clause is an voluntary clause.

What is Unnest in PostgreSQL?

The PostgreSQL unnest() function allows you to expand one array at a time and also expand many arrays (of potentially different data types) into a set of rows.


2 Answers

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

like image 177
Roman Pekar Avatar answered Sep 29 '22 18:09

Roman Pekar


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
like image 28
bma Avatar answered Sep 29 '22 19:09

bma