0% found this document useful (0 votes)
98 views118 pages

Database Management Systems Syllabus

This document provides a syllabus for a database management systems course. It covers relational databases, relational algebra operations like select, project, join, and SQL. It introduces the relational model and defines key concepts like relations, attributes, tuples, domains, and schemas. It discusses integrity constraints, synthesizing ER diagrams to relational schemas, and provides examples of 1:1, 1:N, and N:N relationships. It also includes two case studies and explains relational algebra operations like project and select.
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)
98 views118 pages

Database Management Systems Syllabus

This document provides a syllabus for a database management systems course. It covers relational databases, relational algebra operations like select, project, join, and SQL. It introduces the relational model and defines key concepts like relations, attributes, tuples, domains, and schemas. It discusses integrity constraints, synthesizing ER diagrams to relational schemas, and provides examples of 1:1, 1:N, and N:N relationships. It also includes two case studies and explains relational algebra operations like project and select.
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

CST 204 – Database Management Systems - MODULE

II
SYLLABUS
Structure of Relational Databases - Integrity Constraints, Synthesizing
ER diagram to relational schema

Introduction to Relational Algebra - select, project, cartesian product


operations, join - Equi-join, natural join. query examples, introduction
to Structured Query Language (SQL), Data Definition Language (DDL),
Table definitions and operations – CREATE, DROP, ALTER, INSERT,
DELETE, UPDATE.
Relational Model (RM)
Relational Model (RM)

► Relational Model (RM) represents the database as a collection of


relations.

► A relation is nothing but a table of values.

► Every row in the table represents a collection of related data values.


These rows in the table denote a real-world entity or relationship.

► It is used for data storage and processing


Relational Model (RM)
► Attribute: A column header of a table is known as attribute of a
relation.
► Tuple: A row in a table represents the record of a relation and known
as a tuple of a relation.
► Domain: A set of possible values for a given attribute is known as
domain of a relation.
► Relation Schema: A relation schema represents name of the relation
with its attributes. e.g.; EMPLOYEE (EmployeeId, FirstName,
LastName, Salary)
Relational Model (RM)

► Degree: The number of attributes in the relation is known as degree


of the relation. The EMPLOYEE relation defined above has degree 4.
► Cardinality: The number of tuples in a relation is known as
cardinality. The EMPLOYEE relation defined has cardinality 4.
Relational Model (RM)

Informal Terms Formal Terms


Table Relation
Column header / field Attributes
All possible column values Domain
Row Tuple
Table definition Schema of relation
Characteristics of Relational Database Model
► Each relation in a database must have a distinct or unique name
which would separate it from the other relations in a database.
► A relation must not have two attributes with the same name. Each
attribute must have a distinct name.
► Duplicate tuples must not be present in a relation.
Characteristics of Relational Database Model
► Each tuple must have exactly one data value for an attribute.
► For example, below in the first table, you can see that for Roll_No. 265 we have
enrolled two students Jhoson and Charles, this would not work. We must have
only one student for one Roll_No.
Characteristics of Relational Database Model
► Tuples in a relation do not have to follow a significant order as the
relation is not order-sensitive.
► Similarly, the attributes of a relation also do not have to follow
certain ordering, it’s up to the developer to decide the ordering of
attributes.
Relational Integrity Constraints
Relational Integrity Constraints

► Relational Integrity constraints in DBMS are referred to conditions


which must be present for a valid relation.

► Constraints on the Relational database management system is mostly


divided into three main categories are:

► Domain Constraints
► Entity integrity constraints
► Key Constraints
► Referential Integrity Constraints
Domain Constraints
► Each attribute in a tuple is declared to be of a particular domain (for
example, integer, character, Boolean, String, etc.) which specifies a
constraint on the values that an attribute can take.
Entity integrity constraints
► The entity integrity constraint states that primary key value can't be
null.
► This is because the primary key value is used to identify individual rows in
relation and if the primary key has a null value, then we can't identify those
rows.
► A table can contain a null value other than the primary key field.
Key constraints
► Keys are used to uniquely identify an entity within its entity set.
► An entity set can have multiple keys, but out of which one key will be
the primary key.
► A primary key can contain a unique value in the relational table.
Referential Integrity Constraints
► A referential integrity constraint is specified between two tables.
► In the Referential integrity constraints, if a foreign key in Table 1 refers to the
Primary Key of Table 2, then every value of the Foreign Key in Table 1 must be
null or be available in Table 2.
Synthesizing ER diagram to relational schema
Entities and Simple Attributes
► An entity type within ER diagram is turned into a table.
► Each attribute turns into a column in the table.
► The key attribute of the entity is the primary key of the table which is
usually underlined.
► It is highly recommended that every table should start with its
primary key attribute conventionally named as TablenameID.
Entities and Simple Attributes

