Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL WHERE IN LIKE query

I was wondering if it's possible to do a query using the IN clause where the options inside it are LIKE clauses, for example I have my existing SQL which returns the same results as I intend it just seems like a round about way to do it.

SELECT *
FROM pg_stat_activity
WHERE application_name NOT LIKE '%psql%'
AND (current_timestamp - state_change) > INTERVAL '30 minutes'
AND state IN (
    SELECT state
    FROM pg_stat_activity
    WHERE state LIKE '%idle%'
    OR state LIKE '%disabled%'
)

Is there a way to replace with something along the lines of

SELECT *
FROM pg_stat_activity
WHERE application_name NOT LIKE '%psql%'
AND (current_timestamp - state_change) > INTERVAL '30 minutes'
AND state IN ('%idle%', '%disabled%')
like image 597
TheLovelySausage Avatar asked Jun 28 '16 10:06

TheLovelySausage


People also ask

What is %s in Postgres?

s: It formats the argument value as a string. NULL values are treated as an empty strings. I: It treats the argument value as an SQL identifier. L: It makes the argument value as an SQL literal.

How do I do a wildcard search in PostgreSQL?

PostgreSQL provides you with two wildcards: Percent sign ( % ) matches any sequence of zero or more characters. Underscore sign ( _ ) matches any single character.

What is the difference between like and Ilike in PostgreSQL?

LIKE and ILIKE allow pattern matching within character-based column data. Their syntax is identical, but LIKE is case-sensitive, while ILIKE is case-insensitive.

How can you compare a part of name rather than entire name in PostgreSQL?

The % operator lets you compare against elements of an array, so you can match against any part of the name.


1 Answers

Use SIMILAR TO instead of LIKE

AND state SIMILAR TO '%(idle|disabled)%'

https://www.postgresql.org/docs/9.0/static/functions-matching.html

like image 87
Arsen Avatar answered Oct 14 '22 06:10

Arsen