0% found this document useful (0 votes)
7 views

Lecture7

This document is a lecture on SQL (Structured Query Language) focusing on Data Definition Language (DDL) commands, including how to create, alter, and drop databases and tables. It provides syntax examples for various SQL commands, explains data types, constraints, and the importance of foreign keys in establishing relationships between tables. Additionally, it covers the use of SQL Server Management Studio (SSMS) and the implications of modifying database structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lecture7

This document is a lecture on SQL (Structured Query Language) focusing on Data Definition Language (DDL) commands, including how to create, alter, and drop databases and tables. It provides syntax examples for various SQL commands, explains data types, constraints, and the importance of foreign keys in establishing relationships between tables. Additionally, it covers the use of SQL Server Management Studio (SSMS) and the implications of modifying database structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

”‫“ إدارة قواعد البيانات‬

Database System

Lecture7
SQL (Structured Query Language)
Data Definition Language DDL

Lecture7 – Fall2024 1
SSMS

SSMS is a client tool and not the server by itself

Developer machines (clients) connects to SQL Server using SSMS

Lecture7 – Fall2024
SQL Command

SQL Command

DDL DML DCL TCL DQL


Create Insert Grant Select
Commit
Drop Update Revoke
Rollback
Alter Delete
SavePoint
Truncate

Lecture7 – Fall2024
SQL CREATE / DROP DATABASE Statement

❑ A SQL Server database can be created , altered and dropped

1. Graphically using SQL Server Management Studio (SSMS) or

2. Using a Query

❑ Whether , you create a database graphically using the designer


or , using a query the following 2 files gets generated

▪ .MDF file – Master Data File (Contains actual data)

▪ .LDF file – Transaction Log Data File (Used to recovery the


database)

Lecture7 – Fall2024
SQL CREATE / DROP DATABASE Statement

❑ Syntax :
CREATE DATABASE databasename;
CREATE DATABASE University;
❑ Syntax :
USE University
GO
❑ Syntax :
DROP DATABASE databasename;
DROP DATABASE University;

Lecture7 – Fall2024
SQL CREATE / DROP DATABASE Statement

▪ So , if other users are connected , you need to put the database in


single user mode and then drop the database.

ALTER DATABASE SuperMarket SET SINGLE_USER WITH


ROLLBACK IMMEDIATE

▪ With Rollback immediate option , will rollback all incomplete


transactions and closes the connection to the database

Note: Be careful before dropping a database. Deleting a database will


result in loss of complete information stored in the database!

Note: System database cannot be dropped.


Lecture7 – Fall2024
ALTER DATABASE Statement

❑ Syntax :
ALTER DATABASE OldNamedatabase MODIFY
NAME=NewNameDatabase ;

ALTER DATABASE SuperMarket MODIFY NAME=Company;

❑ SP_RENAMEDB ’OldNamedatabase’, ‘NewNameDatabase’;

SP_RENAMEDB ‘SuperMarket’ , ‘Company’;

Lecture7 – Fall2024
SQL CREATE / DROP DATABASE Statement

❑ Syntax :
CREATE DATABASE Sales
ON
(
NAME = Sales_data ,
FILENAME =‘C:\Program Files\Micrsoft SQL
Server\MSSQL15.MSSQLSERVER\MYSQL\DATA\saledata.mdf’,
SIZE = 10,
MAXSIZE = 50 ,
FILEGROWTH=5)
LOG ON
(
NAME = Sales_LOG ,
FILENAME =‘C:\Program Files\Micrsoft SQL
Server\MSSQL15.MSSQLSERVER\MYSQL\DATA\saledata.idf’,
SIZE = 5MB,
MAXSIZE = 25MB ,
FILEGROWTH=5MB)
Lecture7 – Fall2024
CREATE Schema & DROP Schema

▪ The CREATE SCHEMA statement allows you to create a new


schema in current database.

▪ The following illustrates the simplified version of the CREATE


SCHEMA statement
❑ Syntax :
CREATE SCHEMA schema_name
[Authorization owner_name]

DROP SCHEMA schema_name

Lecture7 – Fall2024
SQL CREATE TABLE Statement

❑ Syntax :
CREATE TABLE [database_name.][schema_name.] table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
▪ The column parameters specify the names of the columns of the
table.

▪ The datatype parameter specifies the type of data the column can
hold (e.g. varchar, integer, date, etc.).
SQL CREATE TABLE Example

CREATE TABLE Student (


StudentID INT IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City int
);

Lecture7 – Fall2024
SQL Data Types for SQL Server

❑ STRING DATA TYPES:


SQL Data Types for SQL Server

❑ NUMBER DATA TYPES:

Lecture7 – Fall2024
SQL Statement

