0% found this document useful (0 votes)
2 views13 pages

Week 12-13 DDL

Uploaded by

f2023266820
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)
2 views13 pages

Week 12-13 DDL

Uploaded by

f2023266820
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/ 13

Database Systems (CC-230)

Lecture # 23-26

Instructor
Rida Ayesha
Lecture # 23-26 Agenda:
SQL: Data Definition Language (Create, Alter, Drop, Truncate)
Introduction to SQL
• Objectives of SQL
• History of SQL
• Importance of SQL
• Terminology

The ISO SQL Data Types


• SQL Identifiers
• SQL Scalar Data Types

Comments in SQL Server (Single line & multi line)

Integrity Enhancement Feature (Implementation in MS SQL)


• Entity Integrity
• Referential Integrity
• Domain Integrity
• Key Constraints (PK, FK, Not Null, Check, Unique and Default)

Data Definition
• Creating a Database
• Dropping & Renaming a Database
• Creating a Table (CREATE TABLE with default & named constraints)
• Changing a Table Definition (ALTER TABLE – add column(s), change datatype of column(s),
rename column(s), drop column(s), add constraint(s), drop constraint(s))
• Removing a Table (DROP TABLE)
• Truncate a Table (TRUNCATE TABLE)

Class Examples/Class Activity in MS SQL Server

2
Introduction to SQL
What is SQL?

SQL (Structured Query Language) is a standard language used to manage and manipulate
relational databases.

Objectives of SQL

• Create and modify database structures (DDL)


• Insert, update, delete data (DML)
• Retrieve data through queries (DQL)
• Control access to data (DCL)
• Manage transactions (TCL)

History of SQL

• Developed in the 1970s by IBM (System R project)


• Originally called SEQUEL
• Standardized by ANSI in 1986 and ISO in 1987
• Adopted by almost all RDBMSs (e.g., SQL Server, Oracle, MySQL)

Importance of SQL

• Universal standard for database communication


• Required skill in data-related fields (analytics, development)
• Enables complex querying and reporting
• Supports relational integrity and security

Key Terminology

Term Meaning

Table A collection of rows and columns

Row (Tuple) A single record in a table

Column A data field within a table

Primary Key Uniquely identifies each record

Foreign Key Links records between tables

Schema A logical structure grouping database objects

3
The ISO SQL Data Types
SQL Identifiers

• Names used for tables, columns, constraints, etc.


• Must begin with a letter; can include letters, digits, and underscores
• Whitespaces or hyphen are not allowed
• Case-insensitive by default in SQL Server

Examples: EmployeeID, Dept_Name, Salary2025

MS SQL Server: Scalar Data Types


Data types define the kind of data a column can store.

Categories of Data Types:

Category Data Type Description Example

INT, BIGINT, DECIMAL(p,s), FLOAT,


Numeric Numbers (whole, decimal) Salary DECIMAL(8,2)
TINYINT

CHAR(n), VARCHAR(n), Name


String Fixed/Variable length text
VARCHAR(MAX) VARCHAR(100)

DATE, TIME, DATETIME,


Date/Time Store date and/or time DOB DATE
SMALLDATETIME

Logical BIT Boolean (0 = False, 1 = True) IsActive BIT

Image
Binary BINARY(n), VARBINARY(n) Binary data
VARBINARY(MAX)

UID
Unique ID UNIQUEIDENTIFIER Globally unique value
UNIQUEIDENTIFIER

1. Numeric Data Types

Used to store numbers (integers or decimals).

Data Type Description Example


INT Integer values 100, -20
BIGINT Very large integers 922337203685...
SMALLINT Small integers 32767
TINYINT Very small integers (0–255) 200

4
Data Type Description Example
DECIMAL(p,s) Fixed precision and scale numbers DECIMAL(5,2) → 123.45
FLOAT Approximate floating point numbers 123.4567

2. Character/String Data Types

Data Type Description Example


CHAR(n) Fixed-length string (padded if short) CHAR(5) → 'Hi '
VARCHAR(n) Variable-length string VARCHAR(50) → 'Hello'
TEXT (deprecated) Large text data – use VARCHAR(MAX) instead 'Long text...'

3. Date and Time Data Types

Data Type Description Example


DATE Stores only date '2025-05-29'
TIME Stores only time '14:30:00'
DATETIME Stores date and time '2025-05-29 14:30:00'
SMALLDATETIME Stores date and time (less precise) '2025-05-29 14:30'

4. Boolean / Logical

Data Type Description Example


BIT 0 or 1 (true/false) 1