Primary key

► The initial relational schema is expressed in the following format


writing the table names with the attributes list inside a parentheses
as shown below for
PERSONS( personid , name, dateOfBirth, gender)

► personid is the primary key for the table : Persons


Multi-Valued Attributes

Foreign key

► If you have a multi-valued attribute, take the attribute and turn it into a new entity
or table of its own.
► Then make a 1:N relationship between the new entity and the existing one.
► Create a table for the attribute.
► Add the primary (id) column of the parent entity as a foreign key within the new table

PERSONS( personid , name, dateOfBirth, gender)


PERSONS_PHONE(personid ,phone)
personid within the table Phones is a foreign key referring to the personid of Persons
1:1 Relationships
For cases when the Person is not married i.e. has no
wifeID, the attribute can be set to NULL

PERSONS( personid , name, dateOfBirth, gender, wifeid)


PERSONS_PHONE(personid ,phone)
WIFE(wifeid , name )
1:N Relationships

For instance, the Person can have a House


from zero to many , but a House can have only
one Person.
To represent such relationship the personid as
the Parent node must be placed within the
Child table as a foreign key

PERSONS( personid , name, dateOfBirth, gender)


PERSONS_PHONE(personid ,phone)
HOUSE(houseid, personid, number , address)
N:N Relationships
Weak Entity

BUILDING( Building_No, Building_name, Address)


APARTMENT(Buiding_No ,Door_No, floor )
Case Study 1
Case Study 1
CAR(Car_ID,Serial_Number,Model_Number,Color,Year,Customer_ID,Emp_ID)
CUSTOMER(Customer_ID,Name, PhoneNumber, Address, Country, City)
EMPLOYEE(Emp_ID, Name, Address)
EMPLOYEE_QUALIFICATION(Emp_ID,Qualification)
INVOICE(Invoice_ID,Date,Emp_ID,Customer_ID)
Case Study 2
Case Study 2
EMPLOYEE(Emp_ID, First_Name,Last_Name,DOB,Company_Id,Project_Id)
EMPLOYEE_CONTACT_NUMBER(Emp_ID,Contact_Number)
COMPANY(Company_Id,Company_Name,Location)
PROJECT(Project_Id,Project_Name,Start_Date)
SALARY(EMP_Id,Amount,Date_Of_Salary,Mode_of_Payment)
Relational Algebra
Relational Algebra

► Database management systems (DBMS) must have a query language so


that the users can access the data stored in the database.

► Relational Algebra is a procedural query language where the user tells the
system to carry out a set of operations to obtain the desired results.
► The user tells what data should be retrieved from the database and how to retrieve it.

► In relational algebra,
► input is a relation (table from which data has to be accessed) and
► output is also a relation (a temporary table holding the data asked for by the user).
Relational Algebra

► Relational Algebra works on the whole table at once, so we do not have


to use loops etc. to iterate over all the rows (tuples) of data one by one.

► All we have to do is specify the table name from which we need the data,
and in a single line of command, relational algebra will traverse the entire
table to fetch data for you.
Relational Algebra
Project(∏)
► Project Operation is used to project or display or get the required column
data from the relation.

► It is denoted by symbol pi(Π).


► This operation eliminates duplicate values while fetching the data.

ς 𝐶1 𝐶2 𝐶𝑛 (𝑅)
, ,….

where C1, C2,...Cn are the column names of relation R.


Project(∏) - Example
► We have an employee table with attributes as Emlpoyee_id, Name, Salary,
Age. We want the name and the age of the employees from the table.

𝝅𝑵𝒂𝒎𝒆,𝑨𝒈𝒆 (𝑬𝒎𝒑𝒍𝒐𝒚𝒆𝒆)
Select(σ)
► Select operation selects the required tuples from the relation according
to the given conditions.
► It is denoted by symbol sigma(σ).
► The select operator only selects the tuples from the relation but to
display those tuples we have to use the project operator.

𝜎𝑝 (𝑅)

