SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


A Check and Foreign Key Constraint Improves Query Performance


A Check and Foreign Key Constraint Improves Query Performance

Author
Message
ss-457805
ss-457805
SSChasing Mays
SSChasing Mays (647 reputation)SSChasing Mays (647 reputation)SSChasing Mays (647 reputation)SSChasing Mays (647 reputation)SSChasing Mays (647 reputation)SSChasing Mays (647 reputation)SSChasing Mays (647 reputation)SSChasing Mays (647 reputation)

Group: General Forum Members
Points: 647 Visits: 1890
Thank you satnam

blog: http://sarveshsingh.com

Twitter: @sarveshsing
peter-757102
peter-757102
SSC Eights!
SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)

Group: General Forum Members
Points: 829 Visits: 2559
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
RichardDouglas
RichardDouglas
Ten Centuries
Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)

Group: General Forum Members
Points: 1097 Visits: 707
Great article SS

Hope this helps,
Rich



ps.
ps.
Hall of Fame
Hall of Fame (3.3K reputation)Hall of Fame (3.3K reputation)Hall of Fame (3.3K reputation)Hall of Fame (3.3K reputation)Hall of Fame (3.3K reputation)Hall of Fame (3.3K reputation)Hall of Fame (3.3K reputation)Hall of Fame (3.3K reputation)

Group: General Forum Members
Points: 3259 Visits: 3668
any idea how do we check the same in sql server 2000? sysforeignkeys doesn't have is_trusted column..



Pradeep Singh
chrisfradenburg
chrisfradenburg
SSCommitted
SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)

Group: General Forum Members
Points: 1988 Visits: 2067
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.
chrisfradenburg
chrisfradenburg
SSCommitted
SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)

Group: General Forum Members
Points: 1988 Visits: 2067
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.
walt-981324
walt-981324
Forum Newbie
Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)

Group: General Forum Members
Points: 3 Visits: 26
Great article. Didn't understand example of 'TeamID' in the last part. Did you mean 'CustomerID'?
peter-757102
peter-757102
SSC Eights!
SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)

Group: General Forum Members
Points: 829 Visits: 2559
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.
peter-757102
peter-757102
SSC Eights!
SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)SSC Eights! (829 reputation)

Group: General Forum Members
Points: 829 Visits: 2559
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.
john.larsen
john.larsen
SSC-Enthusiastic
SSC-Enthusiastic (142 reputation)SSC-Enthusiastic (142 reputation)SSC-Enthusiastic (142 reputation)SSC-Enthusiastic (142 reputation)SSC-Enthusiastic (142 reputation)SSC-Enthusiastic (142 reputation)SSC-Enthusiastic (142 reputation)SSC-Enthusiastic (142 reputation)

Group: General Forum Members
Points: 142 Visits: 100
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.
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search