Showing posts with label value. Show all posts
Showing posts with label value. Show all posts

Friday, March 30, 2012

Query Question

I have a query that I am not sure how to write.
I need to get the value of a column where that column's value happens more
than once AND a date column has the same date.
for instance:
ColA ColB
--
ValA 1/1/2003
ValA 1/1/2003
ValX 1/1/2003
I need to find all values from ColA where there is another row with the same
value in ColA and ColB (in this case the query should return ValA).
?SELECT DISTINCT colA
FROM Sometable
GROUP BY colA, colB
HAVING COUNT(*)>1
--
David Portas
--
Please reply only to the newsgroup
--|||Thanks David,
Makes sense and did the trick
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:-PWdnfOhm6CPriCi4p2dnA@.giganews.com...
> SELECT DISTINCT colA
> FROM Sometable
> GROUP BY colA, colB
> HAVING COUNT(*)>1
> --
> David Portas
> --
> Please reply only to the newsgroup
> --
>|||select cola from table_name
group by cola,colb
having count(*) >1
_______________________
"A" <agarrettbNOSPAM@.hotmail.com> wrote in message
news:OvXOcu6rDHA.1764@.TK2MSFTNGP10.phx.gbl...
> I have a query that I am not sure how to write.
> I need to get the value of a column where that column's value happens more
> than once AND a date column has the same date.
> for instance:
> ColA ColB
> --
> ValA 1/1/2003
> ValA 1/1/2003
> ValX 1/1/2003
> I need to find all values from ColA where there is another row with the
same
> value in ColA and ColB (in this case the query should return ValA).
> ?
>
>

Wednesday, March 28, 2012

Query problem

Hello Friends

I want to convert my float field (named Qty) to a float value with precision 2.
e.g. my Qty field hold 15.10000000000000001 and I wish to convert it into 15.10
I'm using SQL server 2000.

How could I write the query for this conversion.

Plz help me

Thanks

Declare @.float float
SET @.float = 2515.11111000000001

-- the optional third parameter of convert if 1 or 0
-- when applied to smallmoney or money will have only 2 numbers on right side of decimal
-- you can also add commas i.e. 12000.393939
-- if 1 would be 12,000.39
-- if 0 would be 12000.39
SELECT CONVERT(varchar, CONVERT(smallmoney, @.float), 1)

|||you can also do it in the design itself and not worry abt converting everytime you use it...set the column type to decimal and set the precision to 2. that way you dont have to worry abt the conversion everytime and also not lose any values when you do a reverse conversion...

hth|||Acutally I want to store the original value in the table but when i need it somewhere else then it has to be in such required conversion.

I knew ur solution but due to my requirement I'm expecting the proper query for that.

If u have the solution then plz reply me soon.

Thanks|||you can say

SELECT CONVERT(varchar, CONVERT(smallmoney, <column name>), 1) as [<column name>] from the table.

this will display the data without effecting the data base.

Friday, March 23, 2012

Query performence about nText

Is there any difference between a nText field value=' and value=NULL ?You should compare Null with is

where value='' or value IS Null

Madhivanan

Cylix wrote:

Quote:

Originally Posted by

Is there any difference between a nText field value='' and value=NULL ?

|||How about the volume?
Is NULL value also use the harddisk.|||Cylix wrote:

Quote:

Originally Posted by

How about the volume?
Is NULL value also use the harddisk.


Surely this doesn't make a significant difference. Unless you're
dealing with an embedded system, in which case surely you should
use a SQL engine specifically designed for embedded systems.|||Cylix (cylix2000@.gmail.com) writes:

Quote:

Originally Posted by

How about the volume?
Is NULL value also use the harddisk.