► where p denotes the logic according to which the selection is done and R
is the relation.
Select(σ) - Example
► We have an employee table with attributes as name, emlpoyee_id,
salary, age.
► We want the details of all those employee whose age is greater than 26.
The query for the above operation would be

𝜎𝑎𝑔𝑒>26 (𝐸𝑚𝑝𝑙𝑜𝑦𝑒𝑒)

The above operation would select the tuple from the employee relation.
But to display the selected tuple we will have to perform the project operation.
As we need all the details of the employee so we don't provide any condition in the
project operation.
If we don't provide any column name in project operation then it would project all the
columns. So, the new query would be:
Select(σ)- Example

𝜋(𝜎𝑎𝑔𝑒>26 (𝐸𝑚𝑝𝑙𝑜𝑦𝑒𝑒))

After the above operations, the result would be as follows:


Cross Product(X)

► This operation is performed to merge columns from two relations.


► It is denoted by the symbol X.
► Usually, the cross operation is not meaningful but are useful when
combined with some other operations like select, project etc.
► The cross product is also known as the Cartesian product .

► Notation: R1 X R2
► where R1 and R2 are two relations such that the cross product will result in a table
which has all the attributes of the table R1 followed by the attributes of the R2.
Cross Product(X)- Example

► We have two tables of


Student(S_id, Name, Class,
Age) and Courses(C_id,
C_name).

► Now, we will perform the cross


product of both tables i.e Student
X Courses

► If the first table has m tuples and


the second table has n tuples then
their cross product will have m*n
tuples.
Union(U)

► The union operation performs the same function as the union


operation in the set theory. It is represented by U symbol.
► If we perform an operation A U B on table A and B, then the result
would include all the tuples that are in table A as well as in table B.
► This operation removes the duplicate tuples.
► For performing a union operation both the tables should have the
same attributes.
► Notation: R1 U R2 where R1 and R2 are two tables.
Union(U)- Example

► We have two courses table and


we want to perform the union
operation on table
Course_1(C_id,C_name) and
Course_2(C_id,C_name).
► Remember, we can perform
union operation only because
both the tables have same
attribute.
► Course_1 U Course_2
Set Difference(-)

► The set difference operation performs the same function as the set
difference operation in the set theory.
► It is represented by -(minus) symbol.
► If we perform an operation A-B on table A and B, then the result would
include only those tuples that are in table A but not in B.
► This operation removes all those tuples which are common in both table A and B,
from A and gives output.
► For performing a set difference operation both the tables should have
the same attributes.
► Notation: R1 - R2 where R1 and R2 are two tables.
Set Difference - Example

► We have two courses table and we


want to perform the set difference
operation on table
Course_1(C_id,C_name) and
Course_2(C_id,C_name).

► Remember, we can perform set


difference operation only because
both the tables have same
attribute.

► Course_1 - Course_2
Rename(ρ)

► The results of the operations that we are performing are saved without
any name.
► If we want to give some name to the result of any operation then we
can rename the result of the operations using the rename operation.
► It can also be used to rename an old relation. It is denoted by symbol
rho (ρ).
► Notation 1: Naming the result of an operation ρh(E)
► where the result of expression E is stored as h.
► Notation 2: Renaming an already existing column ρNew_Name/Old_Name(E)
Rename

► Example1 : In the previous example of the 'union' operation we can


store the result of the union operation in a variable named 'All
_Courses‘
ρAll_Courses(Course_1 U Course_2)

► Example 2 : In the previous example of the 'union' operation we can


rename the attribute C_id of the Course_1 table to Course_id using the
folllowing query.
ρCourse_id/C_id(Course_1 )
Join Operation
Join Operation

► Join operation is used to combine two or more tables based on the


related attributes.
► It is basically a cross product followed by some more operations like
select, project etc.
► There are mainly two types of join which are further divided as follows:
► Inner Join ► Outer Join
► Natural Join ► Left Outer Join
► Theta Join ► Right Inner Join
► Equi Join ► Full Outer Join
Inner Join

► Inner join is a type of join in which only those tuples are selected which
full fill the required conditions.

► All those tuples which do not satisfy the required conditions are
excluded. Let us now study in detail each type of inner join with
example.
Natural Join(⋈)
► Natural Join is a join which is
performed if there is a
common attribute between
the relations.
► Notation: R1 ⋈ R2 where R1
and R2 are two relations.
► Example: We have two tables of
Student(S_id,Name,Class,Age
,C_id) and Courses(C_id,
C_name). Now, we will perform
natutral join on both the tables
i.e
► Student ⋈ Course
Theta Join (θ)

