Lab Manual 03 PDF
Lab Manual 03 PDF
Lab Manual 03 PDF
Lab Instructor:
Ms. Hira Kanwal
Student Name
Student Roll #
Department
Batch/Year/Section
Marks Signature
xvi
Lab Manual # 3 Creating & Manipulating Databases
3.1. Objective
After this lab, you would be able to understand:
1. Data Definition Language
2. Creating Database using query
3. Create, Alter, Drop table using Query
4. Sql Constraints on Columns & Tables
1. CREATE Database
Use NEW;
3. Delete Database
To add a new column to an existing table, we can use the following query:
You cannot define where a new column is located, each newly inserted column is
always located last. If the table already contains columns with values, the new column
will be populated with NULL values for all these rows.
Example:
ALTER TABLE detail
ALTER COLUMN DOB DateTime;
To drop a column from an existing table, we can use the following query:
If there is any violation between the constraint and the data action, the action is aborted by
the constraint.
Constraint_type – the type of the constraint to be enforced on the column (for example,
Unique or Not Null)
In SQL Server, the Not Null constraint ensures that the column contains no NULL values.
The syntax for defining a Not Null constraint is as follows:
Another Syntax for applying the same NOT NULL constraint is:
NOTE:
In SQL Server, the Unique constraint requires that every value in a column (or set of
columns) be unique. The syntax for defining a UNIQUE Constraint is as follows:
For example:
In SQL Server, the Check constraint defines a condition that each row must satisfy.
The condition written in the CHECK is quite similar in its structure to each of the conditions
written in a WHERE statement.
Syntax:
Examples:
If inserting data does not provide any specific value, the default constraint automatically
assign default value, only if you specified DEFAULT constraint.
Example:
In SQL Server, the Foreign Key constraint designates a column as a Foreign Key and
establishes a relationship between a Primary Key in different table. Foreign Key is used to
link two tables. The syntax for defining a Foreign key Constraint is as follows:
To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID);
To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table
is already created, use the following SQL:
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18);
To create a DEFAULT constraint on the "City" column when the table is already created, use
the following SQL: