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 ««12345»»»

A Check and Foreign Key Constraint Improves Query Performance Expand / Collapse
Author
Message
Posted Thursday, October 21, 2010 3:37 AM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Friday, August 22, 2014 2:51 AM
Points: 357, Visits: 1,692
Thank you satnam

blog: http://sarveshsingh.com

Twitter: @sarveshsing
Post #1008265
Posted Thursday, October 21, 2010 3:47 AM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Today @ 11:27 AM
Points: 329, Visits: 2,240
Unfortunatly it turns out that untrusted check constrains will not always become trusted after altering the contraint as is done in this article. If you find yourself in this situation, this can come due to the constraint being configured (at create time) as not for replication. This can be seen by querying sys.foreign_keys with the condition is_not_for_replication = 1.

In this situation, which can be by design, only re-creating the foreign key without not for replication will make the desired constraint trusted.

More not for replication can be read here:

http://msdn.microsoft.com/en-us/library/ms152529(SQL.90).aspx
Post #1008269
Posted Thursday, October 21, 2010 5:30 AM
SSC Eights!

SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!

Group: General Forum Members
Last Login: Friday, June 27, 2014 2:20 AM
Points: 974, Visits: 691
Great article SS

Hope this helps,
Rich



Post #1008344
Posted Thursday, October 21, 2010 5:48 AM


SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Monday, September 15, 2014 2:38 AM
Points: 2,242, Visits: 3,647
any idea how do we check the same in sql server 2000? sysforeignkeys doesn't have is_trusted column..





Pradeep Singh
Post #1008357
Posted Thursday, October 21, 2010 6:24 AM
SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Monday, August 4, 2014 8:10 AM
Points: 1,635, Visits: 1,972
garima.arya (10/21/2010)
If someone has added a foreign key constraint, why would he write a query like this.


Interesting point about how the query optimizer works but I'm more with Garima. If there's a foreign key constraint there what's the advantage of putting the exists check in the code? The only thing I can think of is that it will make it a little easier to follow if you're not familiar with the DB but I wouldn't think that would be worth giving the optimizer the possibility of generating an execution plan that will scan both tables.
Post #1008382
Posted Thursday, October 21, 2010 6:40 AM
SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Monday, August 4, 2014 8:10 AM
Points: 1,635, Visits: 1,972
ps. (10/21/2010)
any idea how do we check the same in sql server 2000? sysforeignkeys doesn't have is_trusted column..


I'm pretty sure that SQL 2000 doesn't have that same capability. I just disabled a foreign key constraint on one of our SQL 2000 DB, confirmed that it scanned both tables then re-enabled it and without any other action it just scanned the table that I was selecting from.
Post #1008401
Posted Thursday, October 21, 2010 6:56 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Thursday, April 4, 2013 3:16 PM
Points: 1, Visits: 25
Great article. Didn't understand example of 'TeamID' in the last part. Did you mean 'CustomerID'?
Post #1008417
Posted Thursday, October 21, 2010 7:09 AM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Today @ 11:27 AM
Points: 329, Visits: 2,240
cfradenburg (10/21/2010)
garima.arya (10/21/2010)
If someone has added a foreign key constraint, why would he write a query like this.


Interesting point about how the query optimizer works but I'm more with Garima. If there's a foreign key constraint there what's the advantage of putting the exists check in the code? The only thing I can think of is that it will make it a little easier to follow if you're not familiar with the DB but I wouldn't think that would be worth giving the optimizer the possibility of generating an execution plan that will scan both tables.


I think that trusted foreign key constraints provide information that can be used to cut out more of an execution plan then just the simple exists used in this article. It is fact that multiple trusted references to the same target table signify that the data in those foreign key fields is directly comparable to eachother. So the query optimizer can figure this out and simplify execution plans.

As for the arguments that this only involves queries written without build in knowledge by the writer, consider views that server multiple purposes. For views it is accepted that the optimizer has to cut out unused parts based on relevance to the consuming query. The writer of the consuming query might have the knowledge, but not the means to do this for the optimizer in this instance, nor does the writer of the view.
Post #1008437
Posted Thursday, October 21, 2010 7:48 AM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Today @ 11:27 AM
Points: 329, Visits: 2,240
Here is a query I wrote for SQL Server 2008 and its problably good for 2005 as well. For every untrusted foreign key it generates a small script of either two or four commands, here is what they do:

1. Find records that are in conflict with the foreign key constraint definition.
2. Enable and re-check the foreign key constraint (only works when 'not for replication' was not used).

Optional, when 'not for replication' was used during constraint creation.

3. A drop statement for the foreign key.
4. A create statement for the foreign key, this time without 'not for replication'.

set nocount on
;
with
fkCompleteQ as
(
select
is_not_for_replication = fk.is_not_for_replication
, parent_schema_id = fk.schema_id
, parent_object_id = fk.parent_object_id
, referenced_object_id = fk.referenced_object_id
, referenced_schema_id = rt.schema_id
, object_id = fk.object_id
, delete_referential_action_desc = replace( fk.delete_referential_action_desc, '_', ' ' )
, update_referential_action_desc = replace( fk.update_referential_action_desc, '_', ' ' )
, parent_fields = stuff( ( select ', [' + cp.name + ']' from sys.foreign_key_columns as fkc inner join sys.columns as cp on cp.object_id = fkc.parent_object_id and cp.column_id = fkc.parent_column_id where fkc.constraint_object_id = fk.object_id order by fkc.constraint_column_id for xml path( '' ) ), 1, 2, '' )
, referenced_fields = stuff( ( select ', [' + cr.name + ']' from sys.foreign_key_columns as fkc inner join sys.columns as cr on cr.object_id = fkc.referenced_object_id and cr.column_id = fkc.referenced_column_id where fkc.constraint_object_id = fk.object_id order by fkc.constraint_column_id for xml path( '' ) ), 1, 2, '' )
, join_fields = stuff( ( select ' and ( p.[' + cp.name + '] is null or p.[' + cp.name + ']=r.[' + cr.name + '] )' from sys.foreign_key_columns as fkc inner join sys.columns as cp on cp.object_id = fkc.parent_object_id and cp.column_id = fkc.parent_column_id
inner join sys.columns as cr on cr.object_id = fkc.referenced_object_id and cr.column_id = fkc.referenced_column_id where fkc.constraint_object_id = fk.object_id order by fkc.constraint_column_id for xml path( '' ) ), 1, 5, '' )
from
sys.foreign_keys as fk
inner join sys.tables as rt on rt.object_id = fk.referenced_object_id
where
fk.is_not_trusted = 1 /* and fk.is_disabled = 0 */
)
select
result = '/* constraint: [' + schema_name( fk.parent_schema_id )+ '].[' + object_name( fk.parent_object_id ) + '].[' + object_name( fk.object_id ) + '] */' + char(10)
+ 'select p.* from [' + schema_name( fk.parent_schema_id )+ '].[' + object_name( fk.parent_object_id ) + '] as p where not exists ( select 1 from [' + schema_name( fk.referenced_schema_id )+ '].[' + object_name( fk.referenced_object_id ) + '] as r where ' + join_fields + ');' + char(10)
+ 'alter table [' + schema_name( fk.parent_schema_id )+ '].[' + object_name( fk.parent_object_id ) + '] with check check constraint [' + object_name( fk.object_id ) + '];' + char(10)
+ case
when is_not_for_replication = 0
then ''
else
'-- alter table [' + schema_name( fk.parent_schema_id )+ '].[' + object_name( fk.parent_object_id ) + '] drop constraint [' + object_name( fk.object_id ) + '];' + char(10)
+ '-- alter table [' + schema_name( fk.parent_schema_id )+ '].[' + object_name( fk.parent_object_id ) + '] add constraint [' + object_name( fk.object_id ) + '] foreign key ( ' + parent_fields + ' ) references [' + schema_name( fk.referenced_schema_id )+ '].[' + object_name( fk.referenced_object_id ) + '] ( ' + referenced_fields + ' ) on DELETE ' + fk.delete_referential_action_desc + ' on UPDATE ' + fk.update_referential_action_desc + ';' + char(10)
end
from
fkCompleteQ as fk
order by
fk.parent_schema_id
, fk.parent_object_id
, fk.referenced_schema_id
, fk.referenced_object_id
, fk.object_id
, result
;

Execute using text mode output (Ctrl-t) to get the script and copy/paste it to a new query window to examine and possibly execute parts of it. If you find parts of the resuls truncated, go to:

Tools -> Options -> Query Results -> Results to text -> Maximum number of characters displayed in each column. And set the value to a larger number (2048) should be large enough for this.

NOTE:

I modified the code a bit to take into acount optional foreign key fields.
Post #1008483
Posted Thursday, October 21, 2010 8:31 AM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Thursday, July 24, 2014 3:15 PM
Points: 125, Visits: 96

I liked the article as it brought into focus an element of the QO that I had not considered before.

As an aside, I would like to point out that we commonly optimize exists / not exists sub-queries by using left outer joins. I've gotten into the habit now of not using 'exists' sub-queries due to the order of magnitude difference I've seen on some query executions.

In any case, it is a good article.

Post #1008534
« Prev Topic | Next Topic »

Add to briefcase ««12345»»»

Permissions Expand / Collapse