Z
Z
zxcursed2022-03-07 23:22:46
PostgreSQL
zxcursed, 2022-03-07 23:22:46

SELECT if present in column?

There is an 'index' column where values ​​are stored as "1, 2, 3". How to make a query by type:
value = 1
SELECT * FROM index WHERE value is in the column?
I thought about WHERE index IN value, but I think I'm wrong

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2022-03-07
@sergey-gornostaev

You need to read why relational bases are called relational and what normal forms are.

G
galaxy, 2022-03-08
@galaxy

Doing what you need is not a problem in Postgres, there are even several ways. For example:

SELECT * FROM table WHERE value = ANY(string_to_array(index, ', ')::int[])

You can also index if necessary.

V
Vyacheslav Uspensky, 2022-03-08
@Kwisatz

Pretty simple

create index my_table_index_index on my_schema.my_table using gin (cast(string_to_array(index, ', ') as int[]));

select *
from my_schema.my_table 
where string_to_array(index, ', ')::int[] @> ARRAY [1, 2, 3]::int[];

select *
from my_schema.my_table 
where cast(string_to_array(index, ', ') as int[]) @> cast(string_to_array(:param, ', ') as int[]);

The second version of the request is parameterized and the casts have been slightly altered so that there are no problems with the parameters.
param Must be a string of the form '1' or '1, 2, 3';
By the way, you can remake an array for storage exactly the same way as an index is built here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question