Question

The 'count' query runs fine. The 'Page of records' query runs fine as long as the commented section stays as-is. If uncommented it never returns... just keeps going. Any help on how to get past this would be greatly appreciated.

-- Page or records
DECLARE @p0 int;
DECLARE @p1 int;
SET @p0 = 100;
SET @p1 = 20;

SELECT DISTINCT ZIP_CODE, RowNum
FROM     ( SELECT ROW_NUMBER() OVER (ORDER BY ZIP_CODE) as RowNum, ZIP_CODE
           FROM   ODS.PHP1300_DWH.FACETS_MEMBER
           --WHERE LEFT(ZIP_CODE, 5) NOT IN (SELECT SHORT_ZIP_CODE 
                    --                     FROM DWH.Reference.R_ZIP_CODE)
         ) AS x
WHERE    RowNum BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY RowNum

-------------------------------------------------------------------------------------

-- Count
SELECT COUNT(ZIP_CODE)
FROM   ODS.PHP1300_DWH.FACETS_MEMBER  
WHERE  LEFT(ZIP_CODE, 5) NOT IN (SELECT SHORT_ZIP_CODE 
                                 FROM   DWH.Reference.R_ZIP_CODE)
Was it helpful?

Solution

I think that your predicate in the derived table is just quite expensive. Hard to say without an execution plan. Here are a couple of measures you can take:

  • Try making LEFT(FACETS_MEMBER.ZIP_CODE, 5) a computed column and index it
  • Be sure that R_ZIP_CODE.SHORT_ZIP_CODE has an index on it
  • Be sure that R_ZIP_CODE.SHORT_ZIP_CODE has a NOT NULL constraint on it.

Apart from that, I think that your DISTINCT keyword in the outer query is useless, as you're adding the RowNum, which is distinct for every record anyway. So you should move DISTINCT into your nested query, which should use DENSE_RANK() instead of ROW_NUMBER(), as explained here:

http://blog.jooq.org/2013/10/09/sql-trick-row_number-is-to-select-what-dense_rank-is-to-select-distinct/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top