A text value consists of a 16-byte pointer which is stored in the row,
and then the rest of the data is stored outside the row. (Unless you
have set the table option "text in row".

The 16 byte pointer takes up space also for a NULL value. If any space
is allocated for the empty string, I will have to confess that I don't
know. You could examine this by creating two tables with ntext columns,
and fill one with NULL values and one with empty strings, and then use
sp_spaceused to see if there is any difference.

Permit me also to norice that ntext is a data type that is on its way out.
In SQL 2005 there is a new data type nvarchar(MAX) which just like ntext
permits 2GB of data, but works like regular nvarchar, and does not have
the many quirks of ntext.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspxsql

Wednesday, March 21, 2012

Query performance problems with join on UDF-based computed column

We have a table with a couple of computed columns. The value of the computed column represents a foreign key reference into another table. We're seeing a major performance problem doing a query joining between the two tables with one of the columns, but not the other. In other words, this kind of query is very fast:

select * from TheTable A, FKeyTable B
where A.ComputedColumn1 = B.KeyColumn

but this one sends the CPU usage of SQL Server to 99% for a very long time:

select * from TheTable A, FKeyTable B
where A.ComputedColumn2 = B.KeyColumn

The main difference we can see that the computed column that causes problems is based on a UDF, and the other one isn't (but again, both are computed). When I look at the execution plan, the slow query shows a Nested Loop (Inner Join) with a "No Join Predicate" warning, with the estimated # of rows being 70 million (which correponds to the product of 1016 rows in TheTable and 69K rows in FKeyTable). The fast query doesn't have that warning, and shows 1016 rows (the # of rows in TheTable).

Does anyone know why the usage of a UDF would induce this horribly inefficient join behavior? Anything we can do to fix it?

This is SQL Server 2005 SP2, btw.

By default, the engine does not know anything about the udf (i.e. has no statistics). So, bad plan can be generated.

To avoid this, I suggest that you create your udf with schemabinding and persist your computed column.

|||oj,
Thanks for the suggestions. I tried changing the UDF to use schema binding, but it didn't seem to effect the query plan at all. Persisting the computed column isn't a possibility here, as its value changes over time.
|||

Scalar udf is executed once per row which tends to be the cause for horrible performance. Now that we know that the values are non-deterministic, performance hit is almost unavoidable.

Can you post some ddl+sample data (insert)+sample code. We might be able to devise a solution.

|||

I'll see if I can come up with a simple repro.

What I don't understand is why a regular inline computed column (which is also non-deterministic) performs just fine, but the UDF version performs so horribly. I tried taking the computed column, which is essentially computing a time duration by calling datediff between "now" and a datetime stored in another column of the table, and converting the exact logic into a UDF. Once I do that, it has the same (bad) performance characteristics as my original problem - a Nested Loop with a "No Join Predicate" warning, 70M rows.

BTW, actually querying the column value is quite fast. It's the join that craters the performance.

|||

Have you tried explicitly creating a statistic for the column?

e.g.

create statistics _stats on table1(compute_col) with fullscan, norecompute

|||No luck. It complained that it "cannot be used in an index or statistics or as a partition key because it is non-deterministic."|||

Kevin, please post the requested info. Don't forget the udf code, too.

Note: you can use either free tool, objectscriptr or qalite from rac4sql.net to generate ddl+sample data.

|||

Here's the scripts (as far as I can tell, there's no attachment support on the forums....bummer). This is a seriously simplified version of our tables that reproduce the issue we're having.

The Create script:


Code Snippet

CREATE FUNCTION [dbo].[ComputeFKey](@.startTS datetime)
RETURNS float
with schemabinding
AS
BEGIN

RETURN datediff(minute,@.startTS,getutcdate())/(5)*(5)
END

go

CREATE TABLE [dbo].[JoinTable](
[KeyCol] [int] NOT NULL,
[MoreData] [int] NOT NULL,
CONSTRAINT [PK_JoinTable] PRIMARY KEY CLUSTERED
(
[KeyCol] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

go

CREATE TABLE [dbo].[MainTable](
[KeyCol] [int] IDENTITY(1,1) NOT NULL,
[CompCol] AS ((datediff(minute,[TSCol],getutcdate())/(5))*(5)),
[UdfCompCol] AS ([dbo].[ComputeFKey]([TSCol])),
[TSCol] [datetime] NOT NULL,
CONSTRAINT [PK_MainTable] PRIMARY KEY CLUSTERED
(
[KeyCol] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

go

Script to populate the join table:


Code Snippet

declare @.Start int
declare @.KeyVal int
declare @.RowsToAdd int
declare @.MoreData int

select @.RowsToAdd = 1000

if exists (select * from JoinTable)
select @.Start = max(KeyCol) + 5 from JoinTable
else
select @.Start = 0

select @.KeyVal = @.Start

while (@.KeyVal < (@.Start + @.RowsToAdd * 5))
begin
select @.MoreData = @.KeyVal % 60
insert into JoinTable (KeyCol, MoreData) values (@.KeyVal, @.MoreData)

select @.KeyVal = @.KeyVal + 5
end

Script to populate the main table:


Code Snippet

declare @.Row int
declare @.RowsToAdd int

select @.Row = 0
select @.RowsToAdd = 1000

while (@.Row < @.RowsToAdd)
begin
insert into MainTable (TSCol) values (DateAdd("hh", -1, getutcdate()))

select @.Row = @.Row + 1
end

Queries that demonstrate the issue:

Code Snippet


-- Fast query

select A.KeyCol from MainTable A, JoinTable B where A.CompCol = B.KeyCol

-- Slow query (Nested Loop with table spool)

select A.KeyCol from MainTable A, JoinTable B where A.UdfCompCol = B.KeyCol

The second query joins against the computed column that uses the UDF, and ends up with a Nested Loop with a table spool (a million rows in the Nested loop if you use the default values of the populate scripts - 1000 rows per table).

|||

Hi Kevin!

This is probably a bug, because MS SQL 2k behaves fine in this case (the execution plans are identical).

And btw, your function and column have different data types (float and integer).

|||

Oops - that was an error in creating my simplified repro case. The actual application schema has a CAST in the computed column. Thanks for catching that (though it doesn't affect the result). Replace the UdfCompCol definition with this:

[UdfCompCol] AS (CONVERT([int],[dbo].[ComputeFKey]([TSCol]),0))

|||

Thank you for posting the requested info. It's helpful to see what you're up against.

Now, to the _bad_ news. This is actually by design. Because you use getutcdate() within your udf, you make it non-deterministic. In sql2k, it is not possible to call getdate or getutcdate in a udf. Sql2k5 has loosen up this restriction but because the udf is marked as non-deterministric, the index seek (on jointable) is not possible. Therefore, the only option left for the engine is do a full scan of the jointable. Thus is the performance difference you see.

Btw, you can see that the perf is exactly identical for inline computed column versus udf computed column in sql2k. You will have to use the getdate_view trick though.

e.g.

Code Snippet

create view _utcdate
as
select getutcdate() [dt]
go
create FUNCTION [dbo].[ComputeFKey](@.startTS datetime)
RETURNS int
--with schemabinding
AS
BEGIN

RETURN (select datediff(minute,@.startTS,dt)/(5)*(5) from _utcdate)
END

go

-- Fast query

select A.KeyCol from MainTable A, JoinTable B where A.CompCol = B.KeyCol

-- Slow query (Nested Loop with table spool)

(1 row(s) affected)

StmtText
--
|--Hash Match(Inner Join, HASHSadBeer.[KeyCol])=(Angel.[CompCol]), RESIDUALSadBeer.[KeyCol]=Angel.[CompCol]))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[JoinTable].[PK_JoinTable] AS Beer))
|--Compute Scalar(DEFINESadAngel.[CompCol]=datediff(minute, MainTable.[TSCol], getutcdate)/5*5))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[MainTable].[PK_MainTable] AS Angel))

