Skip to content
Advertisement

How to search/select a list of composite index values and get the exact matching rows in SQL Server?

I have a list of value pairs that I have to search in a table in SQL Server. the table is something like this:

| id | class | value |
| 1  | A     | 300   |
| 2  | A     | 400   |
| 1  | B     | 500   |
| 2  | B     | 350   |
| 1  | C     | 230   |
| 2  | C     | 120   |

The columns id and class have an unique composite index that I want to take advantage of. Now I have this list of id-class pairs that I have to get from this table:

(1, A)
(2, B)

I need to select them to UPDATE the value of both rows to any value. Let’s say 1000.

My problem is, how do I select those two rows while taking advantage of the composite index?

I have tried this:

SELECT 
* 
FROM 
    table 
WHERE 
    id IN (1, 2) 
    AND class IN ('A','B')

But this returns me the combinations:

| id | class |
| 1  | A     |
| 1  | B     |
| 2  | A     |
| 2  | B     |

and I just want:

| id | class |
| 1  | A     |
| 2  | B     |

this would work:

SELECT 
* 
FROM 
    test 
WHERE 
    CAST(id as varchar)+class IN ('1A', '2B') 

but this breaks the index. Is there a way to get what I need while taking advantage of the index?

Advertisement

Answer

The follow scripts will take advantage of composite index:

SELECT
    *
FROM [table] T
INNER JOIN (
    SELECT
        1   AS ID
       ,'A' AS CLASS
    UNION
    SELECT
        2   AS ID
        ,'B' AS CLASS
) t2
    ON T.Id = t2.Id
        AND T.class = t2.class

or this:

SELECT
    *
FROM [table] T
WHERE (Id = 1 AND class = 'A') 
    OR (Id = 2 AND class = 'B')

or this:

WITH CTE AS(
        SELECT 1 AS ID, 'A' AS CLASS UNION
        SELECT 2 AS Id, 'B' AS CLASS
)     
SELECT
        *
    FROM [table] T
    WHERE EXISTS (
            SELECT 1
            FROM CTE t2
            WHERE T.Id = t2.Id
                AND T.class = t2.class
        ) 
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement