Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 123»»»

Problem with Datetime Function Expand / Collapse
Author
Message
Posted Sunday, December 16, 2012 11:53 PM
SSC Journeyman

SSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC Journeyman

Group: General Forum Members
Last Login: Monday, November 24, 2014 7:42 AM
Points: 81, Visits: 943
I have SP which contains function
convert(varchar(12),[datetime],112) =convert(varchar(12),getdate(),112)
this takes lots of time during the Market hours and it is very essential as well.
Is there any alternate which we can use for this function
Post #1397101
Posted Monday, December 17, 2012 12:20 AM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Tuesday, September 9, 2014 2:06 AM
Points: 1,768, Visits: 8,318
So this is in a WHERE clause ??

Assuming so, this is what is known as a non-sargable condition.
Basically, as you have wrapped the datetime column in a function then SQL Server has to look at and process every row rather than use the more optimal route of an index.

Definition :
http://en.wikipedia.org/wiki/Sargable

One of the many blog articles available:
http://beyondrelational.com/modules/2/blogs/66/posts/9925/sargable-predicates.aspx





Clear Sky SQL
My Blog
Kent user group
Post #1397109
Posted Monday, December 17, 2012 12:43 AM
SSC Journeyman

SSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC Journeyman

Group: General Forum Members
Last Login: Monday, November 24, 2014 7:42 AM
Points: 81, Visits: 943
Yes it is being used in the where clause so what can be used instead of this fuction which will take less time
Post #1397112
Posted Monday, December 17, 2012 2:19 AM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Tuesday, September 9, 2014 2:06 AM
Points: 1,768, Visits: 8,318
Did you read those articles ?

Example 3 on the beyondrelational one is very close to what you require.




Clear Sky SQL
My Blog
Kent user group
Post #1397149
Posted Monday, December 17, 2012 6:27 AM


SSC-Insane

SSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-Insane

Group: General Forum Members
Last Login: Today @ 4:56 AM
Points: 20,815, Visits: 32,748
mahesh.dasoni (12/16/2012)
I have SP which contains function
convert(varchar(12),[datetime],112) =convert(varchar(12),getdate(),112)
this takes lots of time during the Market hours and it is very essential as well.
Is there any alternate which we can use for this function


Try this in your where clause:


([datetime] >= dateadd(dd, datediff(dd, 0, getdate()), 0) and
[datetime] < dateadd(dd, datediff(dd, 0, getdate()) + 1, 0))


Also, please note that your column name datetime is a very poor choice as it is also a reserved word.

The reason your current criteria is taking a long time to process is that SQL Server has to apply the convert function to every value of datetime in your table.



Lynn Pettis

For better assistance in answering your questions, click here
For tips to get better help with Performance Problems, click here
For Running Totals and its variations, click here or when working with partitioned tables
For more about Tally Tables, click here
For more about Cross Tabs and Pivots, click here and here
Managing Transaction Logs

SQL Musings from the Desert Fountain Valley SQL (My Mirror Blog)
Post #1397225
Posted Monday, December 17, 2012 7:33 AM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Tuesday, November 25, 2014 11:15 AM
Points: 292, Visits: 319
if the left side of the equal sign is a calculation, then the WHERE clause is "non sargeable", meaning that the optimizer can't use simple search arguments and must instead build an efficient query plan and must calculate every field in your table in this matter.

Maybe something like

-- midnight today
DECLARE @dFrom datetime = dateadd(dd, datediff(dd, 0, getdate()), 0)

-- 23:59:59 today
DECLARE @dTo datetime = DATEADD(dd, 1, @dFrom)

Then, in your WHERE clause:

[datetime] >= @dFrom AND [datetime] < @dTo

See if you get a better execution plan with this.
Post #1397257
Posted Monday, December 17, 2012 7:46 AM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Yesterday @ 10:21 AM
Points: 2,128, Visits: 5,561
Andre Ranieri (12/17/2012)
if the left side of the equal sign is a calculation, then the WHERE clause is "non sargeable", meaning that the optimizer can't use simple search arguments and must instead build an efficient query plan and must calculate every field in your table in this matter.

Maybe something like

-- midnight today
DECLARE @dFrom datetime = dateadd(dd, datediff(dd, 0, getdate()), 0)

-- 23:59:59 today
DECLARE @dTo datetime = DATEADD(dd, 1, @dFrom)

Then, in your WHERE clause:

[datetime] >= @dFrom AND [datetime] < @dTo

See if you get a better execution plan with this.


There is a very good chance that this will cause a table scan. A query plan is created only for data access statements (e.g. select, insert, update, delete, etc'). It completely ignores a variables assignment which is done in memory. In your example, the server will create a query plan without knowing the values of @dFrom and @dTo, so it will guess that 20% of the table's records will be selected. In the vast majority of times this will cause a table scan. It can work if you'll have the select statement in a different procedure and you'll send the values of @dFrom and @dTo as parameters to the procedure. This is because in the case of procedures and parameters, the server works with parameter sniffing.

Adi


--------------------------------------------------------------
To know how to ask questions and increase the chances of getting asnwers:
http://www.sqlservercentral.com/articles/Best+Practices/61537/

For better answers on performance questions, click on the following...
http://www.sqlservercentral.com/articles/SQLServerCentral/66909/
Post #1397265
Posted Monday, December 17, 2012 8:07 AM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Monday, November 17, 2014 12:50 PM
Points: 13,872, Visits: 9,598
Something that many don't know about SARGability is that some functions, regardless of side of equation in a Where clause, are SARGable.

Try this:

SET NOCOUNT ON;
USE ProofOfConcept;
GO
CREATE TABLE dbo.SARGTest (
DT DATETIME NOT NULL);
GO
CREATE CLUSTERED INDEX CID_SARGTest_DT ON dbo.SARGTest(DT);
GO
INSERT INTO dbo.SARGTest(DT)
SELECT TOP (1000000) DATEADD(DAY, CHECKSUM(NEWID())%10000, GETDATE())
FROM ProofOfConcept.dbo.Numbers AS N1
CROSS JOIN ProofOfConcept.dbo.Numbers AS N2;
GO
SELECT *
FROM dbo.SARGTest
WHERE DT >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
AND DT < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1);

