Skip to content
Advertisement

How to check if one of several fields is in the set?

I am generating the SQL queries from the C++ code. (sqllite3)

I need to write efficiently the following request.

SELECT * FROM T
WHERE T.field1 IN (V1, V2, V3, ...) or T.field2 IN (V1, V2, V3, ...);

How to optimize it: avoid pasting two times (V1, V2, V3, …), or take sets intersection of (T.field1, T.field2) and (V1, V2, V3, …), or create statement local variable (V1, V2, V3, …), or whatever?

The SQL statement is created as a string and then passed to the SQL-parse engine.

Advertisement

Answer

Create a CTE with the values and use it like this:

WITH cte(x) AS (VALUES (V1), (V2), (V3), ....)
SELECT * FROM T
WHERE T.field1 IN (SELECT * FROM cte) 
   OR T.field2 IN (SELECT * FROM cte);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement