2
SELECT u.id FROM user u WHERE u.id IN (7, 11)
if I have no results for the ids specified, I want to return all users, similar to this query :
SELECT u.id FROM user u
the difficulty and I want to keep the logical operator IN
to schematize my needs :
SELECT u.id FROM user u WHERE IF u.id IN (7, 11) = null THEN IN(*) ELSE IF u.id IN (7, 11) <> null THEN u.id IN (7, 11)
if possible avoid offering me a subquery, in the IN(*) part
Answers
You can achieve this requirement by using a combination of the CASE
statement and the COALESCE
function. Here's how you can modify your query to achieve the desired result:
SELECT u.id
FROM user u
WHERE u.id IN (7, 11)
OR u.id IN (SELECT COALESCE(NULLIF(id, id), id) FROM user);
Explanation:
- The
NULLIF
function compares two expressions and returnsNULL
if they are equal, otherwise it returns the first expression. Here, we are comparingid
with itself, so it will always returnNULL
. - The
COALESCE
function returns the first non-null expression among its arguments. So, whenNULLIF(id, id)
returnsNULL
,COALESCE
will returnid
. - In the subquery, we are selecting either
NULL
orid
. When there are no results for the specified ids, it will returnNULL
. - By using
COALESCE
, if the result of the subquery isNULL
, it will be replaced withid
, effectively returning all users.
This way, you can achieve the desired behavior while still using the IN
operator.
To achieve the desired behavior without using a subquery, you can use a combination of the COALESCE
function and a conditional expression. Here's how you can modify your query:
SELECT u.id FROM user u
WHERE COALESCE(u.id IN (7, 11), true);
In this query:
COALESCE(u.id IN (7, 11), true)
evaluates the expressionu.id IN (7, 11)
. If there are no results for the specified IDs (i.e.,u.id
is not in(7, 11)
), it returnsNULL
. TheCOALESCE
function replacesNULL
withtrue
, effectively returning all users.- If
u.id IN (7, 11)
returnstrue
, it returnstrue
, indicating that the user ID is in the specified list(7, 11)
, and the row is included in the result.
This approach allows you to maintain the logical operator IN
and achieve the desired behavior without using a subquery.