5. Unique Identifiers

Data Type Description Example


UNIQUEIDENTIFIER Globally unique ID (GUID) '6F9619FF-8B86-D011-B42D-00C04FC964FF'

6. Binary Data

Data Type Description Example


BINARY(n) Fixed-length binary data BINARY(8)
VARBINARY(n) Variable-length binary data VARBINARY(MAX)

5
Examples: Choosing Data Types in a Table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
BirthDate DATE,
IsActive BIT,
Salary DECIMAL(10, 2)
);

• Use VARCHAR instead of CHAR unless fixed length is needed.


• Use BIT for yes/no values.
• Choose DECIMAL over FLOAT for exact numeric values (e.g., money).
• Avoid deprecated types like TEXT; use VARCHAR(MAX) instead.

Comments in SQL Server


In SQL Server, comments are used to document code or temporarily disable parts of a query.

1. Single-Line Comment

Use two dashes -- before the comment.

-- This is a single-line comment


SELECT * FROM Employees; -- Fetch all employee records

2. Multi-Line Comment

Wrap the comment with /* ... */

/*
This query retrieves employee details
who are currently active
*/
SELECT * FROM Employees
WHERE IsActive = 1;

6
SQL Constraints in Table Creation
Constraints enforce rules on data.

Constraint Description Example

NOT NULL Column cannot be empty Name VARCHAR(100) NOT NULL

DEFAULT Set default value if none provided IsActive BIT DEFAULT 1

PRIMARY
Uniquely identifies each row EmployeeID INT PRIMARY KEY
KEY

UNIQUE Ensures all values in a column are different Email VARCHAR(100) UNIQUE

CHECK Ensures condition is met CHECK (Salary > 0)

FOREIGN FOREIGN KEY (DeptID) REFERENCES


Links to a column in another table
KEY Departments(DeptID)

Example with Constraints (Way 01)


CREATE TABLE Departments (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(100) NOT NULL
);

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Email VARCHAR(100) UNIQUE,
Salary DECIMAL(10, 2) CHECK (Salary > 0),
IsActive BIT DEFAULT 1,
DeptID INT FOREIGN KEY REFERENCES Departments(DeptID)
);

Example with Named Constraints (Way 02)


CREATE TABLE Departments (
DeptID INT,
DeptName VARCHAR(100) NOT NULL,
CONSTRAINT pk_dept PRIMARY KEY (DeptID)
);

CREATE TABLE Employees (


EmployeeID INT,
Name VARCHAR(100) NOT NULL,
Email VARCHAR(100),

7
Salary DECIMAL(10, 2),
IsActive BIT DEFAULT 1,
DeptID INT,

-- Constraints
CONSTRAINT pk_empId PRIMARY KEY (EmployeeID),
CONSTRAINT uq_emp_email UNIQUE (Email),
CONSTRAINT chk_emp_salary CHECK (Salary > 0),
CONSTRAINT fk_emp_dept FOREIGN KEY (DeptID) REFERENCES Departments(DeptID)
);

Explanation of Named Constraints:

Constraint Type Syntax Used Description

Primary Key CONSTRAINT pk_empId PRIMARY KEY (...) Named pk_empId for EmployeeID

Unique CONSTRAINT uq_emp_email UNIQUE (...) Ensures email uniqueness

Check CONSTRAINT chk_emp_salary CHECK (...) Validates that salary > 0

CONSTRAINT fk_emp_dept FOREIGN KEY (...)


Foreign Key Links to Departments table
REFERENCES ...

Common ALTER Commands


Operation SQL Syntax Example

Add a column ALTER TABLE Employees ADD Age INT;

Modify column datatype ALTER TABLE Employees ALTER COLUMN Name VARCHAR(150);

Drop a column ALTER TABLE Employees DROP COLUMN Age;

Add constraint ALTER TABLE Employees ADD CONSTRAINT chk_salary CHECK (Salary > 1000);

Drop constraint ALTER TABLE Employees DROP CONSTRAINT chk_salary

Adding a Column with NOT NULL Constraint


In SQL Server, when you add a NOT NULL column, you must also provide a default value if
the table already contains data — because existing rows need a value for that new column.
Syntax:

8
ALTER TABLE table_name
ADD column_name datatype NOT NULL DEFAULT default_value;

Example

Let’s say you have an Employees table, and you want to add a new column called Gender that
should not be null.

ALTER TABLE Employees


ADD Gender CHAR(1) NOT NULL DEFAULT 'M';

This will:

• Add a column Gender of type CHAR(1)