❑ DATE & TIME DATA TYPES:

Lecture7 – Fall2024
SQL Statement

❑ Other DATA TYPES:

Lecture7 – Fall2024
SQL Date Data Types

SQL Server comes with the following data types for storing a date or
a date/time value in the database:

• DATE - format YYYY-MM-DD

• DATETIME - format: YYYY-MM-DD HH:MI:SS

• SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS

• TIMESTAMP - format: a unique number

Lecture7 – Fall2024
SQL TRUNCATE TABLE

▪ The TRUNCATE TABLE statement is used to delete the data


inside a table, but not the table itself.

❑ Syntax :
TRUNCATE TABLE table_name;

TRUNCATE TABLE Student;

Lecture7 – Fall2024
SQL Server Describe Table

▪ When working with databases in SQL Server it is essential to


understand the schema of the tables present in the database.
Describing a table means getting information about the structure
and metadata of the table.

❑ Syntax :
EXEC SP_HELP TableName;

EXEC SP_HELP Student;


EXEC SP_COLUMNS Customers;
Lecture7 – Fall2024
SQL DROP TABLE Statement

❑ Syntax :
DROP TABLE table_name;

Note: Be careful before dropping a table. Deleting a table will result


in loss of complete information stored in the table!

DROP TABLE Student;

Lecture7 – Fall2024
SQL ALTER TABLE

Alter Table

Columns Constraints

Add Alter Drop Rename Add Drop

Lecture7 – Fall2024
SQL ALTER TABLE Statement

• The ALTER TABLE statement is used to add, delete, or modify


columns in an existing table.

• The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.

Lecture7 – Fall2024
ALTER TABLE - ADD Column

➢ To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype column_constraint;

ALTER TABLE Student