► Theta join is a join which combines the tuples from different relations
according to the given theta condition.
► The join condition in theta join is denoted by theta (θ) symbol. This
join uses all kind of comparison operator.
Notation: R1⋈ θ R2
► where R1 and R2 are relations such that they don't have any common
attribute.
Theta Join (θ) - Example
► We have two tables of
Student(S_id,Name,Std,Age)
and Courses(Class,C_name).

► Student ⋈ [Link]=[Link]
Course

► The above join operations check if


the 'Std' attribute in Student is
equal to the values of the 'Class'
attribute of the Course table. If
these values are equal then it is
included in the resulting table.
Equi Join

► Equi Join is a type of theta join where we use only the equality
operator, unlike theta join where we can use any operator.
► The previous example which we gave in the theta join is also an
example of equi-join.
Outer Join

► In Inner Join, the matched rows are returned and unmatched rows are
not returned.
► But, in outer join, we include those tuples which meet the given
condition along with that, we also add those tuples which do not meet
the required condition.
► The result also includes the tuples from the left and right tables which
do not satisfy the conditions.
► Based on the tuples that are added from left, right or both the tables,
the outer join is further divided into three types. We will now study
about its types with the help of examples.
► Note: The operators here define the existence of null value which we will use to fill
the table if the required conditions do not match.
Left Outer Join(⟕)

► Left Outer Join is a type of join in which all the tuples from left relation
are included and only those tuples from right relation are included
which have a common value in the common attribute on which the join
is being performed.

► Notation: R1⟕R2 where R1 and R2 are relations.


Left Outer Join(⟕) - Example
► We have two tables of Student(S_id,Name,Class,Age,C_type) and
Courses (C_type,C_name).
► Student ⟕ Course
Right Outer Join(⟖)
► Right Outer Join is a type of join in which all the tuples from right
relation are included and only those tuples from left relation are
included which have a common value in the common attribute on
which the right join is being performed.

► Notation: R1 ⟖ R2 where R1 and R2 are relations.


Right Outer Join(⟖) - Example
► We have two tables of Student(S_id,Name,Class,Age,C_type) and
Courses(C_type,C_name). Now, we will perform right outer on both
the tables i.e