(4 row(s) affected)

StmtText
-

select A.KeyCol from MainTable A, JoinTable B where A.UdfCompCol = B.KeyCol

(1 row(s) affected)

StmtText
--
|--Hash Match(Inner Join, HASHSadBeer.[KeyCol])=(Angel.[UdfCompCol]), RESIDUALSadBeer.[KeyCol]=Angel.[UdfCompCol]))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[JoinTable].[PK_JoinTable] AS Beer))
|--Compute Scalar(DEFINESadAngel.[UdfCompCol]=[dbo].[ComputeFKey](Convert(MainTable.[TSCol]))))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[MainTable].[PK_MainTable] AS Angel))

|||

I kind of figured that would be the answer. However, I still don't understand why the same computation, when done directly in a computed column (but equally non-deterministic), has good performance characteristics. It probably doesn't matter much, since I'm guessing there is no real fix here. I'm just curious.

|||

As shown in the query plan for both queries on sql2k, the index/table scan is used. This is the same as in sql2k5 with the udf.

The inline computed column is calculated differently than the udf. Although, it in itself is non-deterministic, the sql2k5 is enhanced (made smarter) to use the available statistics based on the index key to perform an index seek.

In sql2k8, you can force an index seek but it's still not going to be possible for non-deterministic udf.

|||

Hi Oj!

It is not the same as in sql2k5.

I would understand if 2k5 spools the results of the function, but I don't understand why does it spool JoinTable? It does not make any sense...

Query performance problems with join on UDF-based computed column

