Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column level vs table level constraints in sql server?

Tags:

sql

sql-server

a. Column Level

GO

CREATE TABLE Products
(
ProductID INT CONSTRAINT pk_products_pid PRIMARY KEY,
ProductName VARCHAR(25)
);

GO

b. Table Level

CREATE TABLE Products
(
ProductID INT,
ProductName VARCHAR(25),
CONSTRAINT pk_products_pid PRIMARY KEY(ProductID)
);
GO 

Is their any difference between Column level and table level constraints?

like image 329
Vishwanath Dalvi Avatar asked Feb 29 '12 05:02

Vishwanath Dalvi


3 Answers

No. It's just a matter of personal taste how you apply the constraint.

The primary key constraint is just a primary key constraint - it always applies to the table (after all: it could contain multiple columns - it cannot be "at the column level").

It's not "at the column level" once or at the "table level" in the other case - it's the same always.

Just for fun - you can also create the primary key constraint a third way:

(CREATE TABLE statement)
GO

ALTER TABLE dbo.Products
ADD CONSTRAINT PK_Products_pid PRIMARY KEY(ProductID)

and that again would be identical to the two other options you already have.

like image 122
marc_s Avatar answered Nov 15 '22 19:11

marc_s


Your first example declares the constraint in line, the second does not. Only simple keys (involve one attribute) can be declared in line, compound keys (involving multiple columns) cannot. But both are table-level constraints!


There are four logical levels of constraint:

1) Column level:

CHECK ( ProductID > 0 )

2) Row level:

CHECK ( Product_start_date < Product_end_date )

3) Table level (the following example is not yet supported in SQL Server):

CHECK ( NOT EXISTS ( SELECT *
                       FROM ( SELECT ROW_NUMBER() OVER ( PARTITION BY ProductID ) AS Tally
                                FROM Products AS P ) AS DT1 
                      WHERE Tally > 1 ) )

4) Database level (not yet supported in SQL Server):

CREATE ASSERTION EnterpriseUniqueIds
   CHECK ( NOT EXISTS ( SELECT *
                          FROM ProductID AS P
                               JOIN Components AS C
                                  ON C.ComponentID = P.ProductID ) );

A key constraint involves comparing different rows within the same table, therefore it is a table-level constraint.

like image 27
onedaywhen Avatar answered Nov 15 '22 19:11

onedaywhen


A bit late to the party but FYI for others

http://social.technet.microsoft.com/wiki/contents/articles/13744.table-level-vs-column-level-constraints.aspx

like image 41
kalki Avatar answered Nov 15 '22 19:11

kalki