[Solved] CTE query associated with \"Where Clause\" not executing before evaluation condition in Where clause
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

CTE query associated with \"Where Clause\" not executing before evaluation condition in Where clause

I am facing a strange behaviour while executing the below query

WITH X1 AS 
(
  SELECT 1 AS N1, 0 AS N2
  UNION ALL
  SELECT 1 AS N1, 1 AS N2
)
,X2 AS
(
 SELECT * FROM X1 WHERE N2>0
)
SELECT N1,N2,N1/N2 FROM X2

Output: enter image description here

However when I put below where condition in above select statement

SELECT N1,N2,N1/N2 FROM X2
WHERE N1/N2>0

I get "Divide by zero error encountered." Please can anyone explain why I am getting this error?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 8): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
The optimized query:
WITH X1 AS (SELECT
        1 AS N1,
        0 AS N2 
    UNION
    ALL SELECT
        1 AS N1,
        1 AS N2), X2 AS (SELECT
        * 
    FROM
        X1 
    WHERE
        X1.N2 > 0) SELECT
        X2.N1,
        X2.N2,
        X2.N1 / X2.N2 
    FROM
        X2

Related Articles



* original question posted on StackOverflow here.