We have a table with a couple of computed columns. The value of the computed column represents a foreign key reference into another table. We're seeing a major performance problem doing a query joining between the two tables with one of the columns, but not the other. In other words, this kind of query is very fast:

select * from TheTable A, FKeyTable B
where A.ComputedColumn1 = B.KeyColumn

but this one sends the CPU usage of SQL Server to 99% for a very long time:

select * from TheTable A, FKeyTable B
where A.ComputedColumn2 = B.KeyColumn

The main difference we can see that the computed column that causes problems is based on a UDF, and the other one isn't (but again, both are computed). When I look at the execution plan, the slow query shows a Nested Loop (Inner Join) with a "No Join Predicate" warning, with the estimated # of rows being 70 million (which correponds to the product of 1016 rows in TheTable and 69K rows in FKeyTable). The fast query doesn't have that warning, and shows 1016 rows (the # of rows in TheTable).

Does anyone know why the usage of a UDF would induce this horribly inefficient join behavior? Anything we can do to fix it?

This is SQL Server 2005 SP2, btw.

By default, the engine does not know anything about the udf (i.e. has no statistics). So, bad plan can be generated.

To avoid this, I suggest that you create your udf with schemabinding and persist your computed column.

|||oj,
Thanks for the suggestions. I tried changing the UDF to use schema binding, but it didn't seem to effect the query plan at all. Persisting the computed column isn't a possibility here, as its value changes over time.
|||

Scalar udf is executed once per row which tends to be the cause for horrible performance. Now that we know that the values are non-deterministic, performance hit is almost unavoidable.

Can you post some ddl+sample data (insert)+sample code. We might be able to devise a solution.

|||

I'll see if I can come up with a simple repro.

What I don't understand is why a regular inline computed column (which is also non-deterministic) performs just fine, but the UDF version performs so horribly. I tried taking the computed column, which is essentially computing a time duration by calling datediff between "now" and a datetime stored in another column of the table, and converting the exact logic into a UDF. Once I do that, it has the same (bad) performance characteristics as my original problem - a Nested Loop with a "No Join Predicate" warning, 70M rows.

BTW, actually querying the column value is quite fast. It's the join that craters the performance.

|||

Have you tried explicitly creating a statistic for the column?

e.g.

create statistics _stats on table1(compute_col) with fullscan, norecompute

|||No luck. It complained that it "cannot be used in an index or statistics or as a partition key because it is non-deterministic."|||

Kevin, please post the requested info. Don't forget the udf code, too.

Note: you can use either free tool, objectscriptr or qalite from rac4sql.net to generate ddl+sample data.

|||

Here's the scripts (as far as I can tell, there's no attachment support on the forums....bummer). This is a seriously simplified version of our tables that reproduce the issue we're having.

The Create script:


Code Snippet

CREATE FUNCTION [dbo].[ComputeFKey](@.startTS datetime)
RETURNS float
with schemabinding
AS
BEGIN

RETURN datediff(minute,@.startTS,getutcdate())/(5)*(5)
END

go