► Student ⟖ Course
Full Outer Join(⟗)
► Full Outer Join is a type of join in which all the tuples from the left and
right relation which are having the same value on the common
attribute. Also, they will have all the remaining tuples which are not
common on in both the relations.
► Notation: R1 ⟗ R2 where R1 and R2 are relations.
Full Outer Join(⟗) - Example
► We have two tables of and Courses (C_type,C_name). Now, we
Student(S_id,Name,Class,Age,C_type) will perform full outer join
on both the tables i.e
► Student ⟗ Course
JOIN
Intersect (∩)
► The intersect operation performs the same function as the intersect
operation in the set theory.
► It is represented by ∩ symbol.
► This operation selects all those tuples from the relation which are
common in both the relation.
► Notation: R1 ∩ R2 where R1 and R2 are two relations.
Intersect (∩)
► Example: We have two courses table and we want to perform the intersect operation
on table Course_1(C_id, C_name) and Course_2(C_id, C_name). Remember,
we can perform intesect operation only because both the tables have same attributes.
► Course_1 ∩ Course_2
Example Queries -1
► Assume the following relations:
BOOKS(DocId, Title, Publisher, Year)
STUDENTS(StId, StName, Major, Age)
AUTHORS(AName, Address)
borrows(DocId, StId, Date)
has-written(DocId, AName)
describes(DocId, Keyword)
1. List the year and title of each book.
2. List all information about students whose major is CS
3. List all students with the books they can borrow
4. List all books published by McGraw-Hill before 1990
5. List the name of those authors who are living in Davis
6. List the name of students who are older than 30 and who are not studying CS
7. Rename AName in the relation AUTHORS to Name.
Example Queries -1
► List the year and title of each book.
► πYear, Title(BOOKS)
Example Queries -1
► List the year and title of each book.
► πYear, Title(BOOKS)
► List all information about students whose major is CS
► π (σMajor = ’CS’(STUDENTS))
Example Queries -1
► List the year and title of each book.
► πYear, Title(BOOKS)
► List all information about students whose major is CS
► π (σMajor = ’CS’(STUDENTS))
► List all students with the books they can borrow
► π (STUDENTS × BOOKS)
Example Queries -1
► List the year and title of each book.
► πYear, Title(BOOKS)
► List all information about students whose major is CS
► π (σMajor = ’CS’(STUDENTS))
► List all students with the books they can borrow
► π (STUDENTS × BOOKS)
► List all books published by McGraw-Hill before 1990
► π (σPublisher = ’McGraw-Hill’ ∧ Year<1990(BOOKS))
Example Queries -1
► List the year and title of each book.
► πYear, Title(BOOKS)
► List all information about students whose major is CS
► π (σMajor = ’CS’(STUDENTS))
► List all students with the books they can borrow
► π (STUDENTS × BOOKS)
► List all books published by McGraw-Hill before 1990
► π (σPublisher = ’McGraw-Hill’ ∧ Year<1990(BOOKS))
► List the name of those authors who are living in Davis
► πAName(σAddress like ’%Davis%’(AUTHORS))
Example Queries - 1
► List the name of students who are older than 30 and who are not
studying CS
► πStName(σAge>30(STUDENTS)) − πStName(σMajor=’CS’(STUDENTS))
Example Queries - 1
► List the name of students who are older than 30 and who are not
studying CS
► πStName(σAge>30(STUDENTS)) − πStName(σMajor=’CS’(STUDENTS))
► Rename AName in the relation AUTHORS to Name
► ρAName/Name(AUTHORS)
Example Queries - 2
► Assume the following relations:
BOOKS(DocId, Title, Publisher, Year)
STUDENTS(StId, StName, Major, Age)
AUTHORS(AName, Address)
borrows(DocId, StId, Date)
has-written(DocId, AName)
describes(DocId, Keyword)
1. List each book with its keywords.
2. List each student with the books she/he has borrowed.
3. List the title of books written by the author ’Ullman’
4. List the authors of the books the student ’Smith’ has borrowed
5. Which books have both keywords ’database’ and ’programming’?
Example Queries -2
Q: List each book with its keywords.
BOOKS ⋈ describes
Note that books having no keyword will not be there in the result.
Q: List each student with the books she/he has borrowed.
BOOKS ⋈ (borrows ⋈ STUDENTS)
Q: List the title of books written by the author ’Ullman’
πTitle(σAName=’Ullman’(BOOKS ⋈ has-written))
Or
πTitle(BOOKS ⋈ σAName=’Ullman’(has-written))
Q: List the authors of the books the student ’Smith’ has borrowed
πAName(σStName=’Smith’(has-written ⋈ (borrows ⋈ STUDENTS))
Example Queries -2
Q: Which books have both keywords ’database’ and ’programming’?

BOOKS ⋈ (πDocId(σKeyword=’database’(describes)) ∩
πDocId(σKeyword=’programming’(describes)))
Example Queries - 3
► Assume the following relations:
SALESPERSON(Ssn, Name, StartYear, DeptNo)
TRIP(Ssn, FromCity, ToCity, DepartureDate, ReturnDate, TripId)
EXPENSE(TripId, AccountNo, Amount)
► Write relation algebra expression to get the details of salespersons who hav
travelled between Mumbai and Delhi and the travel expense is greater that
Rs. 50000.
► πSsn,Name,StartYear,DeptNo(σ(FromCity=‘Mumbai’ and ToCity=‘Delhi’) or (FromCity=‘Delhi’ and
ToCity=‘Mumbai’) and Amount>5000(SALESPERSON ⋈ (TRIP ⋈ EXPENSE))))
Example Queries - 4
► Assume the following relations:
SALESPERSON(Ssn, Name, StartYear, DeptNo)
TRIP(Ssn, FromCity, ToCity, DepartureDate, ReturnDate, TripId)
EXPENSE(TripId, AccountNo, Amount)
Specify the subsequent queries in relational algebra:
1. Give the details (all attributes of TRIP) for trips which exceeded $2000 in expenses.
2. Print the SSN of salesman who took trips to ‘Honolulu'
3. Print the trip expenses incurred through the salesman with SSN= ‘234-56-7890'.
Example Queries - 4
► Assume the following relations:
SALESPERSON(Ssn, Name, StartYear, DeptNo)
TRIP(Ssn, FromCity, ToCity, DepartureDate, ReturnDate, TripId)
EXPENSE(TripId, AccountNo, Amount)
Specify the subsequent queries in relational algebra:
1. Give the details (all attributes of TRIP) for trips which exceeded $2000 in expenses.
A: πSsn, FromCity, ToCity, DepartureDate, ReturnDate, TripId (σAmount>2000(TRIP ⋈ EXPENSE))
2. Print the SSN of salesman who took trips to ‘Honolulu‘
A: π Ssn(σToCity=‘Honolulu‘ (TRIP))

