SQL Constraints

SQL Constraints

Primary Key Constraint

Step 1: 

(first ensure the field is NOT NULL)

alter table tablename alter column column int not null 

Step 2:

ALTER TABLE tablename ADD CONSTRAINT constraintname PRIMARY KEY (fieldname);

Example:

Alter table Employees add constraint PK_EmpID PRIMARY KEY (EmployeeID)


Foreign key constraint

alter table Orders            

-- table name

add constraint FK_EID     

– constraint name

foreign key (ShipperID) 

 -- column that will become a foreign key

references Shippers (ShipperID)

-– table and column name to which it links


 

Default constraint

Alter table Orders add constraint df_Constraintname default getdate() for orderdate
 

Check Constraint

Alter table Products add constraint ch_price check (price >= 0)
 

To DROP a Constraint

alter table products drop constraint ch_price

 


Comments

Popular posts from this blog

Delete vs Truncate in MySQL and MS SQL Server

Building Cross-Platform JavaFX Apps with Gluon

Companies and real-world applications using JavaFX