CREATE TABLE [dbo].[JoinTable](
[KeyCol] [int] NOT NULL,
[MoreData] [int] NOT NULL,
CONSTRAINT [PK_JoinTable] PRIMARY KEY CLUSTERED
(
[KeyCol] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

go

CREATE TABLE [dbo].[MainTable](
[KeyCol] [int] IDENTITY(1,1) NOT NULL,
[CompCol] AS ((datediff(minute,[TSCol],getutcdate())/(5))*(5)),
[UdfCompCol] AS ([dbo].[ComputeFKey]([TSCol])),
[TSCol] [datetime] NOT NULL,
CONSTRAINT [PK_MainTable] PRIMARY KEY CLUSTERED
(
[KeyCol] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

go

Script to populate the join table:


Code Snippet

declare @.Start int
declare @.KeyVal int
declare @.RowsToAdd int
declare @.MoreData int

select @.RowsToAdd = 1000

if exists (select * from JoinTable)
select @.Start = max(KeyCol) + 5 from JoinTable
else
select @.Start = 0

select @.KeyVal = @.Start

while (@.KeyVal < (@.Start + @.RowsToAdd * 5))
begin
select @.MoreData = @.KeyVal % 60
insert into JoinTable (KeyCol, MoreData) values (@.KeyVal, @.MoreData)

select @.KeyVal = @.KeyVal + 5
end

Script to populate the main table:


Code Snippet

declare @.Row int
declare @.RowsToAdd int

select @.Row = 0
select @.RowsToAdd = 1000

while (@.Row < @.RowsToAdd)
begin
insert into MainTable (TSCol) values (DateAdd("hh", -1, getutcdate()))

select @.Row = @.Row + 1
end

Queries that demonstrate the issue:

Code Snippet


-- Fast query

select A.KeyCol from MainTable A, JoinTable B where A.CompCol = B.KeyCol

-- Slow query (Nested Loop with table spool)

select A.KeyCol from MainTable A, JoinTable B where A.UdfCompCol = B.KeyCol

The second query joins against the computed column that uses the UDF, and ends up with a Nested Loop with a table spool (a million rows in the Nested loop if you use the default values of the populate scripts - 1000 rows per table).

|||

Hi Kevin!

This is probably a bug, because MS SQL 2k behaves fine in this case (the execution plans are identical).

And btw, your function and column have different data types (float and integer).

|||

Oops - that was an error in creating my simplified repro case. The actual application schema has a CAST in the computed column. Thanks for catching that (though it doesn't affect the result). Replace the UdfCompCol definition with this:

[UdfCompCol] AS (CONVERT([int],[dbo].[ComputeFKey]([TSCol]),0))

|||

Thank you for posting the requested info. It's helpful to see what you're up against.

Now, to the _bad_ news. This is actually by design. Because you use getutcdate() within your udf, you make it non-deterministic. In sql2k, it is not possible to call getdate or getutcdate in a udf. Sql2k5 has loosen up this restriction but because the udf is marked as non-deterministric, the index seek (on jointable) is not possible. Therefore, the only option left for the engine is do a full scan of the jointable. Thus is the performance difference you see.

Btw, you can see that the perf is exactly identical for inline computed column versus udf computed column in sql2k. You will have to use the getdate_view trick though.

e.g.

Code Snippet

create view _utcdate
as
select getutcdate() [dt]
go
create FUNCTION [dbo].[ComputeFKey](@.startTS datetime)
RETURNS int
--with schemabinding
AS
BEGIN

RETURN (select datediff(minute,@.startTS,dt)/(5)*(5) from _utcdate)
END

go

-- Fast query

select A.KeyCol from MainTable A, JoinTable B where A.CompCol = B.KeyCol

-- Slow query (Nested Loop with table spool)

(1 row(s) affected)

StmtText
--
|--Hash Match(Inner Join, HASHSadBeer.[KeyCol])=(Angel.[CompCol]), RESIDUALSadBeer.[KeyCol]=Angel.[CompCol]))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[JoinTable].[PK_JoinTable] AS Beer))
|--Compute Scalar(DEFINESadAngel.[CompCol]=datediff(minute, MainTable.[TSCol], getutcdate)/5*5))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[MainTable].[PK_MainTable] AS Angel))

(4 row(s) affected)

StmtText
-

select A.KeyCol from MainTable A, JoinTable B where A.UdfCompCol = B.KeyCol

(1 row(s) affected)

StmtText
--
|--Hash Match(Inner Join, HASHSadBeer.[KeyCol])=(Angel.[UdfCompCol]), RESIDUALSadBeer.[KeyCol]=Angel.[UdfCompCol]))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[JoinTable].[PK_JoinTable] AS Beer))
|--Compute Scalar(DEFINESadAngel.[UdfCompCol]=[dbo].[ComputeFKey](Convert(MainTable.[TSCol]))))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[MainTable].[PK_MainTable] AS Angel))

|||

I kind of figured that would be the answer. However, I still don't understand why the same computation, when done directly in a computed column (but equally non-deterministic), has good performance characteristics. It probably doesn't matter much, since I'm guessing there is no real fix here. I'm just curious.

|||

As shown in the query plan for both queries on sql2k, the index/table scan is used. This is the same as in sql2k5 with the udf.

The inline computed column is calculated differently than the udf. Although, it in itself is non-deterministic, the sql2k5 is enhanced (made smarter) to use the available statistics based on the index key to perform an index seek.

In sql2k8, you can force an index seek but it's still not going to be possible for non-deterministic udf.

|||

Hi Oj!

It is not the same as in sql2k5.

I would understand if 2k5 spools the results of the function, but I don't understand why does it spool JoinTable? It does not make any sense...

Query performance problems with join on UDF-based computed column