SELECT *
FROM dbo.SARGTest
WHERE CAST(DT AS DATE) = CAST(GETDATE() AS DATE);

Check the execution plans on both of the final queries. We know the first query will result in an index seek. It follows the usual rules for SARGability. What's surprising to many is that the second one, with CAST() on the left (and right) of the Where clause, also results in an index seek.

(Actual execution plans attached.)

Also tested:

DECLARE @S DATE = GETDATE(), @E DATE = DATEADD(DAY, 1, GETDATE());

SELECT *
FROM dbo.SARGTest
WHERE DT >= @S AND DT < @E;

Still get a seek. (See Plan2.sqlplan, attached.)


- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
Property of The Thread

"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon


  Post Attachments 
Plans.sqlplan (3 views, 16.59 KB)
Plan2.sqlplan (4 views, 13.27 KB)
Post #1397274
Posted Monday, December 17, 2012 9:27 AM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: 2 days ago @ 9:10 AM
Points: 13,230, Visits: 12,709
Andre Ranieri (12/17/2012)
if the left side of the equal sign is a calculation, then the WHERE clause is "non sargeable", meaning that the optimizer can't use simple search arguments and must instead build an efficient query plan and must calculate every field in your table in this matter.



That just simply isn't true. The sql engine does not care at all which side of the equal sign a given predicate is located. If it were that simple to make it sargable you could switch the order of the equals predicate. I know that even the wiki article mentions the left side of the equation but consider this from the wiki example.

Non-Sargable: Select ... WHERE Year(date) = 2012

If it were try that to make it sargable the function can't be on the left side then that is like saying that the following is sargable

WHERE 2012 = Year(date)

The above is no more sargable than the first but the left side of the equation is a constant and not a function.


_______________________________________________________________

Need help? Help us help you.

Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

Need to split a string? Try Jeff Moden's splitter.

Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Understanding and Using APPLY (Part 1)
Understanding and Using APPLY (Part 2)
Post #1397316
Posted Monday, December 17, 2012 12:15 PM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Yesterday @ 10:21 AM
Points: 2,128, Visits: 5,561
GSquared (12/17/2012)
Something that many don't know about SARGability is that some functions, regardless of side of equation in a Where clause, are SARGable.

Try this:

SET NOCOUNT ON;
USE ProofOfConcept;
GO
CREATE TABLE dbo.SARGTest (
DT DATETIME NOT NULL);
GO
CREATE CLUSTERED INDEX CID_SARGTest_DT ON dbo.SARGTest(DT);
GO
INSERT INTO dbo.SARGTest(DT)
SELECT TOP (1000000) DATEADD(DAY, CHECKSUM(NEWID())%10000, GETDATE())
FROM ProofOfConcept.dbo.Numbers AS N1
CROSS JOIN ProofOfConcept.dbo.Numbers AS N2;
GO

Also tested:

[code="sql"]DECLARE @S DATE = GETDATE(), @E DATE = DATEADD(DAY, 1, GETDATE());

SELECT *
FROM dbo.SARGTest
WHERE DT >= @S AND DT < @E;

Still get a seek. (See Plan2.sqlplan, attached.)


I guess that the quoted part was written because of my previous message about the fact that using variables, assign them values and then use them in the same scope in the where clause will cause the server to do a table scan instead of seek operation. If I'm correct, then let be clearer about it. If you use a clustered index, then seek operation will be used. If you'll use an appropriate none clustered index that is also a covering index to this query, then you'll get seek operation. If you'll use none clustered index that is not covering, then most times you will get scan operation. In your example you had a table with one column and a clustered that is based on this column. Here is an example that is based on the code that you've added to your message:


CREATE TABLE dbo.SARGTest (
DT DATETIME NOT NULL, filler char(1) default ('a'));
GO

INSERT INTO dbo.SARGTest(DT)
SELECT TOP (1000000) DATEADD(DAY, CHECKSUM(NEWID())%10000, GETDATE())
FROM sys.objects
CROSS JOIN sys.objects as s2

CREATE INDEX CID_SARGTest_DT ON dbo.SARGTest(DT);


DECLARE @S datetime
declare @E datetime

SET @S = GETDATE()
SET @E = DATEADD(DAY, 1, GETDATE())

--Using the varibles cause table scan
SELECT *
FROM dbo.SARGTest
WHERE DT >= @S AND DT < @E;

--Using the same values but without the varibles use a table seek
SELECT *
FROM dbo.SARGTest
where DT > GETDATE() AND DT < DATEADD(DAY, 1, GETDATE())
go

drop table SARGTest




--------------------------------------------------------------
To know how to ask questions and increase the chances of getting asnwers:
http://www.sqlservercentral.com/articles/Best+Practices/61537/

For better answers on performance questions, click on the following...
http://www.sqlservercentral.com/articles/SQLServerCentral/66909/
Post #1397382
« Prev Topic | Next Topic »

Add to briefcase 123»»»

Permissions Expand / Collapse