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 | 30 Comments
30 Responses
Leave a Reply
-
About Pinal Dave
Pinalkumar Dave is Microsoft SQL Server MVP, Solid Quality Mentor and a prominent author of over 1000 SQL Server articles at SQLAuthority. He is a dynamic and proficient Principal Database Architect, Corporate Trainer and Project Manager specializing in SQL Server Programming with over 7 years of hands-on experience. He holds a degree in Masters of Science and has accomplished a number of certifications including MCDBA and MCAD (.NET). He has also been awarded Regional Mentor for PASS Asia.
-
Blog Stats
- 8,410,343 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
Categories
- About Me (49)
- Best Practices (82)
- Business Intelligence (6)
- Data Warehousing (27)
- Database (257)
- DBA (121)
- DigiCorp (7)
- MVP (81)
- Poll (5)
- Readers Contribution (22)
- Readers Question (28)
- Software Development (62)
- SQL Add-On (88)
- SQL Backup and Restore (48)
- SQL BOL (8)
- SQL Coding Standards (21)
- SQL Constraint and Keys (49)
- SQL Cursor (30)
- SQL Data Storage (36)
- SQL DateTime (36)
- SQL Documentation (193)
- SQL Download (198)
- SQL Error Messages (116)
- SQL Function (104)
- SQL Humor (22)
- SQL Index (82)
- SQL Interview Questions and Answers (54)
- SQL Joins (61)
- SQL Optimization (51)
- SQL Performance (204)
- SQL Puzzle (18)
- SQL Security (115)
- SQL Server DBCC (42)
- SQL Server Management Studio (17)
- SQL Stored Procedure (97)
- SQL String (17)
- SQL System Table (27)
- SQL Trigger (27)
- SQL User Group (41)
- SQL Utility (116)
- SQL White Papers (8)
- SQLAuthority (307)
- SQLAuthority Author Visit (62)
- SQLAuthority Book Review (19)
- SQLAuthority News (277)
- SQLAuthority Website Review (23)
- SQLServer (42)
- Tech (772)
- Pinal Dave (761)
- SQL Scripts (490)
- Technology (1023)
- SQL (1023)
- SQL Authority (1023)
- SQL Query (1023)
- SQL Server (1023)
- SQL Tips and Tricks (1023)
- T SQL (1023)
-
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 - Import CSV File Into SQL Server Using Bulk Insert - Load Comma Delimited File Into SQL Server
- SQL SERVER - Retrieve Current Date Time in SQL Server CURRENT_TIMESTAMP, GETDATE(), {fn NOW()}
- 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 - Convert Text to Numbers (Integer) - CAST and CONVERT
- SQL Server Interview Questions and Answers Complete List Download
- SQL SERVER - Restore Database Backup using SQL Script (T-SQL)
- SQL SERVER - 2008 - Interview Questions and Answers Complete List Download
- SQL SERVER - 2005 List All Tables of Database
- SQL SERVER - Shrinking Truncate Log File - Log Full
- SQL SERVER - TRIM() Function - UDF TRIM()
-
Authors
-
pinaldave
- SQLAuthority News – Authors Visit – K-MUG TechEd Trivandrum on June 27, 2009
- SQLAuthority News – Book Review – Murach’s SQL Server 2008 for Developers
- SQLAuthority News – Authors Visit – DotNet Buzz Delhi TechEd Delhi on July 11, 2009
- SQL SERVER – Languages for BI – MDX, DMX, XMLA
- SQLAuthority News – FIX : Error : HP OfficeJet Scanning and Printing Gray or Pink Shades
- SQL SERVER – Disk Partition Alignment Best Practices
- SQLAuthority News – Book Review – The Rational Guide to Building Technical User Communities (Rational Guides)
- SQLAuthority News – MVP Award Renewed
- SQL SERVER – Difference between Line Feed (\n) and Carriage Return (\r) – T-SQL New Line Char
- SQL SERVER – 2008 – Policy-Based Management – Create, Evaluate and Fix Policies
-
Archives
- 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 Interview Questions and Answers SQL Joins SQL Optimization SQL Performance SQL Query SQL Scripts SQL Security 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.