We have a table with a couple of computed columns. The value of the computed column represents a foreign key reference into another table. We're seeing a major performance problem doing a query joining between the two tables with one of the columns, but not the other. In other words, this kind of query is very fast:

select * from TheTable A, FKeyTable B
where A.ComputedColumn1 = B.KeyColumn

but this one sends the CPU usage of SQL Server to 99% for a very long time:

select * from TheTable A, FKeyTable B
where A.ComputedColumn2 = B.KeyColumn

The main difference we can see that the computed column that causes problems is based on a UDF, and the other one isn't (but again, both are computed). When I look at the execution plan, the slow query shows a Nested Loop (Inner Join) with a "No Join Predicate" warning, with the estimated # of rows being 70 million (which correponds to the product of 1016 rows in TheTable and 69K rows in FKeyTable). The fast query doesn't have that warning, and shows 1016 rows (the # of rows in TheTable).

Does anyone know why the usage of a UDF would induce this horribly inefficient join behavior? Anything we can do to fix it?

This is SQL Server 2005 SP2, btw.

By default, the engine does not know anything about the udf (i.e. has no statistics). So, bad plan can be generated.

To avoid this, I suggest that you create your udf with schemabinding and persist your computed column.

|||oj,
Thanks for the suggestions. I tried changing the UDF to use schema binding, but it didn't seem to effect the query plan at all. Persisting the computed column isn't a possibility here, as its value changes over time.
|||

Scalar udf is executed once per row which tends to be the cause for horrible performance. Now that we know that the values are non-deterministic, performance hit is almost unavoidable.

Can you post some ddl+sample data (insert)+sample code. We might be able to devise a solution.

|||

I'll see if I can come up with a simple repro.

What I don't understand is why a regular inline computed column (which is also non-deterministic) performs just fine, but the UDF version performs so horribly. I tried taking the computed column, which is essentially computing a time duration by calling datediff between "now" and a datetime stored in another column of the table, and converting the exact logic into a UDF. Once I do that, it has the same (bad) performance characteristics as my original problem - a Nested Loop with a "No Join Predicate" warning, 70M rows.

BTW, actually querying the column value is quite fast. It's the join that craters the performance.

|||

Have you tried explicitly creating a statistic for the column?

e.g.

create statistics _stats on table1(compute_col) with fullscan, norecompute

|||No luck. It complained that it "cannot be used in an index or statistics or as a partition key because it is non-deterministic."|||

Kevin, please post the requested info. Don't forget the udf code, too.

Note: you can use either free tool, objectscriptr or qalite from rac4sql.net to generate ddl+sample data.

|||

Here's the scripts (as far as I can tell, there's no attachment support on the forums....bummer). This is a seriously simplified version of our tables that reproduce the issue we're having.

The Create script:


Code Snippet

CREATE FUNCTION [dbo].[ComputeFKey](@.startTS datetime)
RETURNS float
with schemabinding
AS
BEGIN

RETURN datediff(minute,@.startTS,getutcdate())/(5)*(5)
END

go