3. Print the trip expenses incurred through the salesman with SSN= ‘234-56-7890'.

A: πAmount(σSsn=‘234-56-7890'(TRIP ⋈ EXPENSE))
References
► [Link]
► [Link]
algebra-operators-in-dbms-1ff2ddecaad7
► [Link]
algebra/
► [Link]
► [Link]
Introduction to Structured Query Language (SQL)
History
► Structured Query Language(SQL) was developed at IBM
by Donald D. Chamberlin and Raymond F. Boyce in the
early 1970s.
► This was initially called SEQUEL(Structured English
QUEry Language).
► The main objective of SQL is to update, store,
manipulate and retrieve data stored in a relational
database.

Donald D. Chamberlin Raymond F. Boyce


Data Definition Language
► The SQL data-definition language (DDL) allows the specification of
information about relations, including:
► The schema for each relation.
► The domain of values associated with each attribute.
► Integrity constraints
Domain Types in SQL
► char(n). Fixed length character string, with user-specified length n.
► varchar(n). Variable length character strings, with user-specified
maximum length n.
Domain Types in SQL
► char(n). Fixed length character string, with user-specified length n.
► varchar(n). Variable length character strings, with user-specified
maximum length n.
► int. Integer (a finite subset of the integers that is machine-dependent).
► smallint. Small integer (a machine-dependent subset of the integer
domain type).
► numeric(p,d). Fixed point number, with user-specified precision of p
digits, with d digits to the right of decimal point. (ex., numeric(3,1),
allows 44.5 to be stores exactly, but not 444.5 or 0.32)
► real, double precision. Floating point and double-precision floating
point numbers, with machine-dependent precision.
► float(n). Floating point number, with user-specified precision of at
least n digits.
SQL
DDL Commands
► DDL or Data Definition Language actually consists of the SQL
commands that can be used to define the database schema.
► It simply deals with descriptions of the database schema and is used to
create and modify the structure of database objects in the database.
► Examples of DDL commands:
► CREATE – is used to create the database or its objects (like table, index, function,
views, store procedure and triggers).
► DROP – is used to delete objects from the database.
► ALTER-is used to alter the structure of the database.
► TRUNCATE–is used to remove all records from a table, including all spaces
allocated for the records are removed.
► RENAME –is used to rename an object existing in the database.
SQL | CREATE

► There are two CREATE statements available in SQL:


► CREATE DATABASE
► CREATE TABLE
CREATE DATABASE
► A Database is defined as a structured set of data. So, in SQL the very
first step to store the data in a well structured manner is to create a
database.
► The CREATE DATABASE statement is used to create a new database in
SQL.
► Syntax:
► CREATE DATABASE database_name;
► database_name: name of the database.
► Example
► CREATE DATABASE university;
CREATE TABLE
► An SQL relation is defined using the create table command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
► r is the name of the relation
► each Ai is an attribute name in the schema of relation r
► Di is the data type of values in the domain of attribute Ai
► Example:

create table instructor (


ID char(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2));
Integrity Constraints in Create Table

► Types of Integrity Constraints in DBMS

► Entity Integrity Constraints


► Referential Integrity Constraints
► Domain Constraints
Integrity Constraints in Create Table

► primary key (A1, ..., An )


► The attributes required to be non null and unique
► foreign key (Am, ..., An ) references s
► The values of the attributes (Am, ..., An ) for any tuple in the relation must
correspond to values of the primary key attributes of some tuple in relation s.
► not null
► Specifies that the null value is not allowed for that attribute
Schema Diagram for University Database
Create Table Example
► create table instructor (
ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
primary key (ID),
foreign key (dept_name) references
department);
Create Table Example

► create table student (


ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department);
Create Table Example
► create table takes (
ID varchar(5),
course_id varchar(8),
sec_id varchar(8),
semester varchar(6),
year numeric(4,0),
grade varchar(2),
primary key (ID, course_id, sec_id, semester, year) ,
foreign key (ID) references student,
foreign key (course_id, sec_id, semester, year) references section);
Create Table Example
► create table course (
course_id varchar(8),
title varchar(50),
dept_name varchar(20),
credits numeric(2,0),
primary key (course_id),
foreign key (dept_name) references department);
SQL | DROP, TRUNCATE
► DROP is used to delete a whole database or just a table.
► The DROP statement destroys the objects like an existing database,
table, index, or view.
► A DROP statement in SQL removes a component from a relational
database management system (RDBMS).
► Syntax
► DROP object object_name
► Examples:
► DROP TABLE table_name;
► table_name: Name of the table to be deleted.
► DROP DATABASE database_name;
► database_name: Name of the database to be deleted.
SQL | DROP, TRUNCATE
► TRUNCATE statement is a Data Definition Language (DDL) operation
that is used to mark the extents of a table for deallocation (empty for
reuse).
► The result of this operation quickly removes all data from a table
► Syntax:
► TRUNCATE TABLE table_name;
► table_name: Name of the table to be truncated.
► Truncate is normally ultra-fast and its ideal for deleting data from a
temporary table.
► Truncate preserves the structure of the table for future use, unlike drop
table where the table is deleted with its full structure.
► Table or Database deletion using DROP statement cannot be rolled
back, so it must be used wisely.
SQL | DROP, TRUNCATE

TRUNCATE user
SQL | ALTER (ADD, DROP, MODIFY)
► ALTER TABLE is used to add, delete/drop or modify columns in the
existing table.
► It is also used to add and drop various constraints on the existing
table.
► ALTER TABLE – ADD
► ADD is used to add columns into the existing table.
► Sometimes we may require to add additional information, in that case we do not
require to create the whole database again, ADD comes to our rescue.
► Syntax
ALTER TABLE table_name
ADD (Columnname_1 datatype,
Columnname_2 datatype,

Columnname_n datatype);
SQL | ALTER (ADD, DROP, MODIFY)
ROLL_NO NAME

1 Ram

2 Abhi To ADD 2 columns AGE and COURSE to table Student.


3 Rahul

4 Tanu

ALTER TABLE Student ADD (AGE number(3),COURSE


varchar(40));
ROLL_NO NAME AGE COURSE

1 Ram

2 Abhi

3 Rahul

4 Tanu
SQL | ALTER (ADD, DROP, MODIFY)
► ALTER TABLE – DROP

► DROP COLUMN is used to drop column in a table. Deleting the unwanted


columns from the table.
► Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
SQL | ALTER (ADD, DROP, MODIFY)
ROLL_NO NAME AGE COURSE

1 Ram

2 Abhi

3 Rahul

4 Tanu

► ALTER TABLE Student DROP COLUMN COURSE;


ROLL_NO NAME AGE

1 Ram

2 Abhi

3 Rahul

4 Tanu
SQL | ALTER (ADD, DROP, MODIFY)
► ALTER TABLE-MODIFY
► It is used to modify the existing columns in a table. Multiple columns can also be
modified at once.
► Syntax may vary slightly in different databases.
► Syntax(Oracle,MySQL,MariaDB):
ALTER TABLE table_name
MODIFY column_name column_type;
► Syntax(SQL Server):
ALTER TABLE table_name
ALTER COLUMN column_name column_type;
► Example
ALTER TABLE Student MODIFY COURSE varchar(20);
SQL | ALTER (RENAME)
► Sometimes we may want to rename our table to give it a more
relevant name.
► For this purpose we can use ALTER TABLE to rename the name of
table.

► Syntax may vary in different databases.


► Syntax(Oracle,MySQL,MariaDB):
► ALTER TABLE table_name
► RENAME TO new_table_name;
► Columns can be also be given new name with the use of ALTER
TABLE.
► Syntax(MySQL, Oracle):
► ALTER TABLE table_name
► RENAME COLUMN old_name TO new_name;
Data Manipulation Language
► DML stands for Data Manipulation Language.
► It is a language used for selecting, inserting, deleting and updating
data in a database.
► It is used to retrieve and manipulate data in a relational database.

► There are three basic constructs which allow database program and
user to enter data and information are:
► INSERT
► UPDATE
► DELETE
Data Manipulation Language
► DML stands for Data Manipulation Language.
► It is a language used for selecting, inserting, deleting and updating
data in a database.
► It is used to retrieve and manipulate data in a relational database.

► There are three basic constructs which allow database program and
user to enter data and information are:
► INSERT
► UPDATE
► DELETE
SQL | INSERT

► The INSERT INTO statement is used to insert new records in a


table.
► It is possible to write the INSERT INTO statement in two ways:
► Specify both the column names and the values to be inserted:
► Syntax :
► INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);
► If you are adding values for all the columns of the table, you do not need to specify
the column names in the SQL query.
► Make sure that the order of the values is in the same order as the columns in the
table.
► Syntax
► INSERT INTO table_name VALUES (value1, value2, value3, ...);
SQL | INSERT | Example
CustomerID CustomerName ContactName Address City PostalCode Country
White Clover 305 - 14th Ave. S.
89 Karl Jablonski Seattle 98128 USA
Markets Suite 3B
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

► INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

CustomerID CustomerName ContactName Address City PostalCode Country


White Clover 305 - 14th Ave. S.
89 Karl Jablonski Seattle 98128 USA
Markets Suite 3B
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 Cardinal Tom B. Erichsen Skagen 21 Stavanger 4006 Norway
SQL | INSERT
► Insert Data Only in Specified Columns
► It is also possible to only insert data in specific columns.
► Syntax
► INSERT INTO Customers (CustomerName, City, Country) VALUES ('Cardinal', 'Stavanger',
'Norway');
► The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country


White Clover 305 - 14th Ave. S.
89 Karl Jablonski Seattle 98128 USA
Markets Suite 3B
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 Cardinal null null Stavanger null Norway
SQL | INSERT
► To insert multiple rows in a table using Single SQL Statement
INSERT INTO table_name(Column1,Column2,Column3,.......)
VALUES (Value1, Value2,Value3,.....),
(Value1, Value2,Value3,.....),
(Value1, Value2,Value3,.....),
............................. ;
► Example
INSERT INTO STUDENT(ID, NAME,AGE,GRADE,CITY)
VALUES(1,"AMIT KUMAR",15,10,"DELHI"),
(2,"GAURI RAO",18,12,"BANGALORE"),
(3,"MANAV BHATT",17,11,"NEW DELHI"),
(4,"RIYA KAPOOR",10,5,"UDAIPUR");
SQL | UPDATE
► The UPDATE statement in SQL is used to update the data of an existing
table in database.
► We can update single columns as well as multiple columns using
UPDATE statement as per our requirement.
► Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
► Note: The WHERE clause specifies which record(s) that should be updated. If you omit
the WHERE clause, all records in the table will be updated!
SQL | UPDATE | Example
CustomerID CustomerName ContactName Address City PostalCode Country
Alfreds
1 Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds
5 Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
SQL | UPDATE | Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
CustomerID CustomerName ContactName Address City PostalCode Country
Alfreds
1 Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds
5 Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp
SQL | UPDATE
► UPDATE Multiple Records
► It is the WHERE clause that determines how many records will be updated.
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
CustomerID CustomerName ContactName Address City PostalCode Country
Alfreds
1 Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Juan México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Juan Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds
5 Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp
SQL | UPDATE
► If you omit the WHERE clause, ALL records will be updated!
UPDATE Customers
SET ContactName='Juan';

CustomerID CustomerName ContactName Address City PostalCode Country


Alfreds
1 Juan Obere Str. 57 Frankfurt 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Juan México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Juan Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Juan 120 Hanover Sq. London WA1 1DP UK
Berglunds
5 Juan Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp
SQL | DELETE
► The DELETE Statement in SQL is used to delete existing records from a
table.
► We can delete a single record or multiple records depending on the
condition we specify in the WHERE clause.
► Syntax
► DELETE FROM table_name WHERE condition;
► The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all
records in the table will be deleted!
SQL | DELETE | Example
CustomerID CustomerName ContactName Address City PostalCode Country
Alfreds
1 Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería

► DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';


CustomerID CustomerName ContactName Address City PostalCode Country
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
SQL | DELETE
► Delete All Records
► It is possible to delete all rows in a table without deleting the table. This means
that the table structure, attributes, and indexes will be intact:
► Syntax
► DELETE FROM table_name;
► Example
► DELETE FROM customers;
References
► [Link]
► [Link]
► [Link]

You might also like