[Solved] how is CTE giving output for the the below mentioned query
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

how is CTE giving output for the the below mentioned query

I am very new in sql programming .i have 2 questions based on the below mentioned query

WITH CTE_Stars AS
(
    SELECT CONVERT(VARCHAR(10), '*') Stars

    UNION ALL

    SELECT CONVERT(VARCHAR(10), CTE_Stars.Stars+'*') Stars 
    FROM CTE_Stars  
    WHERE LEN(Stars) < 6
)
SELECT * 
FROM CTE_Stars

Can someone explain how the above query is working and second this query does not work without convert function why..? Why do we need to convert '*' to character? By default * datatype is character only.

This query is giving output in 5 rows and that to without a loop.. how is this possible

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 Calling Functions With Indexed Columns (query line: 11): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `Stars` is indexed, the index won’t be used as it’s wrapped with the function `LEN`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  2. Avoid Selecting Unnecessary Columns (query line: 12): 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 CTE_Stars AS (SELECT
        CONVERT(VARCHAR(10),
        '*') Stars 
    UNION
    ALL SELECT
        CONVERT(VARCHAR(10),
        CTE_Stars.Stars + '*') Stars 
    FROM
        CTE_Stars 
    WHERE
        LEN(Stars) < 6) SELECT
        * 
    FROM
        CTE_Stars

Related Articles



* original question posted on StackOverflow here.