Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9241575
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T08:23:38+00:00 2026-06-18T08:23:38+00:00

I have a pretty complex query, but I applied some indexing and now it

  • 0

I have a pretty complex query, but I applied some indexing and now it runs very smoothly in less than 1 second. The structure of the query is like this (I find it unnecessary to post the full query as I will later prove – the fault is not in the query itself):

DECLARE @period varchar(6);
SET @period = '201302';

DECLARE @day datetime;
SET @day = dba.fnu_firstdate(@period);//returns 2013-02-01

SELECT
    user_id,
    (SELECT CAST(MAX(c1) AS varchar) FROM table t WHERE t.user_id = table.user_id AND when = DATEADD(day, 0, @day)) Day01,
    ...    
    (SELECT CAST(MAX(c1) AS varchar) FROM table t WHERE t.user_id = table.user_id AND when = DATEADD(day, 30, @day)) Day31
FROM
    table

So yeah, if I execute this query, it takes about 1 second to complete, which is perfectly fine for me. However, as you can see, I need to supply parameter for it. Thus I changed it to a table valued function so I could easily make select queries from it:

CREATE FUNCTION fnu_data(@period varchar(6))
RETURNS @results TABLE
(
    id int,
    Day01 varchar(10) null,
    ...
    Day31 varchar(10) null
)
AS
BEGIN
    DECLARE @day datetime;
    SET @day = dba.fnu_firstdate(@period);

    INSERT INTO @results 
    (
        id,     
        Day01,
        ...
        Day31
    )
    SELECT

SELECT
    user_id,
    (SELECT CAST(MAX(c1) AS varchar) FROM table t WHERE t.user_id = table.user_id AND when = DATEADD(day, 0, @day)) Day01,
    ...    
    (SELECT CAST(MAX(c1) AS varchar) FROM table t WHERE t.user_id = table.user_id AND when = DATEADD(day, 30, @day)) Day31
FROM
    table

RETURN

Now when I do

SELECT * FROM dba.fnu_data('201302')

it takes 6 seconds, which is way too long. Advised by my colleague I tried adding a primary index on id and replacing every subselect as joins, but it extended the time to execute the query to 8 seconds. (P.S. the query returns ~3200 rows).

In my opinion, the culprit is the insertion, but I do not see how I can get rid of it.

What can I do to improve my query?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T08:23:39+00:00Added an answer on June 18, 2026 at 8:23 am

    Not sure what might cause the difference in performance between the standalone SELECT and the INSERT ... SELECT as part of your function, but I could suggest a rewrite to your SELECT statement, as your SELECT looks definitely suboptimal to me.

    You seem to be doing a pivot, for which there’s a native syntax in SQL Server 2005+. Consider the following query:

    WITH data AS (
      SELECT
        user_id,
        DAY([when]) AS day,
        c1
      FROM [table] t
      CROSS APPLY (
        SELECT CAST(@period + '01' AS date)  -- this is supposed to be a replacement
                                             -- for dba.fnu_firstdate(), but you
                                             -- could use your function here instead
      ) x (startdate)
      WHERE t.day >= x.startdate
        AND t.day <  DATEADD(MONTH, 1, startdate)
    )
    INSERT INTO @results
    (
      id,
      Day01,
      ...
      Day31
    )
    SELECT
      id,     
      [1],
      ...
      [31]
    FROM data
    PIVOT (
      MAX(c1) FOR day IN ([1], [2], ..., [30], [31])
    ) p
    ;
    

    It prepares the data for the specified month as a separate step, using a common table expression, then pivots the results with aggregating, using the PIVOT syntax.

    Note that the above does the entire job using a single statement, which is also a SELECT statement. That means you could transform your multi-statement TVF into an inline TVF:

    IF OBJECT_ID('dba.fnu_data') IS NOT NULL
      DROP FUNCTION dba.fnu_data
    GO
    CREATE FUNCTION dba.fnu_data(@period varchar(6))
    RETURNS TABLE
    RETURN (
      WITH data AS (
        SELECT
          user_id,
          DAY([when]) AS day,
          c1
        FROM [table] t
        CROSS APPLY (
          SELECT CAST(@period + '01' AS date)
        ) x (startdate)
        WHERE t.day >= x.startdate
          AND t.day <  DATEADD(MONTH, 1, startdate)
      )
      SELECT
        id,
        CAST([1] AS varchar(30)) AS Day01,
        ...
        CAST([31] AS varchar(30)) AS Day31
      FROM data
      PIVOT (
        MAX(c1) FOR day IN ([1], [2], ..., [30], [31])
      ) p
    )
    GO
    

    An inline TVF has the advantage before a multi-statement TVF in that the plan for it is chosen in consideration with the entire query in which the function is being called. An inline TVF is like a view in this respect.

    Note that the transformation must be done using DROP + CREATE, like above, because multi-statement TVFs and inline TVFs are distinct kinds of objects in SQL Server, and one can’t be ALTERed into the other.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a View that is pretty complex. The query pulls data from about
This is a pretty complex MySQL query for me. what i have is a
I have a table with some persistent data in it. Now when I query
I have this rather complex query that grabs data from three tables, and now
I have a pretty complex SQL query which can't be done, or can't be
I have a pretty complex Linq statement with multiple joins, but am having a
I was wondering if I'm missing something. I have a pretty complex app, but
I have some pretty complex reports to write. Some of them... I'm not sure
I have a rather complex query that pretty much mimics a test query I
I have a pretty complex object graph G with an object o1 in G

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.