1

I want to fix some performance issue with the following query.

  • Tbl_A has 65 million rows
  • Tbl_B has 2 rows

I need to filter Tbl_A with the values of Tbl_b

 SELECT COUNT(*) 
 FROM Tbl_A R1 WITH (NOLOCK) 
      INNER JOIN Tbl_B PBD 
          ON PBD.Indicators = CASE R1.Indicator WHEN 'Y' THEN 'B'
                                                WHEN 'N' THEN 'D'       
                                                WHEN '1' THEN 'B'
                                                WHEN '0' THEN 'D'       
                                                ELSE R1.Indicator       
                             END

I have tried using in & exists instead of join, but I cant find any performance benefits. Please assist.

James Z
  • 12,209
  • 10
  • 24
  • 44
vignesh
  • 1,414
  • 5
  • 19
  • 38

2 Answers2

3

There is not much you can do here. You should have indexes on Tbl_A.Indicator and Tbl_B.Indicators of course.

The only option for a performance increase I see would be a persisted computed column:

ALTER TABLE tbl_a ADD pbd_indicator AS (CASE indicator WHEN 'Y' THEN 'B'
                                                       WHEN 'N' THEN 'D'       
                                                       WHEN '1' THEN 'B'
                                                       WHEN '0' THEN 'D'       
                                                       ELSE Indicator       
                                        END) PERSISTED;

Add the related index:

CREATE INDEX idx_tbl_a_pbd ON tbl_a(pbd_indicator);

And change the query accordingly:

SELECT COUNT(*) 
FROM tbl_a r1
INNER JOIN tbl_b pbd ON pbd.indicators = r1.pbd_indicator;
Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73
0

Try this, joining on case statement might take lot of logical reads, instead use case statement in inner query.

SELECT COUNT(*)
FROM (
    SELECT CASE Indicator
            WHEN 'Y'
                THEN 'B'
            WHEN 'N'
                THEN 'D'
            WHEN '1'
                THEN 'B'
            WHEN '0'
                THEN 'D'
            ELSE Indicator
            END AS Indicator
    FROM Tbl_b
    ) R1
INNER JOIN Tbl_a PBD
    ON PBD.Indicators = R1.indicator
Ven
  • 2,011
  • 1
  • 13
  • 27