• Ensure it cannot be null (NOT NULL)
• Assign 'M' to existing rows by default

Without a DEFAULT:

If the table has existing data and you don't use DEFAULT, this will throw an error:

-- This will FAIL if Employees has data


ALTER TABLE Employees
ADD Gender CHAR(1) NOT NULL;

DROP and TRUNCATE


Command Use Case Example

DROP TABLE Delete the entire table & structure DROP TABLE Employees;

DROP DATABASE Delete the whole database DROP DATABASE CompanyDB;

TRUNCATE TABLE Remove all rows (faster than DELETE) TRUNCATE TABLE Employees;

Notes:

• DDL commands auto-commit – they cannot be rolled back in most cases.


• Always take backups before DROP or TRUNCATE.

9
RENAME Operations in SQL Server
1. Rename a Column
Syntax:
EXEC sp_rename 'table_name.old_column_name', 'new_column_name', 'COLUMN';

Example:

Rename the Salary column in Employees to MonthlySalary:

EXEC sp_rename 'Employees.Salary', 'MonthlySalary', 'COLUMN';

2. Rename a Table
Syntax:
EXEC sp_rename 'old_table_name', 'new_table_name';

Example:

Rename Employees table to Staff:

EXEC sp_rename 'Employees', 'Staff';

3. Rename a Database

Renaming a database must be done carefully — make sure no one is connected to it.

Option 1: Using ALTER DATABASE


ALTER DATABASE OldDBName MODIFY NAME = NewDBName;

Example:
ALTER DATABASE CompanyDB MODIFY NAME = CorporateDB;

Ensure:

• You are not currently using the database you're trying to rename.
• Switch to master first:

USE master;

10
DDL for Relationships in SQL Server

1. One-to-One (1:1)
Definition: One record in Table A is related to one and only one record in Table B.

Example: Person ↔ Passport

CREATE TABLE Person (


PersonID INT PRIMARY KEY,
Name VARCHAR(100)
);

CREATE TABLE Passport (


PassportID INT PRIMARY KEY,
PersonID INT UNIQUE, -- Ensures one-to-one
PassportNumber VARCHAR(20),
FOREIGN KEY (PersonID) REFERENCES Person(PersonID)
);

Explanation:

• PersonID in Passport is both foreign key and UNIQUE.


• Ensures each person has only one passport, and each passport belongs to only one
person.

2. One-to-Many (1:N)
Definition: One record in Table A can be related to many records in Table B.

Example: Department → Employee

CREATE TABLE Department (


DeptID INT PRIMARY KEY,
DeptName VARCHAR(100)
);

CREATE TABLE Employee (


EmpID INT PRIMARY KEY,
Name VARCHAR(100),
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES Department(DeptID)
);

Explanation:

11
• One department can have many employees.
• Each employee belongs to only one department.

Creating Composite Primary Key


In MS SQL Server, a composite primary key is a primary key made up of two or more
columns. You define it using either:

1. Inline Table Constraint (at CREATE TABLE time)

You can define it after the column definitions using PRIMARY KEY (column1, column2, ...).

Example:
CREATE TABLE Orders (
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID)
);

This creates a composite primary key on OrderID and ProductID.

2. Named Constraint

You can also name the constraint explicitly:

CREATE TABLE Orders (


OrderID INT,
ProductID INT,
Quantity INT,
CONSTRAINT PK_Orders PRIMARY KEY (OrderID, ProductID)
);

3. Adding Composite Primary Key to Existing Table

If the table already exists:

ALTER TABLE Orders


ADD CONSTRAINT PK_Orders PRIMARY KEY (OrderID, ProductID);

Notes:

• Columns in a composite key cannot be NULL.


• The order of columns matters — it affects indexing and how uniqueness is enforced.

12
3. Many-to-Many (M:N)
Definition: Multiple records in Table A relate to multiple records in Table B.

Example: Student ↔ Course

We need a junction (bridge) table for many-to-many relationships.

CREATE TABLE Student (


StudentID INT PRIMARY KEY,
Name VARCHAR(100)
);

CREATE TABLE Course (


CourseID INT PRIMARY KEY,
Title VARCHAR(100)
);

-- Junction table
CREATE TABLE StudentCourse (
StudentID INT,
CourseID INT,
EnrollmentDate DATE,
PRIMARY KEY (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
FOREIGN KEY (CourseID) REFERENCES Course(CourseID)
);

Explanation:

• A student can enroll in many courses.


• A course can have many students.
• Composite primary key ensures no duplicate enrollments.

13

You might also like