ADD gender CHAR(1) DEFAULT 'm' CHECK (gender IN ('m','f’));

Lecture7 – Fall2024
ALTER TABLE - ADD Column
➢ To add more than on new columns to the table

➢ The basic syntax for Adding columns to the table is:


ALTER TABLE table_name
ADD
column1_namecolumn_definition,
column2_namecolumn_definition,
column3_namecolumn_definition ;

ALTER TABLE Student


ADD gender CHAR(1) DEFAULT 'm' CHECK (gender IN ('m','f’),
Email VARCHAR(50) );
Lecture7 – Fall2024
ALTER TABLE - DROP Column

➢ To delete a column in a table, use the following syntax

ALTER TABLE table_name


DROP COLUMN column_name;

ALTER TABLE Student


DROP COLUMN gender;

➢ Some database systems don't allow deleting a column

Lecture7 – Fall2024
ALTER TABLE - ALTER/MODIFY Column

➢ To change the data type of a column in a table, use the following


syntax:

ALTER TABLE table_name

ALTER COLUMN column_name datatype(size)

ALTER TABLE Student


ALTER COLUMN City VARCHAR(50) NOT NULL,
Lecture7 – Fall2024
ALTER TABLE - RENAME Column/TABLE

❑ Rename Table

EXEC SP_RENAME Old Table , New Table

EXEC SP_RENAME ‘Student' ,Student_1‘

❑ Rename Column
EXEC SP_RENAME Name table .Old Column, New Column

EXEC SP_RENAME ' University.FirstName' ,‘First_Name'


Lecture7 – Fall2024
IDENTITY Column

To explicitly supply a value for identity column

1. First turn on identity insert – SET Identity_insert TableName ON

2. In the insert query specify the column list

INSERT INTO TableName (Personid ,Name) VALUES(2,’Ali’)

SET IDENTITY_INSERT TableName ON

SET IDENTITY_INSERT TableName OFF

DBCC CHECKIDENT (TableName, RESEED,0)


Lecture7 – Fall2024
SQL Constraints

❑ NOT NULL - Ensures that a column cannot have a NULL value


❑ UNIQUE - Ensures that all values in a column are different
❑ PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
❑ CHECK - Ensures that all values in a column satisfies a specific
condition
❑ DEFAULT - Sets a default value for a column when no value is
specified
❑ FOREIGN KEY - Uniquely identifies a row/record in another table
❑ CREATE INDEX - Used to create and retrieve data from the
database very quickly
Lecture7 – Fall2024
SQL Constraints

Constraints can be specified when the table is created with the


CREATE TABLE statement, or after the table is created with the
ALTER TABLE statement.

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint, ....);
.
Lecture7 – Fall2024
SQL Constraints

CREATE TABLE Stu_1(

ID INT PRIMARY KEY IDENTITY(1,1)/ IDENTITY,


LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255) UNIQUE,
Age INT CHECK (Age>=18),

City VARCHAR(255) DEFAULT ‘Tripoli‘,

INDEX indexname (FirstName)

);
SQL Constraints

CREATE TABLE Stu_1(


ID INT IDENTITY(1,1),
LastName VARCHAR (255) NOT NULL,
FirstName VARCHAR (255),
Age INT CHECK (Age>=18),
Salary NUMERIC(7,2) CHECK(Salary BETWEEN 3000 AND 5000),
City VARCHAR(255) DEFAULT ‘Tripoli‘,
CONSTRAINT Student_ID_PK PRIMARY KEY(ID),
CONSTRAINT First_Name_UN UNIQUE(FirstName)
);
Lecture7 – Fall2024
SQL Constraints

CREATE TABLE Persons (


ID INT ,

ProductName VARCHAR(50),
Age int CHECK (Age BETWEEN 18 AND 21),

-- Age int CHECK (Age >=18 AND Age <= 21),

Gender CHAR(1)

);

Lecture7 – Fall2024
ADD Constraints
ALTER TABLE Persons
ADD CONSTRAINT Persons_ProductName_UQ UNIQUE (ProductName);
ALTER TABLE Persons
ADD CONSTRAINT Persons_PK PRIMARY KEY (ID);
ALTER TABLE Persons
ADD CONSTRAINT Persons_FK FOREIGN KEY(ID ,Name) REFERENCES
Person(personID , personName)
ADD CONSTRAINT Persons_FK FOREIGN KEY(ID) REFERENCES
Person(personID)
ALTER TABLE Persons
ADD CONSTRAINT Persons_Gender_Default DEFAULT 3 FOR Gender
Lecture7 – Fall2024
ADD Constraints

ALTER TABLE Persons

ADD CONSTRAINT Persons_ProductName_UQ CHECK (Age >


0 AND Age<150);

If the BOOLEAN_EXPRESSION returns true , then the CHECK


constraint allows the value , otherwise it doesn’t . Since , AGE is a
nullable column , it’s possible to pass null for this column , when
inserting a row. When you pass NULL for the AGE column , the
boolean expression evaluates to UNKNOWN , and allows the value.
Lecture7 – Fall2024
ADD Constraints

ALTER TABLE Persons

WITH CHECK ADD CONSTRAINT Persons_ProductName_UQ


CHECK (Age > 0 AND Age<150);

ALTER TABLE Persons

WITH NOCHECK ADD CONSTRAINT


Persons_ProductName_UQ CHECK (Age > 0 AND Age<150);

Lecture7 – Fall2024
ADD Constraints
ALTER TABLE Persons

ADD Hire_Date SMALLDATETIME NULL

CONSTRAINT Persons_ProductName_UQ DEFAULT


GETDATE() WITH VALUES

ALTER TABLE Persons

ADD CONSTRAINT Persons_ProductName_FK FOREIGN KEY


(EmpID) REFERENCES Department(DID);

Lecture7 – Fall2024
DROP Constraints

ALTER TABLE Persons

DROP CONSTRAINT Persons_ProductName_UQ;

ALTER TABLE Persons

DROP CONSTRAINT Persons_PK

Lecture7 – Fall2024
SQL FOREIGN KEY Constraint

▪ A FOREIGN KEY is a key used to link two tables together.

▪ A FOREIGN KEY is a field (or collection of fields) in one table


that refers to the PRIMARY KEY in another table.

▪ The table containing the foreign key is called the child table, and
the table containing the candidate key is called the referenced or
parent table.

Lecture7 – Fall2024
SQL FOREIGN KEY Constraint
ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }
Specifies what action happens to rows in the table created, if those rows have a referential
relationship and the referenced row is deleted from the parent table. The default is NO
ACTION.
❑ NO ACTION
The Database Engine raises an error and the delete action on the row in the parent table is
rolled back.
❑ CASCADE
Corresponding rows are deleted from the referencing table if that row is deleted from the parent
table.
❑ SET NULL
All the values that make up the foreign key are set to NULL if the corresponding row in the
parent table is deleted. For this constraint to execute, the foreign key columns must be nullable.
❑ SET DEFAULT
All the values that make up the foreign key are set to their default values if the corresponding
row in the parent table is deleted. For this constraint to execute, all foreign key columns must
have default definitions. If a column is nullable, and there is no explicit default value set,
NULL becomes the implicit default value of the column.
SQL FOREIGN KEY Constraint
ON UPDATE { NO ACTION | CASCADE \ SET NULL | SET DEFAULT }
Specifies what action happens to rows in the table altered when those rows have a referential
relationship and the referenced row is updated in the parent table. The default is NO ACTION.
❑ NO ACTION
The Database Engine raises an error, and the update action on the row in the parent table is
rolled back.
❑ CASCADE
Corresponding rows are updated in the referencing table when that row is updated in the parent
table.
❑ SET NULL
All the values that make up the foreign key are set to NULL when the corresponding row in the
parent table is updated. For this constraint to execute, the foreign key columns must be
nullable.
❑ SET DEFAULT
All the values that make up the foreign key are set to their default values when the
corresponding row in the parent table is updated. For this constraint to execute, all foreign key
columns must have default definitions. If a column is nullable, and there is no explicit default
value set, NULL becomes the implicit default value of the column.
SQL FOREIGN KEY Constraint
CREATE TABLE table_name
(col_name col_type
[NOT NULL| NULL]
[IDENTITY [ (seed , increment) ]]
[DEFAULT initial-value]
[CONSTRAINT const_name]{
[CHECK logical_expression]
[PRIMARY KEY col_name]
[FOREIGN KEY fore_name REFERENCES ref_tab_nam
[(par_col_name)]
[ON DELETE { NO ACTION | CASCADE | SET NULL | SET
DEFAULT}]
[ON UPDATE { NO ACTION | CASCADE | SET NULL | SET
DEFAULT} ]
}); Lecture7 – Fall2024
Example

Age Hour ProjName


ENO Fname PID

Phone M N
Employee Work_on Project

Employee

ENO Fname Age Phone


Project Name Database : Company
PID ProjNamae
Work_on

Eno PID Hour


Example

CREATE TABLE Project (


PID int PRIMARY KEY IDENTITY(1,1),
ProjName VARCHAR(255) NOT NULL);

CREATE TABLE Employee(


Eno int PRIMARY KEY ,
Fname VARCHAR(255) NOT NULL,
Age INT CHECK(Age>=24 AND Age <=60),
Phone UNIQUE);
Example

CREATE TABLE work_no(


PID INT ,

ENO INT,

Hour TIME ,

FOREIGN KEY (PID) REFERENCES Project(PID),

CONSTRAINT work_no_Employee FOREIGN KEY(ENO)


REFERENCES Employee(ENO),

PRIMARY KEY(PID,ENO) );
Lecture7 – Fall2024
❑ Database Schema (Relationship Schema)
In the relationship diagram, the tables are linked to each other through
the foreign key, and to create a database relationship diagram, we
expand the database that was created, right-click on the Database
Diagram, and create a New Database Diagram as in the following
figure:

Lecture7 – Fall2024
❑ Database Schema (Relationship Schema)

The following figure appears:

Lecture7 – Fall2024
❑ Database Schema (Relationship Schema)
We add the tables by pressing Add to show the following figure:

To create a relationship between two tables, we click and drag the


mouse on the field from the first table to the second table on the same
field, such as E_no in the Employee table with the same field in the
Work_on table, and the following figure appears:
Lecture7 – Fall2024
❑ Database Schema (Relationship Schema)

Through this form, the name of the relationship can be written in


Relationship name. The primary key has been selected with the
foreign key that is available in both tables, so we press OK, then OK,
so that the relationship chart appears as follows:
Lecture7 – Fall2024
❑ Database Schema (Relationship Schema)

To save the chart by saving from the toolbar and choosing the name of
the chart, and to delete a relationship between two tables, we right-
click on the relationship, and the following figure appears, so we
choose Delete Relationship Database, and thus we have deleted the
relationship between the two tables as in the following figure:
❑ The Entity – Relationship (ER) Model
❑ Database Schema

ExpiredDate
❑ CREATE DATABASE SuperMarket

❑ USE SuperMarket

❑ CREATE TABLE Customer (


CustomerID INT PRIMARY KEY IDENTITY(1,1),
FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255) NOT NULL,
Age INT CHECK (Age >= 18));

❑ CREATE TABLE CustomerPhone (


CustomerID INT ,
FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID) ,
Phone VARCHAR(255) ,
PRIMARY KEY (CustomerID , Phone));
❑ CREATE TABLE Bill (
BillID INT IDENTITY(1,1) PRIMARY KEY,
BillDate DATE ,
TotalAmount FLOAT CHECK(TotalAmount > 0),
Discount FLOAT,
CustomerID INT REFERENCES Customer(CustomerID));

❑ CREATE TABLE Product (


ProductID INT PRIMARY KEY,
ProductName VARCHAR(255) ,
Price FLOAT CHECK (Price >0),
ExpiredDate DATE CHECK(ExpiredDate > GETDATE())

);
❑ CREATE TABLE BillProducts (
BillID INT REFERENCES Bill(BillID),
ProductID INT REFERENCES Product(ProductID),
Quantity FLOAT CHECK (Quantity > 0),
PRIMARY KEY (BillID , ProductID));
Database Diagram

You might also like