I have a simple query in T-SQL:
SELECT
*
FROM
Table t
WHERE
t.Column IN ( 'Value1', 'Value2', 'Value3', ..., 'ValueN' )
;
Of course, the query is actually much more complex with a couple of JOINs and subqueries, but that does not matter at the moment.
The question is: Which of the following is faster in terms of performance?
(1) The original condition of
t.Column IN ( 'Value1', 'Value2', 'Value3', ..., 'ValueN' )
(2) Using a table ValueEnumeration with just one column named Value (being possibly a primary key), the table being populated with the values 'Value1', 'Value2', ...
SELECT
*
FROM
Table t
WHERE
t.Column in ( SELECT ve.Value FROM ValueEnumeration ve )
;
(3) Using a user defined function (UDF), a scalar function to be precise, called IsAllowedValue.
The function:
CREATE FUNCTION dbo.IsAllowedValue ( @ValueToCheck VARCHAR(20) ) RETURNS INT
AS
BEGIN
IF @ValueToCheck = 'Value1'
OR @ValueToCheck = 'Value2'
OR @ValueToCheck = 'Value3'
...
OR @ValueToCheck = 'ValueN'
BEGIN
RETURN 1;
END;
RETURN 0;
END
;
The query:
SELECT
*
FROM
Table t
WHERE
dbo.IsAllowedValue(t.Column) = 1
;
Well, I guess the first one will be the quickest solution. However, I need to perform a similar check in many places in my stored procedures. Once the original enumeration of values changes in the future (which is very likely to happen - e.g. a new value has to be added to it), you will have to go to all the occurrences of the original condition in your code and add the new value in there. Therefore, I decided for a more re-usable solution. But I don't know which one to choose. I sometimes need to do a test the other way around (WHERE t.Column NOT IN (...)
). It also came to my mind to use the table ValueEnumeration in an INNER JOIN
(for positive checks) or a LEFT OUTER JOIN
(for negative checks), but this will be painful to implement since I have approx. 50 locations of such conditions in the code and, in general, adding a JOIN considerably changes the look of the SQL query as well as the execution plan, the latter not always for good.
Do you have any idea?