CREATE TABLE [dbo].[JoinTable](
[KeyCol] [int] NOT NULL,
[MoreData] [int] NOT NULL,
CONSTRAINT [PK_JoinTable] PRIMARY KEY CLUSTERED
(
[KeyCol] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

go

CREATE TABLE [dbo].[MainTable](
[KeyCol] [int] IDENTITY(1,1) NOT NULL,
[CompCol] AS ((datediff(minute,[TSCol],getutcdate())/(5))*(5)),
[UdfCompCol] AS ([dbo].[ComputeFKey]([TSCol])),
[TSCol] [datetime] NOT NULL,
CONSTRAINT [PK_MainTable] PRIMARY KEY CLUSTERED
(
[KeyCol] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

go

Script to populate the join table:


Code Snippet

declare @.Start int
declare @.KeyVal int
declare @.RowsToAdd int
declare @.MoreData int

select @.RowsToAdd = 1000

if exists (select * from JoinTable)
select @.Start = max(KeyCol) + 5 from JoinTable
else
select @.Start = 0

select @.KeyVal = @.Start

while (@.KeyVal < (@.Start + @.RowsToAdd * 5))
begin
select @.MoreData = @.KeyVal % 60
insert into JoinTable (KeyCol, MoreData) values (@.KeyVal, @.MoreData)

select @.KeyVal = @.KeyVal + 5
end

Script to populate the main table:


Code Snippet

declare @.Row int
declare @.RowsToAdd int

select @.Row = 0
select @.RowsToAdd = 1000

while (@.Row < @.RowsToAdd)
begin
insert into MainTable (TSCol) values (DateAdd("hh", -1, getutcdate()))

select @.Row = @.Row + 1
end

Queries that demonstrate the issue:

Code Snippet


-- Fast query

select A.KeyCol from MainTable A, JoinTable B where A.CompCol = B.KeyCol

-- Slow query (Nested Loop with table spool)

select A.KeyCol from MainTable A, JoinTable B where A.UdfCompCol = B.KeyCol

The second query joins against the computed column that uses the UDF, and ends up with a Nested Loop with a table spool (a million rows in the Nested loop if you use the default values of the populate scripts - 1000 rows per table).

|||

Hi Kevin!

This is probably a bug, because MS SQL 2k behaves fine in this case (the execution plans are identical).

And btw, your function and column have different data types (float and integer).

|||

Oops - that was an error in creating my simplified repro case. The actual application schema has a CAST in the computed column. Thanks for catching that (though it doesn't affect the result). Replace the UdfCompCol definition with this:

[UdfCompCol] AS (CONVERT([int],[dbo].[ComputeFKey]([TSCol]),0))

|||

Thank you for posting the requested info. It's helpful to see what you're up against.

Now, to the _bad_ news. This is actually by design. Because you use getutcdate() within your udf, you make it non-deterministic. In sql2k, it is not possible to call getdate or getutcdate in a udf. Sql2k5 has loosen up this restriction but because the udf is marked as non-deterministric, the index seek (on jointable) is not possible. Therefore, the only option left for the engine is do a full scan of the jointable. Thus is the performance difference you see.

Btw, you can see that the perf is exactly identical for inline computed column versus udf computed column in sql2k. You will have to use the getdate_view trick though.

e.g.

Code Snippet

create view _utcdate
as
select getutcdate() [dt]
go
create FUNCTION [dbo].[ComputeFKey](@.startTS datetime)
RETURNS int
--with schemabinding
AS
BEGIN

RETURN (select datediff(minute,@.startTS,dt)/(5)*(5) from _utcdate)
END

go

-- Fast query

select A.KeyCol from MainTable A, JoinTable B where A.CompCol = B.KeyCol

-- Slow query (Nested Loop with table spool)

(1 row(s) affected)

StmtText
--
|--Hash Match(Inner Join, HASHSadBeer.[KeyCol])=(Angel.[CompCol]), RESIDUALSadBeer.[KeyCol]=Angel.[CompCol]))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[JoinTable].[PK_JoinTable] AS Beer))
|--Compute Scalar(DEFINESadAngel.[CompCol]=datediff(minute, MainTable.[TSCol], getutcdate)/5*5))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[MainTable].[PK_MainTable] AS Angel))

(4 row(s) affected)

StmtText
-

select A.KeyCol from MainTable A, JoinTable B where A.UdfCompCol = B.KeyCol

(1 row(s) affected)

StmtText
--
|--Hash Match(Inner Join, HASHSadBeer.[KeyCol])=(Angel.[UdfCompCol]), RESIDUALSadBeer.[KeyCol]=Angel.[UdfCompCol]))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[JoinTable].[PK_JoinTable] AS Beer))
|--Compute Scalar(DEFINESadAngel.[UdfCompCol]=[dbo].[ComputeFKey](Convert(MainTable.[TSCol]))))
|--Clustered Index Scan(OBJECTSad[tempdb].[dbo].[MainTable].[PK_MainTable] AS Angel))

|||

I kind of figured that would be the answer. However, I still don't understand why the same computation, when done directly in a computed column (but equally non-deterministic), has good performance characteristics. It probably doesn't matter much, since I'm guessing there is no real fix here. I'm just curious.

|||

As shown in the query plan for both queries on sql2k, the index/table scan is used. This is the same as in sql2k5 with the udf.

The inline computed column is calculated differently than the udf. Although, it in itself is non-deterministic, the sql2k5 is enhanced (made smarter) to use the available statistics based on the index key to perform an index seek.

In sql2k8, you can force an index seek but it's still not going to be possible for non-deterministic udf.

|||

Hi Oj!

It is not the same as in sql2k5.

I would understand if 2k5 spools the results of the function, but I don't understand why does it spool JoinTable? It does not make any sense...