Lab1 Intro SQL&Ddl
Lab1 Intro SQL&Ddl
• Installing SQL Server creates system databases as (master , model , tempdb and msdb) and
sample user databases such as:( pubs and Northwind)
SQL Constraint:-
Rules enforced on data columns on tables. These are used to limit the type of data that can go into a
table. This ensures the accuracy and reliability of the data in the database.
The following are commonly used constraints available in SQL:
• NOT NULL: A Constraint that ensures that a column cannot have NULL value.
• DEFAULT: A Constraint that provides a default value for a column when none is specified.
• UNIQUE: A Constraint that ensures that all values in a column are different or NULL.
• PRIMARY Key: A Constraint that uniquely identify each row/record in a database table (NOT
NULL + UNIQUE)
• FOREIGN KEY (FK): A Constraint that ensures referential integrity. A foreign key from 1
table to another is used link a tuple in the 1st table to a unique tuple in the 2nd table.
• CHECK: A constraint that ensures that all values in a column satisfy a certain condition.
Constraints can be specified within the CREATE TABLE statement after the attributes are
declared, or they can be added later using the ALTER TABLE command.
4. Altering Table: Used to change the table structure i.e. add column, change data type of a
column, or remove existent column.
• ALTER TABLE<table name>
ADD <column name> <data type>
5. Dropping Table: Used to drop a table structure and all the data stored in it:
DROP TABLE <table name>
Ex:
DROP TABLE STAFF
--DEPARTMENT Table
CREATE TABLE Department(
DeptCode VARCHAR(5) NOT NULL PRIMARY KEY ,
Name VARCHAR(15) NOT NULL,
)
--Course Table
CREATE TABLE Course
(
CrsCode SMALLINT NOT NULL,
Name VARCHAR(45) UNIQUE,
PRIMARY KEY (CrsCode)
)
--Student Table
CREATE TABLE Student
(
SSN INT NOT NULL,
Name VARCHAR(45),
Age INT CHECK (AGE >= 18),
City VARCHAR(15) DEFAULT 'CAIRO',
)
--Add PK to Student table
ALTER TABLE STUDENT
ADD PRIMARY KEY (SSN),
--OR
ALTER TABLE STUDENT
ADD CONSTRAINT PK1 PRIMARY KEY (SSN) -- constraint name is unique across database
--Registered Table
CREATE TABLE Registered
(
SSN INT NOT NULL,
CrsCode SMALLINT NOT NULL REFERENCES COURSE(Crscode),
Semester VARCHAR (45) NOT NULL,
Year VARCHAR (45)
)
ALTER EXAMPLES:
• Add a check constraint to make sure that "DeptCode" will only take one
of these codes (IS, CS, IT, DS).
ALTER TABLE DEPARTMENT
ADD CONSTRAINT CK_DEPTCODE CHECK (DEPTCODE IN
('IS','CS','IT','DS'))