Following script are very useful to know all the constraint in the database. I use this many times to check the foreign key and primary key constraint in database. This is simple but useful script from my personal archive.
USE AdventureWorks;
GO
SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
GO
Reference : Pinal Dave (http://blog.SQLAuthority.com)
SQL SERVER – 2005 – List All The Constraint of Database – Find Primary Key and Foreign Key Constraint in Database
September 16, 2007 by pinaldave
Posted in Pinal Dave, SQL, SQL Authority, SQL Constraint and Keys, SQL Query, SQL Scripts, SQL Server, SQL System Table, SQL Tips and Tricks, T SQL, Technology | 33 Comments
33 Responses
Leave a Reply
About Pinal Dave
Pinalkumar Dave is a Microsoft SQL Server MVP and a Mentor for Solid Quality India. He has written over 1100 articles on the subject on his blog at http://blog.sqlauthority.com. He is a dynamic and proficient Principal Database Architect, Corporate Trainer and Project Manager, who specializes in SQL Server Programming and has 7 years of hands-on experience. He holds a Masters of Science degree and a number of certifications, including MCDBA and MCAD (.NET). He was awarded Regional Mentor for PASS Asia.
-
Blog Stats
- 10,989,502 Readers
SQLAuthority Links

My Homepage
My Resume
My Other Blog
--------------------
Top Downloads
PDF Downloads
Script Downloads
Script Bank
Favorite Scripts
All Scripts - 1
All Scripts - 2
Top Articles
Best Articles
Favorite Articles - 1
Favorite Articles - 2
--------------------
SQL Interview Q & A
SQL Coding Standards
SQL FAQ Download
--------------------
Jobs @ SQLAuthority
Top 7 Commenters
365 - Imran Mohammed
138- Brian Tkatch
57 - Tejas Shah
56 - Jacob Sebastian
47 - Jerry Hung
46 - Kuldip Bhatt
43 - Ashish GilhotraCategories
- About Me (61)
- Best Practices (91)
- Business Intelligence (14)
- Data Warehousing (30)
- Database (270)
- DBA (126)
- MVP (98)
- Poll (5)
- Readers Contribution (37)
- Readers Question (45)
- Software Development (67)
- SQL Add-On (91)
- SQL Backup and Restore (54)
- SQL BOL (10)
- SQL Coding Standards (20)
- SQL Constraint and Keys (51)
- SQL Cursor (28)
- SQL Data Storage (45)
- SQL DateTime (37)
- SQL Documentation (219)
- SQL Download (222)
- SQL Error Messages (125)
- SQL Function (124)
- SQL Humor (25)
- SQL Index (98)
- SQL Interview Questions and Answers (58)
- SQL Joins (64)
- SQL Optimization (66)
- SQL Performance (223)
- SQL Puzzle (26)
- SQL Security (119)
- SQL Server DBCC (42)
- SQL Server Management Studio (28)
- SQL Stored Procedure (102)
- SQL String (19)
- SQL System Table (50)
- SQL Trigger (24)
- SQL User Group (48)
- SQL Utility (126)
- SQL White Papers (37)
- SQLAuthority (376)
- SQL Training (1)
- SQLAuthority Author Visit (80)
- SQLAuthority Book Review (19)
- SQLAuthority News (346)
- SQLAuthority Website Review (29)
- SQLServer (77)
- Tech (916)
- Pinal Dave (906)
- SQL Scripts (533)
- Technology (1159)
- SQL (1159)
- SQL Authority (1159)
- SQL Query (1159)
- SQL Server (1159)
- SQL Tips and Tricks (1159)
- T SQL (1159)
-
Top Posts
- SQL SERVER - Insert Data From One Table to Another Table - INSERT INTO SELECT - SELECT INTO TABLE
- SQL SERVER - Insert Multiple Records Using One Insert Statement - Use of UNION ALL
- SQL SERVER - Retrieve Current Date Time in SQL Server CURRENT_TIMESTAMP, GETDATE(), {fn NOW()}
- SQL SERVER - Import CSV File Into SQL Server Using Bulk Insert - Load Comma Delimited File Into SQL Server
- SQL Server Interview Questions and Answers Complete List Download
- SQL SERVER - Convert Text to Numbers (Integer) - CAST and CONVERT
- SQL SERVER - 2005 - Create Script to Copy Database Schema and All The Objects - Stored Procedure, Functions, Triggers, Tables, Views, Constraints and All Other Database Objects
- SQL SERVER - Shrinking Truncate Log File - Log Full
- SQL SERVER - 2005 List All Tables of Database
- SQL SERVER - Restore Database Backup using SQL Script (T-SQL)
- SQL SERVER - 2008 - Interview Questions and Answers Complete List Download
- SQL Server Interview Questions and Answers - Part 1
-
Authors
-
pinaldave
- SQLAuthority News – SQL Server 2008 for Oracle DBA
- SQLAuthority News – Book Review – Expert SQL Server 2008 Encryption by Michael Coles
- SQL SERVER – Understanding Table Hints with Examples
- SQL SERVER – Size of Index Table – A Puzzle to Find Index Size for Each Index on Table
- SQL SERVER – 2005 2008 – Backup, Integrity Check and Index Optimization By Ola Hallengren
- SQLAuthority News – Notes of Excellent Experience at SQL PASS 2009 Summit, Seattle
- SQL SERVER – Whitepaper Consolidation Using SQL Server 2008
- SQLAuthority News – Disk Partition Alignment Best Practices for SQL Server
- SQL SERVER – Policy Based Management – Create, Evaluate and Fix Policies
- SQL SERVER – Disable CHECK Constraint – Enable CHECK Constraint
-
Archives
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
- April 2007
- March 2007
- February 2007
- January 2007
- December 2006
- November 2006
Pages
Category Cloud
About Me Best Practices Database DBA MVP Pinal Dave Software Development SQL SQL Add-On SQL Authority SQLAuthority Author Visit SQLAuthority News SQL Documentation SQL Download SQL Error Messages SQL Function SQL Index SQL Joins SQL Optimization SQL Performance SQL Query SQL Scripts SQL Security SQLServer SQL Server SQL Stored Procedure SQL Tips and Tricks SQL Utility Technology T SQL



Dear Pinal,
To get the idea of any relationship between tables using foreign key relationships, I think, following query will be more useful :
select Referencing_Object_name, referencing_column_Name, Referenced_Object_name, Referenced_Column_Name from
(select Referenced_Column_Name = c.name, Referenced_Object_name = o.name, f.constid from sysforeignkeys f, sysobjects o, syscolumns c
where (f.rkeyid = o.id) and c.id = o.id and c.colid = f.rkey) r,
(select referencing_column_Name = c.name, Referencing_Object_name = o.name, f.constid from sysforeignkeys f, sysobjects o, syscolumns c
where (f.fkeyid = o.id) and c.id = o.id and c.colid = f.fkey) f
where r.Referenced_Column_Name = f.referencing_column_Name
and r.constid = f.constid
order by f.Referencing_Object_name
Regards,
Abhay
Hey Pinal,
I was going through google to look for the query that you’ve posted here and came across your blog.
Its surprising to see you and remember your face from Nirma Bus, if my memory is not wrong. I was studying in Nirma between 1999 – 2003. And you are also from Gandhingar, right? yeah I am from Gandhinagar.
Regards,
Ujjaval
PS:- Oh by the way, useful post. Thanks for that.
Hi Ujjaval Suthar,
Yes, I am Pinal from Gandhinagar. Nirma 1999-2003.
Regards,
Pinal
This query works and was very helpful to me. Thanks.
For SQL Server 2005, you can use the sys.foreign_keys view to achieve the same. The columns in this view are self explanatory so am not publishing the query here.
Regards
Shishir
i’m new to sql server 2005 …
can u plz suggest ny gud book for sqlserver 2005 for a beginner and i want to do certification for d same..
plz guide!!!!!
sir,
i got my answer, initially i didn’t search in sqlauthority.com!!
thx
Hello Sir,
I am a .net Developer and I came across some difficult questions during the interview on database. The question
is :
There is a table with 5 coloumns, in that under country coloumn the fields should be all asain countries. If the user
enters other than asian country it should throw an error.
How to write a query for this?
1 column should be for continent.
Put ‘Asia’ in as the value for all the Asian coutries, etc.
Hi!
I made an easier to understand script that shows all constraint in the database including that rows where the referencing_column_name and the referenced_column_name are different and the name of the constraint
select
o1.name as Referencing_Object_name
, c1.name as referencing_column_Name
, o2.name as Referenced_Object_name
, c2.name as Referenced_Column_Name
, s.name as Constraint_name
from sysforeignkeys fk
inner join sysobjects o1 on fk.fkeyid = o1.id
inner join sysobjects o2 on fk.rkeyid = o2.id
inner join syscolumns c1 on c1.id = o1.id and c1.colid = fk.fkey
inner join syscolumns c2 on c2.id = o2.id and c2.colid = fk.rkey
inner join sysobjects s on fk.constid = s.id
inner join syscolumns c1 on c1.id = o1.id and c1.colid = fk.fkey
inner join syscolumns c2 on c2.id = o2.id and c2.colid = fk.rkey
inner join sysobjects s on fk.constid = s.id
Hi szolarp,
Your query is prefect. It had some defect, i refined it below.
select
o1.name as Referencing_Object_name
, c1.name as referencing_column_Name
, o2.name as Referenced_Object_name
, c2.name as Referenced_Column_Name
, s.name as Constraint_name
from sysforeignkeys fk
inner join sysobjects o1 on fk.fkeyid = o1.id
inner join sysobjects o2 on fk.rkeyid = o2.id
inner join syscolumns c1 on c1.id = o1.id and c1.colid = fk.fkey
inner join syscolumns c2 on c2.id = o2.id and c2.colid = fk.rkey
inner join sysobjects s on fk.constid = s.id
and o2.name=’tblUserDetails’ — this predicate for a specific table
Hi
Does anyone know how can I find the relationship between colomn and default constraint. I need it for dynamicly drop the column in different databases
Hi Pinal,
really this procedure its very very useful,
I was facing trouble from last half an hour, and your query has resolved my problem, with in second.
thanks a lot.
great work!!!!
Thanks for the script above, it really helped me on deleting my DWH constraints. Cheers.
This blog helped me a lot! Many thanks to you all.
I was looking for days to solve my constraint problem.
this is very usefull in my ADO application. Looks like ADO does not have functions to read detailed constraint information like this script from an SQL database. Therefore I was forced to search for a solution in SQL scripting and here it was!
Thx!
Msg 547, Level 16, State 0, Line 1
The UPDATE statement conflicted with the REFERENCE constraint “hrpyprc_ps_auth_r01_fk”. The conflict occurred in database “HRMS40_CBI”, table “dbo.hrpyprc_payset_auth_cnt”.
The statement has been terminated.
szolarp & Tushar
Many thanks .. you really helped me ..
i’m new to sql server 2005 …
can u plz suggest ny gud book for sqlserver 2005 for a beginner and i want to do certification for d same..
plz guide!!!!!
What r the differences b/w Sql Server 2005 and 2000
Hi,
I think using information schema is much useful than using sysobjects. To see the list of constraints you can use the query:
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
or you can use database name with it:
SELECT * FROM [SugarCMS].INFORMATION_SCHEMA.TABLE_CONSTRAINTS
Here is the complete list of information_schema views:
CHECK_CONSTRAINTS: Check Constraints
COLUMN_DOMAIN_USAGE: Every column that has a user-defined data type.
COLUMN_PRIVILEGES: Every column with a privilege granted to or by the current user in the current database.
COLUMNS:Lists every column in the system
CONSTRAINT_COLUMN_USAGE: Every column that has a constraint defined on it.
CONSTRAINT_TABLE_USAGE: Every table that has a constraint defined on it.
DOMAIN_CONSTRAINTS: Every user-defined data type with a rule bound to it.
DOMAINS: Every user-defined data type.
KEY_COLUMN_USAGE: Every column that is constrained as a key
PARAMETERS: Every parameter for every user-defined function or stored procedure in the datbase. For functions this returns one row with return value information.
REFERENTIAL_CONSTRAINTS: Every foreign constraint in the system.
ROUTINE_COLUMNS: Every column returned by table-valued functions.
ROUTINES: Every stored procedure and function in the database.
SCHEMATA: Every database in the system.
TABLE_CONSTRAINTS: Every table constraint.
TABLE_PRIVILEGES: Every table privilege granted to or by the current user.
TABLES: Every table in the system.
VIEW_COLUMN_USAGE: Every column used in a view definition.
VIEW_TABLE_USAGE: Every table used in a view definition.
VIEWS: Every View
Hi,
Does any one know how to get DEFAULT Constraint along with the name of the column on which it has defined.
Nirmal query gives the table name, but not the column name, because most of the time DEFAULT is created on the column by using DEFAULT, which create the system generated name of the DEFAULT, so I would like to know how to get the column name along with the table name.
I would appreciate any suggestion.
Thanks
@SYED,
This might help,
SELECT OBJECT_NAME(PARENT_OBJECT_ID) TABLE_NAME,
COL_NAME (PARENT_OBJECT_ID, PARENT_COLUMN_ID)COLUMN_NAME ,
NAME DEFAULT_CONSTRAINT_NAME
FROM SYS.DEFAULT_CONSTRAINTS ORDER BY 1
Hope this helps,
Imran.
I think is easier… it’s pretty much like the one publish by szolarp and “fixed” by Tushar Mehere…
is this:
SELECT RO.NAME AS ParentTable, RC.NAME AS ParentColumn, FO.NAME AS ForeignTable, FC.NAME AS ForeignColumn
FROM sysforeignkeys F INNER JOIN sysobjects RO
ON F.rkeyid = RO.id INNER JOIN syscolumns RC
ON RC.id = RO.id AND RC.colid = F.rkey INNER JOIN sysobjects FO
ON F.fkeyid = FO.id INNER JOIN syscolumns FC
ON FC.id = FO.id AND FC.colid = F.fkey
ORDER BY RO.NAME, RC.NAME, FO.NAME, FC.NAME
we don’t really to know the name…
Hi Pinal,
I have a situation wherein I need to change a particular name in my entire database.
Please tell me how can i trace this particular word – it might be occuring in ‘n’ number of tables in the database, in ‘n’ number of column values and in ‘n’ number of records throughout present in any table of that database.
I need to write a cursor, go to each record and trace that word, likewise for others, for each table. I heard that sysobjects and syscolumns could help in this scenario, could you please generate the code if possible.
Thanks, Mark
i was seaching for the query regarding constraints. It was nice and thankx
Superb site…
This site really provides simple solutions for complex problems
Thanks alot
[...] SQL SERVER – 2005 – List All The Constraint of Database – Find Primary Key and Foreign Key Constrain… [...]
hey pinal
i get this error when i run ur script
‘SCHEMA_NAME’ is not a recognized function name.
ne thoughts?
Is there way to find DEFAULT_CONSTRANTS of the table from INFORMATION_SCHEMA ?
@Shihab
If you see, text of Information_Schema.Constraints view you will find that it is querying from sys.objects view. where we have information about all objects in the database.
I used the same view but modified it a little bit in order to get information for default constraints, here is the script.
select
Object_Id
,[name] [Default_Constraint_Name]
,schema_name (schema_id) [Schema_Name]
,object_name (parent_object_id)[Table_Name]
,[Create_Date]
,[Modify_Date]
from sys.objects where type = ‘D’
~ IM.
hi,
im a beginner..please tell me syntax how to create a table within a schema?..
@Padma,
If Schema name is Product
And you want to create a table under schema Product, then you use this script.
Create table Product.Table1 (Eid Int, Ename Varchar(100))
Where Product is Schema Name, and Table1 is the name of the table.
You should have DDL Permissions, Permissions to create objects in the database.
IM.
hi pinal,
how to insert/update a tables’s data residing in database A(suppose) of server1 to server 2’s database B’s table which can have same or different table structure.
I know one solution is with the usage of linked server,but i want to do it using replication or mirroring or any other technique(if available) for sql server 2005.
Please provide me code/querry’s rather than theory.
Thanks alot.