0% found this document useful (0 votes)
201 views79 pages

Uit 1 & Unit 2 Notes

DBMS is a collection of data that is organized and stored efficiently to allow for data retrieval, insertion, and deletion. It provides abstraction of data, meaning it hides the physical representation of data and provides users with an abstract view. Some advantages of DBMS include reduced data redundancy, data consistency even with concurrent access, backup and recovery capabilities, and support for multiple users. Popular examples of DBMS include MySQL, Oracle, SQL Server, and IBM DB2. DBMS is widely used in applications such as banking, telecom, sales, education, and more.

Uploaded by

Sakshi Raj
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)
201 views79 pages

Uit 1 & Unit 2 Notes

DBMS is a collection of data that is organized and stored efficiently to allow for data retrieval, insertion, and deletion. It provides abstraction of data, meaning it hides the physical representation of data and provides users with an abstract view. Some advantages of DBMS include reduced data redundancy, data consistency even with concurrent access, backup and recovery capabilities, and support for multiple users. Popular examples of DBMS include MySQL, Oracle, SQL Server, and IBM DB2. DBMS is widely used in applications such as banking, telecom, sales, education, and more.

Uploaded by

Sakshi Raj
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/ 79

UNIT -I

INTRODUCTION TO DBMS:

What is data?
 Data is nothing but facts and statistics stored or free flowing over a network, generally
it's raw and unprocessed.
 Data becomes information when it is processed, turning it into something meaningful.
 What is database: The database is a collection of inter-related data which is used to
retrieve, insert and delete the data efficiently.
 It is also used to organize the data in the form of a table, schema, views, and reports,
etc.
 Using the database, you can easily retrieve, insert, and delete the information.
 For example: The college Database organizes the data about the admin, staff, students
and faculty etc.

What is dbms?

DBMS File System

DBMS is a collection of data. In DBMS, the File system is a collection of data. In this system, the
user is not required to write the procedures. user has to write the procedures for managing the
database.

Searching data is easy in Dbms Searching is difficult in File System

Dbms is structured data Files are unstructured data

No data redundancy in Dbms Data redundancy is there in file system

Memory utilisation well in dbms Memory utilisation poor in file system

No data inconsistency in dbms Inconsistency in file system

DATABASE MANAGEMENT SYSTEMS Page 6


DBMS gives an abstract view of data that hides File system provides the detail of the data
the details. representation and storage of data.

DBMS provides a crash recovery mechanism, File system doesn't have a crash mechanism, i.e., if
i.e., DBMS protects the user from the system the system crashes while entering some data, then the
failure. content of the file will lost.

DBMS provides a good protection mechanism. It is very difficult to protect a file under the file
system.

DBMS contains a wide variety of sophisticated File system can't efficiently store and retrieve the
techniques to store and retrieve the data. data.

DBMS takes care of Concurrent access of data In the File system, concurrent access has many
using some form of locking. problems like redirecting the file while other deleting
some information or updating some information.

 A DBMS is software that allows creation, definition and manipulation of database,


allowing users to store, process and analyse data easily.
 DBMS provides us with an interface or a tool, to perform various operations like
creating database, storing data in it, updating data, creating tables in the database and
a lot more.
 DBMS also provides protection and security to the databases.
 It also maintains data consistency in case of multiple users.
Here are some examples of popular DBMS used these days:
 MySql
 Oracle
 SQL Server
 IBM DB2
DATABASE APPLICATIONS – DBMS:
 Applications where we use Database Management Systems are:
 Telecom: There is a database to keeps track of the information regarding calls made,
network usage, customer details etc.

DATABASE MANAGEMENT SYSTEMS Page 7


 Industry: Where it is a manufacturing unit, warehouse or distribution centre, each one
needs a database to keep the records of ins and outs
 Banking System: For storing customer info, tracking day to day credit and debit
transactions, generating bank statements etc.
 Sales: To store customer information, production information and invoice details.
 Airlines: To travel though airlines, we make early reservations; this reservation
information along with flight schedule is stored in database.
 Education sector: Database systems are frequently used in schools and colleges to
store and retrieve the data regarding student details, staff details, course details, exam
details, payroll data, attendance details, fees details etc.

PURPOSE OF DATABASE SYSTEMS

 The main purpose of database systems is to manage the data. Consider a university
that keeps the data of students, teachers, courses, books etc. To manage this data we
need to store this data somewhere where we can add new data, delete unused data,
update outdated data, retrieve data, to perform these operations on data we need a
Database management system that allows us to store the data in such a way so that all
these operations can be performed on the data efficiently.
Characteristics of DBMS
 Data stored into Tables: Data is never directly stored into the database. Data is stored
into tables, created inside the database.
 Reduced Redundancy: In the modern world hard drives are very cheap, but earlier
when hard drives were too expensive, unnecessary repetition of data in database was a
big problem. But DBMS follows Normalisation which divides the data in such a way
that repetition is minimum.
 Data Consistency: On Live data, i.e. data that is being continuosly updated and added,
maintaining the consistency of data can become a challenge. But DBMS handles it all
by itself.
 Support Multiple user and Concurrent Access: DBMS allows multiple users to work
on it(update, insert, delete data) at the same time and still manages to maintain the
data consistency.

DATABASE MANAGEMENT SYSTEMS Page 8


 Query Language: DBMS provides users with a simple Query language, using which
data can be easily fetched, inserted, deleted and updated in a database.

Advantages of DBMS

 Controls database redundancy: It can control data redundancy because it stores all the
data in one single database file and that recorded data is placed in the database.
 Data sharing: In DBMS, the authorized users of an organization can share the data
among multiple users.
 Easily Maintenance: It can be easily maintainable due to the centralized nature of the
database system.
 Reduce time: It reduces development time and maintenance need.
 Backup: It provides backup and recovery subsystems which create automatic backup
of data from hardware and software failures and restores the data if required.
 multiple user interface: It provides different types of user interfaces like graphical
user interfaces, application program interfaces

Disadvantages of DBMS

 Cost of Hardware and Software: It requires a high speed of data processor and large
memory size to run DBMS software.
 Size: It occupies a large space of disks and large memory to run them efficiently.
 Complexity: Database system creates additional complexity and requirements.
 Higher impact of failure: Failure is highly impacted the database because in most of
the organization, all the data stored in a single database and if the database is damaged
due to electric failure or database corruption then the data may be lost forever.

View of Data in DBMS


 Abstraction is one of the main features of database systems.
 Hiding irrelevant details from user and providing abstract view of data to users, helps
in easy and efficient user-database interaction.
 the three level of DBMS architecture, The top level of that architecture is “view
level”. The view level provides the “view of data” to the users and hides the irrelevant

DATABASE MANAGEMENT SYSTEMS Page 9


details such as data relationship, database schema, constraints, security etc from the
user.

Data Abstraction in DBMS

Database systems are made-up of complex data structures. To ease the user interaction with
database, the developers hide internal irrelevant details from users. This process of hiding
irrelevant details from user is called data abstraction.

We have three levels of abstraction:


Physical level: This is the lowest level of data abstraction. It describes how data is actually
stored in database. You can get the complex data structure details at this level.

Logical level: This is the middle level of 3-level data abstraction architecture. It describes
what data is stored in database.

View level: Highest level of data abstraction. This level describes the user interaction with
database system.
Instance and schema in DBMS

 Definition of schema: Design of a database is called the schema. Schema is of three


types: Physical schema, logical schema and view schema.

DATABASE MANAGEMENT SYSTEMS Page 10


 The design of a database at physical level is called physical schema, how the data
stored in blocks of storage is described at this level.
 Design of database at logical level is called logical schema, programmers and
database administrators work at this level, at this level data can be described as certain
types of data records gets stored in data structures, however the internal details such
as implementation of data structure is hidden at this level (available at physical level).
 Design of database at view level is called view schema. This generally describes end
user interaction with database systems.

Definition of instance:
The data stored in database at a particular moment of time is called instance of
database. Database schema defines the variable declarations in tables that belong to a
particular database; the value of these variables at a moment of time is called the instance of
that database.

DBMS ARCHITECTURE:
 Database management systems architecture will help us understand the components of
database system and the relation among them.
 The architecture of DBMS depends on the computer system on which it runs.
 the basic client/server architecture is used to deal with a large number of PCs, web
servers, database servers and other components that are connected with networks.
 The client/server architecture consists of many PCs and a workstation which are
connected via the network.
 DBMS architecture depends upon how users are connected to the database to get their
request done.

TYPES OF DBMS ARCHITECTURE

There are three types of DBMS architecture:


1. Single tier architecture
2. Two tier architecture
3.Three tier architecture

DATABASE MANAGEMENT SYSTEMS Page 11


1-Tier Architecture
 In this type of architecture, the database is readily available on the client machine, any
request made by client doesn’t require a network connection to perform the action on
the database.
 Any changes done here will directly be done on the database itself. It doesn't provide
a handy tool for end users.
 The 1-Tier architecture is used for development of the local application, where
programmers can directly communicate with the database for the quick response.

2. Two tier architecture


 In two-tier architecture, the Database system is present at the server machine and the
DBMS application is present at the client machine, these two machines are connected
with each other through a reliable network.
 Whenever client machine makes a request to access the database present at server
using a query language like sql, the server perform the request on the database and
returns the result back to the client.
 The application connection interface such as JDBC, ODBC are used for the
interaction between server and client.

3-Tier Architecture
 In three-tier architecture, another layer is present between the client machine and
server machine.
 In this architecture, the client application doesn’t communicate directly with the
database systems present at the server machine, rather the client application

DATABASE MANAGEMENT SYSTEMS Page 12


communicates with server application and the server application internally
communicates with the database system present at the server.

DATA MODELS:
 Data Model is the modeling of the data description, data semantics, and consistency
constraints of the data.
 It provides the conceptual tools for describing the design of a database at each level of
data abstraction.
 Therefore, there are following four data models used for understanding the structure
of the database:

Four Types of DBMS systems are:

 Hierarchical database
 Network database
 Relational database
 ER model database

Hierarchical DBMS
In a Hierarchical database, model data is organized in a tree-like structure. Data is Stored
Hierarchically (top down or bottom up) format. Data is represented using a parent-child

DATABASE MANAGEMENT SYSTEMS Page 13


relationship. In Hierarchical DBMS parent may have many children, but children have only
one parent.

Network Model
The network database model allows each child to have multiple parents. It helps you to
address the need to model more complex relationships like as the orders/parts many-to-many
relationship. In this model, entities are organized in a graph which can be accessed through
several paths.

Relational model
Relational DBMS is the most widely used DBMS model because it is one of the easiest. This
model is based on normalizing data in the rows and columns of the tables. Relational model
stored in fixed structures and manipulated using SQL.

Entity-Relationship Model
Entity-Relationship (ER) Model is based on the notion of real-world entities and relationships
among them. While formulating real-world scenario into the database model, the ER Model
creates entity set, relationship set, general attributes and constraints.

DATABASE MANAGEMENT SYSTEMS Page 14


DBMS languages

Database languages are used to read, update and store data in a database. There are several
such languages that can be used for this purpose; one of them is SQL (Structured Query
Language).

 DDL – Data Definition Language:


(CREATE,DROP,ALTER,TRUNCATE,COMMENT,RENAME)
 DML – Data Manipulation Language: (INSERT, UPDATE,DELETE)
 DCL – Data Control Language: (GRANT,REVOKE)
 TCL-Transaction Control Language: (COMMIT,ROLLBACK)

1. DDL(Data Definition Language) : 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.
CREATE – it is used to create the database or its objects (like table, index, function, views,
store procedure and triggers).
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 MANAGEMENT SYSTEMS Page 15


Example:
SQL> CREATE DATABASE Employee;
In order to get the list of all the databases, you can use SHOW DATABASES statement.
Example –
SQL> SHOW DATABASES;

CREATE TABLE:
The CREATE TABLE statement is used to create a table in SQL. We know that a table
comprises of rows and columns. So while creating tables we have to provide all the
information to SQL about the names of the columns, type of data to be stored in columns,
size of the data etc. Let us now dive into details on how to use CREATE TABLE statement to
create tables in SQL.
Syntax:
CREATE TABLE table_name
(
column1 data_type(size),
column2 data_type(size),
column3 data_type(size),
....
);
Example Query:
This query will create a table named Students with three columns, ROLL_NO, NAME and
SUBJECT.
CREATE TABLE Students
(
ROLL_NO int(3),
NAME varchar(20),
SUBJECT varchar(20),
);

DROP:
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.

DATABASE MANAGEMENT SYSTEMS Page 16


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.
TRUNCATE
It is used to remove all records from a table, including all spaces
The TRUNCATE TABLE mytable statement is logically (though not physically) equivalent
to the DELETE FROM mytable statement (without a WHERE clause).
Syntax:
TRUNCATE TABLE table_name;
DROP vs TRUNCATE
 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.

To delete the whole database


DROP DATABASE student_data;
After running the above query whole database will be deleted.
To truncate Student_details table from student_data database.
TRUNCATE TABLE Student_details;
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:

DATABASE MANAGEMENT SYSTEMS Page 17


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);

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;
ALTER TABLE-MODIFY
It is used to modify the existing columns in a table. Multiple columns can also be modified at
once.
ALTER TABLE table_name
MODIFY column_name column_type;
QUERY:
To ADD 2 columns AGE and COURSE to table Student.
ALTER TABLE Student ADD (AGE number(3),COURSE varchar(40));
MODIFY column COURSE in table Student
ALTER TABLE Student MODIFY COURSE varchar(20);
Comments
As is any programming languages comments matter a lot in SQL also. In this set we will
learn about writing comments in any SQL snippet.
Comments can be written in the following three formats:
 Single line comments.
 Multi line comments
 In line comments

DATABASE MANAGEMENT SYSTEMS Page 18


DML(Data Manipulation Language) : The SQL commands that deals with the
manipulation of data present in the database belong to DML or Data Manipulation Language
and this includes most of the SQL statements.
SELECT Statement
select statement is used to fetch data from relational database. A relational database is
organized collection of data. As we know that data is stored inside tables in a database. SQL
select statement or SQL select query is used to fetch data from one or more than one tables.

SELECT Syntax
One column:
Here column_name is the name of the column for which we need to fetch data and
table_name is the name of the table in the database.
SELECT column_name FROM table_name;
More than one columns:
SELECT column_name_1, column_name_2, ... FROM table_name;
To fetch the entire table or all the fields in the table:
SELECT * FROM table_name;
Example:
SELECT EMP_NAME FROM EMPLOYEES;
To fetch the entire EMPLOYEES table:
SELECT * FROM EMPLOYEES;
Query to fetch the fields ROLL_NO, NAME, AGE from the table Student:
SELECT ROLL_NO, NAME, AGE FROM Student;
INSERT INTO Statement
The INSERT INTO statement of SQL is used to insert a new row in a table. There are two
ways of using INSERT INTO statement for inserting rows:
Only values: First method is to specify only the value of data to be inserted without the
column names.

INSERT INTO table_name VALUES (value1, value2, value3,…);

Column names and values both: In the second method we will specify both the columns
which we want to fill and their corresponding values as shown below:

DATABASE MANAGEMENT SYSTEMS Page 19


INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1, value2,
value3,..);
Example:
Method 1 (Inserting only values) :
INSERT INTO Student VALUES (‘5′,’HARSH’,’WEST
BENGAL’,’XXXXXXXXXX’,’19’);
Method 2 (Inserting values in only specified columns):
INSERT INTO Student (ROLL_NO, NAME, Age) VALUES (‘5′,’PRATIK’,’19’);
UPDATE Statement
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.
Basic Syntax:
UPDATE TableName
SET column_name1 = value, column_name2 = value....
WHERE condition;
EX1:
SQL> UPDATE EMPLOYEES
SET EMP_SALARY = 10000
WHERE EMP_AGE > 25;

EX2;
SQL> UPDATE EMPLOYEES
SET EMP_SALARY = 120000
WHERE EMP_NAME = 'Apoorv';
DELETE Statement
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.
Basic Syntax:
DELETE FROM table_name WHERE some_condition;
Deleting single record: Delete the rows where NAME = ‘Ram’. This will delete only the first
row.
DELETE FROM Student WHERE NAME = 'Ram';

DATABASE MANAGEMENT SYSTEMS Page 20


Deleting multiple records: Delete the rows from the table Student where Age is 20. This will
delete 2 rows(third row and fifth row).
DELETE FROM Student WHERE Age = 20;
Delete all of the records: There are two queries to do this as shown below,
query1: "DELETE FROM Student";
query2: "DELETE * FROM Student";
DCL(Data Control Language) : DCL includes commands such as GRANT and REVOKE
which mainly deals with the rights, permissions and other controls of the database system.
Examples of DCL commands:
GRANT-gives user’s access privileges to database.
REVOKE-withdraw user’s access privileges given by using the GRANT command.

TCL(transaction Control Language) : TCL commands deals with the transaction within the
database.
Examples of TCL commands:
COMMIT– commits a Transaction.
ROLLBACK– rollbacks a transaction in case of any error occurs.
SAVEPOINT–sets a savepoint within a transaction.
SET TRANSACTION–specify characteristics for the transaction.

What is the Procedure for Database Access?


 Any access to the stored data is done by the data manager. A user’s request for data
is-received by the data manager, which detern1ines the physical record required. The
decision as 10 which physical record is needed may require some preliminary
consultation of the database and/or the data dictionary prior to the access of the actual
data itself.
 The data manager sends the request for a specific physical record to the file manager.
The file manager decides which physical block of secondary storage devices contains
the required record and sends the request for the appropriate block to the disk
manager. A block is a unit of physical input/output operations between primary and
secondary storage. The disk manager retrieves the block and sends it to the file
manager, which sends the required record to the data manager.

DATABASE MANAGEMENT SYSTEMS Page 21


DATA BASE USERS AND ADMINISTRATORS:
Database users are the persons who interact with the database and take the benefits of
database.
They are differentiated into different types based on the way they expect to interact with the
system.
Naive users: They are the unsophisticated users who interact with the system by using
permanent applications that already exist. Example: Online Library Management System,
ATMs (Automated Teller Machine), etc.
Application programmers: They are the computer professionals who interact with system
through DML. They write application programs.
Sophisticated users: They interact with the system by writing SQL queries directly through
the query processor without writing application programs.
Specialized users: They are also sophisticated users who write specialized database
applications that do not fit into the traditional data processing framework. Example: Expert
System, Knowledge Based System, etc.

Database Administrators

The life cycle of database starts from designing, implementing to administration of it. A
database for any kind of requirement needs to be designed perfectly so that it should work
without any issues. Once all the design is complete, it needs to be installed. Once this step is
complete, users start using the database. The database grows as the data grows in the
database. When the database becomes huge, its performance comes down. Also accessing the
data from the database becomes challenge. There will be unused memory in database, making
the memory inevitably huge. These administration and maintenance of database is taken care

DATABASE MANAGEMENT SYSTEMS Page 22


by database Administrator – DBA.
A DBA has many responsibilities. A good performing database is in the hands of DBA.
Database Administrators coordinate all the activities of the database system. They have all
the permissions.

Tasks of DBA

 Creatingtheschema
 Specifying integrity constraints
 Storage structure and access method definition
 Granting permission to other users.
 Monitoring performance
 Routine Maintenance

Transaction Management?

 A Database Transaction is a logical unit of processing in a DBMS which entails one


or more database access operation. In a nutshell, database transactions represent real-
world events of any enterprise.
 All types of database access operation which are held between the beginning and end
transaction statements are considered as a single logical transaction in DBMS. During
the transaction the database is inconsistent. Only once the database is committed the
state is changed from one consistent state to another.

What are ACID Properties?

ACID Properties are used for maintaining the integrity of database during transaction
processing. ACID in DBMS stands for Atomicity, Consistency, Isolation, and Durability.
 Atomicity: A transaction is a single unit of operation. You either execute it entirely or
do not execute it at all. There cannot be partial execution.
 Consistency: Once the transaction is executed, it should move from one consistent
state to another.

DATABASE MANAGEMENT SYSTEMS Page 23


 Isolation: Transaction should be executed in isolation from other transactions (no
Locks). During concurrent transaction execution, intermediate transaction results from
simultaneously executed transactions should not be made available to each other.
(Level 0,1,2,3)
 Durability: · After successful completion of a transaction, the changes in the
database should persist. Even in the case of system failures.

Storage Manager In DBMS


 A storage manager is a program module that provides the interface between the
lowlevel data stored in the database and the application programs and queries
submitted to the system.
 The storage manager is responsible for the interaction with the file manager.
 The raw data are stored on the disk using the file system, which is usually provided by
a conventional operating system.
 The storage manager translates the various DML statements into low-level file-system
commands. Thus, the storage manager is responsible for storing, retrieving, and
updating data in the database.
The storage manager components include:
1. Authorization and integrity manager, which tests for the satisfaction of integrity constraints
and checks the authority of users to access data.
2. Transaction manager, which ensures that the database remains in a consistent (correct)
state despite system failures, and that concurrent transaction executions proceed without
conflicting.
3. File manager, which manages the allocation of space on disk storage and the data
structures used to represent information stored on disk.
4. Buffer manager, which is responsible for fetching data from disk storage into main
memory, and deciding what data to cache in main memory. The buffer manager is a critical
part of the database system, since it enables the database to handle data sizes that are much
larger than the size of main memory.The storage manager implements several data structures
as part of the physical system implementation:

DATABASE MANAGEMENT SYSTEMS Page 24


Query Processing in DBMS

A query processor is one of the major components of a relational database or an electronic


database in which data is stored in tables of rows and columns. It complements the storage
engine, which writes and reads data to and from storage media.

Parsing and Translation

As query processing includes certain activities for data retrieval. Initially, the given user
queries get translated in high-level database languages such as SQL. It gets translated into
expressions that can be further used at the physical level of the file system. After this, the
actual evaluation of the queries and a variety of query -optimizing transformations and takes
place.

Query Evaluation Plan


o In order to fully evaluate a query, the system needs to construct a query evaluation
plan.
o The annotations in the evaluation plan may refer to the algorithms to be used for the
particular index or the specific operations.
o Such relational algebra with annotations is referred to as Evaluation Primitives. The
evaluation primitives carry the instructions needed for the evaluation of the operation.

DATABASE MANAGEMENT SYSTEMS Page 25


o Thus, a query evaluation plan defines a sequence of primitive operations used for
evaluating a query. The query evaluation plan is also referred to as the query
execution plan.

o A query execution engine is responsible for generating the output of the given query.
It takes the query execution plan, executes it, and finally makes the output for the user
query.

Optimization
o The cost of the query evaluation can vary for different types of queries. Although the
system is responsible for constructing the evaluation plan, the user does need not to
write their query efficiently.
o Usually, a database system generates an efficient query evaluation plan, which
minimizes its cost. This type of task performed by the database system and is known
as Query Optimization.
o For optimizing a query, the query optimizer should have an estimated cost analysis of
each operation. It is because the overall operation cost depends on the memory
allocations to several operations, execution costs, and so on.

What is Relational Model?

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.

The table name and column names are helpful to interpret the meaning of values in each row.
The data are represented as a set of relations. In the relational model, data are stored as tables.
However, the physical storage of the data is independent of the way the data are logically
organized.

Relational Model Concepts

1. Attribute: Each column in a Table. Attributes are the properties which define a
relation. e.g., Student_Rollno, NAME,etc.

DATABASE MANAGEMENT SYSTEMS Page 26


2. Tables – In the Relational model the, relations are saved in the table format. It is
stored along with its entities. A table has two properties rows and columns. Rows
represent records and columns represent attributes.
3. Tuple – It is nothing but a single row of a table, which contains a single record.
4. Relation Schema: A relation schema represents the name of the relation with its
attributes.
5. Degree: The total number of attributes which in the relation is called the degree of the
relation.
6. Cardinality: Total number of rows present in the Table.
7. Column: The column represents the set of values for a specific attribute.
8. Relation instance – Relation instance is a finite set of tuples in the RDBMS system.
Relation instances never have duplicate tuples.
9. Relation key - Every row has one, two or multiple attributes, which is called relation
key.
10. Attribute domain – Every attribute has some pre-defined value and scope which is
known as attribute domain
Keys in DBMS
KEYS in DBMS is an attribute or set of attributes which helps you to identify a row(tuple) in
a relation(table). They allow you to find the relation between two tables. Keys help you
uniquely identify a row in a table by a combination of one or more columns in that table. Key
is also helpful for finding unique record or row from the table. Database key is also helpful
for finding unique record or row from the table.

Why we need a Key?

Here are some reasons for using sql key in the DBMS system.

 Keys help you to identify any row of data in a table. In a real-world application, a
table could contain thousands of records. Moreover, the records could be duplicated.
Keys ensure that you can uniquely identify a table record despite these challenges.
 Allows you to establish a relationship between and identify the relation between
tables
 Help you to enforce identity and integrity in the relationship.

DATABASE MANAGEMENT SYSTEMS Page 27


Types of Keys in Database Management System

There are mainly seven different types of Keys in DBMS and each key has its different
functionality:

 Super Key - A super key is a group of single or multiple keys which identifies rows
in a table.
 Primary Key - is a column or group of columns in a table that uniquely identify
every row in that table.
 Candidate Key - is a set of attributes that uniquely identify tuples in a table.
Candidate Key is a super key with no repeated attributes.
 Alternate Key - is a column or group of columns in a table that uniquely identify
every row in that table.
 Foreign Key - is a column that creates a relationship between two tables. The
purpose of Foreign keys is to maintain data integrity and allow navigation between
two different instances of an entity.
 Compound Key - has two or more attributes that allow you to uniquely recognize a
specific record. It is possible that each column may not be unique by itself within the
database.
 Composite Key - An artificial key which aims to uniquely identify each record is
called a surrogate key. These kind of key are unique because they are created when
you don't have any natural primary key.
 Surrogate Key - An artificial key which aims to uniquely identify each record is
called a surrogate key. These kind of key are unique because they are created when
you don't have any natural primary key.
Primary key example:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

DATABASE MANAGEMENT SYSTEMS Page 28


Create Primary Key (ALTER TABLE statement)

Syntax
The syntax to create a primary key using the ALTER TABLE statement in SQL is:

ALTER TABLE table_name


ADD CONSTRAINT constraint_name
PRIMARY KEY (column1, column2, ... column_n);

FOREIGN KEY on CREATE TABLE

The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders"
table is created:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

ER model
o ER model stands for an Entity-Relationship model. It is a high-level data model. This
model is used to define the data elements and relationship for a specified system.
o It develops a conceptual design for the database. It also develops a very simple and
easy to design view of data.
o In ER modeling, the database structure is portrayed as a diagram called an entity-
relationship diagram.

For example, Suppose we design a school database. In this database, the student will be an
entity with attributes like address, name, id, age, etc. The address can be another entity with
attributes like city, street name, pin code, etc and there will be a relationship between them.

DATABASE MANAGEMENT SYSTEMS Page 29


Component of ER Diagram

1. Entity:

An entity may be any object, class, person or place. In the ER diagram, an entity can be
represented as rectangles.

DATABASE MANAGEMENT SYSTEMS Page 30


Consider an organization as an example- manager, product, employee, department etc. can be
taken as an entity.

a. Weak Entity

An entity that depends on another entity called a weak entity. The weak entity doesn't contain
any key attribute of its own. The weak entity is represented by a double rectangle.

2. Attribute

The attribute is used to describe the property of an entity. Eclipse is used to represent an
attribute.

For example, id, age, contact number, name, etc. can be attributes of a student.

a. Key Attribute

The key attribute is used to represent the main characteristics of an entity. It represents a
primary key. The key attribute is represented by an ellipse with the text underlined.

DATABASE MANAGEMENT SYSTEMS Page 31


b. Composite Attribute

An attribute that composed of many other attributes is known as a composite attribute. The
composite attribute is represented by an ellipse, and those ellipses are connected with an
ellipse.

c. Multivalued Attribute

An attribute can have more than one value. These attributes are known as a multivalued
attribute. The double oval is used to represent multivalued attribute.

For example, a student can have more than one phone number.

DATABASE MANAGEMENT SYSTEMS Page 32


d. Derived Attribute

An attribute that can be derived from other attribute is known as a derived attribute. It can be
represented by a dashed ellipse.

For example, A person's age changes over time and can be derived from another attribute
like Date of birth.

3. Relationship

A relationship is used to describe the relation between entities. Diamond or rhombus is used
to represent the relationship

Types of relationship are as follows:

DATABASE MANAGEMENT SYSTEMS Page 33


a. One-to-One Relationship

When only one instance of an entity is associated with the relationship, then it is known as
one to one relationship.

For example, A female can marry to one male, and a male can marry to one female.

b. One-to-many relationship

When only one instance of the entity on the left, and more than one instance of an entity on
the right associates with the relationship then this is known as a one-to-many relationship.

For example, Scientist can invent many inventions, but the invention is done by the only
specific scientist.

c. Many-to-one relationship

When more than one instance of the entity on the left, and only one instance of an entity on
the right associates with the relationship then it is known as a many-to-one relationship.

For example, Student enrolls for only one course, but a course can have many students.

DATABASE MANAGEMENT SYSTEMS Page 34


d. Many-to-many relationship

When more than one instance of the entity on the left, and more than one instance of an entity
on the right associates with the relationship then it is known as a many-to-many relationship.

For example, Employee can assign by many projects and project can have many employees.

Notation of ER diagram

Database can be represented using the notations. In ER diagram, many notations are used to
express the cardinality. These notations are as follows:

Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of information.

o Integrity constraints ensure that the data insertion, updating, and other processes have
to be performed in such a way that data integrity is not affected.

DATABASE MANAGEMENT SYSTEMS Page 35


o Thus, integrity constraint is used to guard against accidental damage to the database.

Types of Integrity Constraint

1. Domain constraints
o Domain constraints can be defined as the definition of a valid set of values for an
attribute.

o The data type of domain includes string, character, integer, time, date, currency, etc.
The value of the attribute must be available in the corresponding domain.

Example:

2. Entity integrity constraints


o The entity integrity constraint states that primary key value can't be null.
o 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.
o A table can contain a null value other than the primary key field.

DATABASE MANAGEMENT SYSTEMS Page 36


3. Referential

Integrity Constraints
o A referential integrity constraint is specified between two tables.
o 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.

4. Key constraints
o Keys are the entity set that is used to identify an entity within its entity set uniquely.
o 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 and null value in the relational table.

DATABASE MANAGEMENT SYSTEMS Page 37


ER Design Issues
 ER design issues need to be discussed for better ER- design
 users often mislead the concept of the elements and the design process of the ER
diagram. Thus, it leads to a complex structure of the ER diagram and certain issues
that does not meet the characteristics of the real-world enterprise model.
 Here, we will discuss the basic design issues of an ER database schema in the
following points:

1) Use of Entity Set vs Attributes

The use of an entity set or attribute depends on the structure of the real-world enterprise that
is being modelled and the semantics associated with its attributes. It leads to a mistake when
the user use the primary key of an entity set as an attribute of another entity set. Instead, he
should use the relationship to do so. Also, the primary key attributes are implicit in the
relationship set, but we designate it in the relationship sets.

2) Use of Entity Set vs. Relationship Sets


It is difficult to examine if an object can be best expressed by an entity set or relationship set.

3) Use of Binary vs n-ary Relationship Sets


Generally, the relationships described in the databases are binary relationships. However,
non-binary relationships can be represented by several binary relationships.

4) Placing Relationship Attributes

The cardinality ratios can become an affective measure in the placement of the relationship
attributes. So, it is better to associate the attributes of one-to-one or one-to-many relationship
sets with any participating entity sets, instead of any relationship set.

DATABASE MANAGEMENT SYSTEMS Page 38


Conceptual design
Conceptual design is the first stage in the database design process. The goal at this stage is to
design a database that is independent of database software and physical details. The output of
this process is a conceptual data model that describes the main data entities, attributes,
relationships, and constraints of a given problem domain.
Keep in mind the following minimal data rule:

"All that is needed is there, and all that is there is needed".


1. Data analysis and requirements

2. Entity relationship modeling and normalization

3. Data model verification

4. Distributed database design

DATABASE MANAGEMENT SYSTEMS Page 39


UNIT-2

Relational Algebra
 Relational Algebra is procedural query language, which takes Relation as input and
generates relation as output. Relational algebra mainly provides theoretical
foundation for relational databases and SQL.
 Relational algebra is a procedural query language, it means that it tells what data to be
retrieved and how to be retrieved.
 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 given table to fetch
data for you.

DATABASE MANAGEMENT SYSTEMS Page 40


Basic/Fundamental Operations:

1.Select (σ)
2. Project (∏)
3. Union (∪)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)

1. Select Operation (σ) :This is used to fetch rows (tuples) from table(relation) which
satisfies a given condition.
Syntax: σp(r)

 σ is the predicate
 r stands for relation which is the name of the table
 p is prepositional logic
ex: σage > 17 (Student)
This will fetch the tuples(rows) from table Student, for which age will be greater than 17.
σage > 17 and gender = 'Male' (Student)
This will return tuples(rows) from table Student with information of male students, of age
more than 17.

BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

DATABASE MANAGEMENT SYSTEMS Page 41


Input:
σ BRANCH_NAME="perryride" (LOAN)

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

Project Operation (∏):


 Project operation is used to project only a certain set of attributes of a relation. In
simple words, If you want to see only the names all of the students in
the Student table, then you can use Project Operation.
 It will only project or show the columns or attributes asked for, and will also remove
duplicate data from the columns.
Syntax of Project Operator (∏)
∏ column_name1, column_name2, ...., column_nameN(table_name)

Example:
∏Name, Age(Student)
Above statement will show us only the Name and Age columns for all the rows of data
in Student table.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

DATABASE MANAGEMENT SYSTEMS Page 42


Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:
∏ NAME, CITY (CUSTOMER)

Output:

NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

Union Operation (∪):

 This operation is used to fetch data from two relations(tables) or temporary


relation(result of another operation).
 For this operation to work, the relations(tables) specified should have same number of
attributes(columns) and same attribute domain. Also the duplicate tuples are
autamatically eliminated from the result.
Syntax: A ∪ B
∏Student(RegularClass) ∪ ∏Student(ExtraClass)

DATABASE MANAGEMENT SYSTEMS Page 43


Example:

DEPOSITOR RELATION

CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

CUSTOMER_NAME LOAN_NO

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

DATABASE MANAGEMENT SYSTEMS Page 44


Williams L-17

Input:
∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes

Set Difference (-):


This operation is used to find data present in one relation and not present in the second
relation. This operation is also applicable on two relations, just like Union operation.
Syntax: A - B
where A and B are relations.
For example, if we want to find name of students who attend the regular class but not the
extra class, then, we can use the below operation:
∏Student(RegularClass) - ∏Student(ExtraClass)

DATABASE MANAGEMENT SYSTEMS Page 45


Input: ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)

CUSTOMER_NAME

Smith

Jones

Cartesian Product (X):

This is used to combine data from two different relations(tables) into one and fetch data from
the combined relation.
Syntax: A X B
For example, if we want to find the information for Regular Class and Extra Class which are
conducted during morning, then, we can use the following operation:
σtime = 'morning' (RegularClass X ExtraClass)
For the above query to work, both RegularClass and ExtraClass should have the
attribute time.
Notation: E X D

EMPLOYEE

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B

DATABASE MANAGEMENT SYSTEMS Page 46


DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal

Input:
EMPLOYEE X DEPARTMENT

Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

DATABASE MANAGEMENT SYSTEMS Page 47


3 John B C Legal

Rename Operation (ρ):

This operation is used to rename the output relation for any query operation which returns
result like Select, Project etc. Or to simply rename a relation(table)
Syntax: ρ(RelationNew, RelationOld)

The rename operation is used to rename the output relation. It is denoted by rho (ρ).

Example: We can use the rename operator to rename STUDENT relation to STUDENT1.
ρ(STUDENT1, STUDENT)

Join in DBMS:

 A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
 Join in DBMS is a binary operation which allows you to combine join product and
selection in one single statement.
 The goal of creating a join condition is that it helps you to combine the data from two
or more DBMS tables.
 The tables in DBMS are associated using the primary key and foreign keys.

Types of SQL JOIN


1. INNER JOIN
2. LEFT JOIN

3. RIGHT JOIN
4. FULL JOIN

Table name: EMPLOYEE

DATABASE MANAGEMENT SYSTEMS Page 48


EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

PROJECT

PROJECT_NO EMP_ID DEPARTMENT

101 1 Testing

102 2 Development

103 3 Designing

104 4 Development

1. INNER JOIN

In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied.

It returns the combination of all rows from both the tables where the condition satisfies.

DATABASE MANAGEMENT SYSTEMS Page 49


Syntax
SELECT table1.column1, table1.column2
FROM table1 INNER JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT JOIN

The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.

DATABASE MANAGEMENT SYSTEMS Page 50


Syntax
SELECT table1.column1, table1.column2 FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

3. RIGHT JOIN

DATABASE MANAGEMENT SYSTEMS Page 51


In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and
the matched values from the left table. If there is no matching in both tables, it will return
NULL.

Syntax
SELECT table1.column1, table1.column2
FROM table1 RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

DATABASE MANAGEMENT SYSTEMS Page 52


4. FULL JOIN

In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join
tables have all the records from both tables. It puts NULL on the place of matches not found.

Syntax
SELECT table1.column1, table1.column2
FROM table1 FULL JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

DATABASE MANAGEMENT SYSTEMS Page 53


Marry NULL

Division Operator in SQL


Division Operator (÷): Division operator A÷B can be applied if and only if:
 Attributes of B is proper subset of Attributes of A.
 The relation returned by division operator will have attributes = (All attributes of A –
All Attributes of B)
 The relation returned by division operator will return those tuples from relation A
which are associated to every B’s tuple.

The division operator is used when we have to evaluate queries which contain the
keyword ALL.

Table 1: Course_Taken → It consists of the names of Students against the courses that they
have taken.

Student_Name Course

Robert Databases

DATABASE MANAGEMENT SYSTEMS Page 54


Robert Programming Languages

David Databases

David Operating Systems

Hannah Programming Languages

Hannah Machine Learning

Tom Operating Systems

Table 2: Course_Required → It consists of the courses that one is required to take in order
to graduate.

Course

Databases

Programming Languages

1.Find all the students

Create a set of all students that have taken courses. This can be done easily using the
following command.

DATABASE MANAGEMENT SYSTEMS Page 55


CREATE TABLE AllStudents AS SELECT DISTINCT Student_Name FROM
Course_Taken
This command will return the table AllStudents, as the resultset:

Student_name

Robert

David

Hannah

Tom

2. Find all the students and the courses required to graduate

Next, we will create a set of students and the courses they need to graduate. We can express
this in the form of Cartesian Product of AllStudents and Course_Required using the
following command.
CREATE table StudentsAndRequired AS
SELECT AllStudents.Student_Name, Course_Required.Course
FROM AllStudents, Course_Required
Now the new resultset - table StudentsAndRequired will be:

DATABASE MANAGEMENT SYSTEMS Page 56


Student_Name Course

Robert Databases

Robert Programming Languages

David Databases

David Programming Languages

Hannah Databases

Hannah Programming Languages

Tom Databases

Tom Programming Languages

Relational Calculus:

Relational calculus is a non-procedural query language that tells the system what data to be
retrieved but doesn’t tell how to retrieve it. Relational Calculus exists in two forms:

1. Tuple Relational Calculus (TRC)


2. Domain Relational Calculus (DRC)
Tuple Relational Calculus (TRC)

DATABASE MANAGEMENT SYSTEMS Page 57


Tuple relational calculus is used for selecting those tuples that satisfy the given condition.
Table: Student

First_Name Last_Name Age


---------- --------- ----
Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28
Lets write relational calculus queries.
Query to display the last name of those students where age is greater than 30
{ t.Last_Name | Student(t) AND t.age > 30 }

In the above query you can see two parts separated by | symbol. The second part is where we
define the condition and in the first part we specify the fields which we want to display for
the selected tuples.
The result of the above query would be:
Last_Name
---------
Singh
Query to display all the details of students where Last name is ‘Singh’
{ t | Student(t) AND t.Last_Name = 'Singh' }

Output:
First_Name Last_Name Age
---------- --------- ----
Ajeet Singh 30
Chaitanya Singh 31

Ex:
Table-1: Customer

DATABASE MANAGEMENT SYSTEMS Page 58


Customer name Street City

Saurabh A7 Patiala

Mehak B6 Jalandhar

Sumiti D9 Ludhiana

Ria A5 Patiala

Table-2: Branch

Branch name Branch city

ABC Patiala

DEF Ludhiana

GHI Jalandhar

Table-3: Account

Account number Branch name Balance

1111 ABC 50000

1112 DEF 10000

1113 GHI 9000

DATABASE MANAGEMENT SYSTEMS Page 59


Account number Branch name Balance

1114 ABC 7000

Table-4: Loan

Loan number Branch name Amount

L33 ABC 10000

L35 DEF 15000

L49 GHI 9000

L98 DEF 65000

Table-5: Borrower

Customer name Loan number

Saurabh L33

Mehak L49

Ria L98

Table-6: Depositor

Customer name Account number

Saurabh 1111

DATABASE MANAGEMENT SYSTEMS Page 60


Customer name Account number

Mehak 1113

Sumiti 1114

Queries-1: Find the loan number, branch, amount of loans of greater than or equal to
10000 amount.

{t| t ∈ loan ∧ t[amount]>=10000}


Resulting relation:

Loan number Branch name Amount

L33 ABC 10000

L35 DEF 15000

L98 DEF 65000

Domain Relational Calculus (DRC)


In domain relational calculus the records are filtered based on the domains.
Again we take the same table to understand how DRC works.
Table: Student
First_Name Last_Name Age
---------- --------- ----
Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28
Query to find the first name and age of students where student age is greater than 27
{< First_Name, Age > | ∈ Student ∧ Age > 27}

DATABASE MANAGEMENT SYSTEMS Page 61


Note:
The symbols used for logical operators are: ∧ for AND, ∨ for OR and ┓ for NOT.
Output:
First_Name Age
---------- ----
Ajeet 30
Chaitanya 31
Carl 28

SQL Basic Structure

1. Basic structure of an SQL expression consists of select, from and where clauses.
o select clause lists attributes to be copied - corresponds to relational
algebra project.
o from clause corresponds to Cartesian product - lists relations to be used.
o where clause corresponds to selection predicate in relational algebra.

The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.


To fetch the entire table or all the fields in the table:
SELECT * FROM table_name;
To fetch individual column data
SELECT column1,column2 FROM table_name

WHERE SQL clause

WHERE clause is used to specify/apply any condition while retrieving, updating or deleting
data from a table. This clause is used mostly with SELECT, UPDATE and DELETEquery.

The basic syntax of the SELECT statement with the WHERE clause is as shown below.
SELECT column1, column2, columnN
FROM table_name

DATABASE MANAGEMENT SYSTEMS Page 62


WHERE [condition]

Example

Consider the CUSTOMERS table having the following records −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

The following code is an example which would fetch the ID, Name and Salary fields from
the CUSTOMERS table, where the salary is greater than 2000 −
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000;

This would produce the following result −


+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

DATABASE MANAGEMENT SYSTEMS Page 63


From clause:

From clause can be used to specify a sub-query expression in SQL. The relation produced
by the sub-query is then used as a new relation on which the outer query is applied.
 Sub queries in the from clause are supported by most of the SQL implementations.
 The correlation variables from the relations in from clause cannot be used in the sub-
queries in the from clause.

Syntax:
SELECT column1, column2 FROM
(SELECT column_x as C1, column_y FROM table WHERE PREDICATE_X)
as table2
WHERE PREDICATE;

SET Operations
SQL supports few Set operations which can be performed on the table data. These are used to
get meaningful results from data stored in the table, under different special conditions.
In this tutorial, we will cover 4 different types of SET operations, along with example:

1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS

1. Union

o The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
o In the union operation, all the number of datatype and columns must be same in both
the tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.

DATABASE MANAGEMENT SYSTEMS Page 64


Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;

The First table

ID NAME

1 Jack

2 Harry

3 Jackson

The Second table

ID NAME

3 Jackson

4 Stephan

5 David

Union SQL query will be:


SELECT * FROM First
UNION
SELECT * FROM Second;

The resultset table will look like:

DATABASE MANAGEMENT SYSTEMS Page 65


ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan

5 David

2. Union All

Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.

Syntax:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:


SELECT * FROM First
UNION ALL
SELECT * FROM Second;

The resultset table will look like:

DATABASE MANAGEMENT SYSTEMS Page 66


-ID NAME

1 Jack

2 Harry

3 Jackson

3 Jackson

4 Stephan

5 David

3. Intersect

o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.

Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

DATABASE MANAGEMENT SYSTEMS Page 67


SELECT * FROM First
INTERSECT
SELECT * FROM Second;

The resultset table will look like:

ID NAME

3 Jackson

4. Minus

o It combines the result of two SELECT statements. Minus operator is used to display
the rows which are present in the first query but absent in the second query.

o It has no duplicates and data arranged in ascending order by default.

Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:


SELECT * FROM First
MINUS
SELECT * FROM Second;

The resultset table will look like:

DATABASE MANAGEMENT SYSTEMS Page 68


ID NAME

1 Jack

2 Harry

Aggregate functions in SQL


o SQL aggregation function is used to perform the calculations on multiple rows of a
single column of a table. It returns a single value.

o It is also used to summarize the data.


Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()

1. COUNT FUNCTION

o COUNT function is used to Count the number of rows in a database table. It can work
on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
Count(*): Returns total number of records

DATABASE MANAGEMENT SYSTEMS Page 69


PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: COUNT()
SELECT COUNT(*) FROM PRODUCT_MAST;

Output:
10

Example: COUNT with WHERE


SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;

Output:7

Example: COUNT() with DISTINCT

DATABASE MANAGEMENT SYSTEMS Page 70


SELECT COUNT(DISTINCT COMPANY)
FROM PRODUCT_MAST;

Output:
3

2. SUM Function

Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.

Syntax
SUM()
or
SUM( [ALL|DISTINCT] expression )

Example: SUM()
SELECT SUM(COST)
FROM PRODUCT_MAST;

Output:
670

Example: SUM() with WHERE


SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;

Output:
320

3. AVG function

The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.

DATABASE MANAGEMENT SYSTEMS Page 71


Syntax
AVG()

Example:
SELECT AVG(COST)
FROM PRODUCT_MAST;

Output:
67.00

4. MAX Function

MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.

Syntax: MAX()

Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
30

5. MIN Function

MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.

Syntax:MIN() )

Example: SELECT MIN(RATE)


FROM PRODUCT_MAST;

Output:10

GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary rows, like
"find the number of customers in each country".

DATABASE MANAGEMENT SYSTEMS Page 72


The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result-set by one or more columns.

GROUP BY Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Example:
 Group By single column: Group By single column means, to place all the rows with
same value of only that particular column in one group. Consider the query as shown
below:
 SELECT NAME, SUM(SALARY) FROM Employee
 GROUP BY NAME;
The above query will produce the below output:

DATABASE MANAGEMENT SYSTEMS Page 73


Group By multiple columns: Group by multiple column is say for example, GROUP BY
column1, column2. This means to place all the rows with same values of both the
columns column1 and column2 in one group. Consider the below query:
SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;

HAVING Clause:

We know that WHERE clause is used to place conditions on columns but what if we want
to place conditions on groups?
This is where HAVING clause comes into use. We can use HAVING clause to place
conditions to decide which group will be the part of final result-set. Also we can not use
the aggregate functions like SUM(), COUNT() etc. with WHERE clause. So we have to
use HAVING clause if we want to use any of these functions in the conditions.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;
function_name: Name of the function used for example, SUM() , AVG().

DATABASE MANAGEMENT SYSTEMS Page 74


table_name: Name of the table.
condition: Condition used.
Example:
SELECT NAME, SUM(SALARY) FROM Employee
GROUP BY NAME
HAVING SUM(SALARY)>3000;

Example

Consider the CUSTOMERS table having the following records.


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would display a record for a similar age count that would be
more than or equal to 2.
SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;

This would produce the following result −


+----+--------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |

DATABASE MANAGEMENT SYSTEMS Page 75


+----+--------+-----+---------+---------+
Nested Queries

In nested queries, a query is written inside a query. The result of inner query is used in
execution of outer query. We will use STUDENT, COURSE,
STUDENT_COURSE tables for understanding nested queries.
STUDENT

S_ID S_NAME S_ADDRESS S_PHONE S_AGE

S1 RAM DELHI 9455123451 18

S2 RAMESH GURGAON 9652431543 18

S3 SUJIT ROHTAK 9156253131 20

S4 SURESH DELHI 9156768971 18

COURSE

C_ID C_NAME

C1 DSA

C2 Programming

C3 DBMS

STUDENT_COURSE

S_ID C_ID

DATABASE MANAGEMENT SYSTEMS Page 76


S1 C1

S1 C3

S2 C1

S3 C2

S4 C2

S4 C3

Example

Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Now, let us check the following subquery with a SELECT statement.

SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID

DATABASE MANAGEMENT SYSTEMS Page 77


FROM CUSTOMERS
WHERE SALARY > 4500) ;

This would produce the following result.

+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Students

id name class_id GPA

1 Jack Black 3 3.45

2 Daniel White 1 3.15

3 Kathrine Star 1 3.85

4 Helen Bright 2 3.10

5 Steve May 2 2.40

DATABASE MANAGEMENT SYSTEMS Page 78


Teachers

id name subject class_id monthly_salary

1 Elisabeth Grey History 3 2,500

2 Robert Sun Literature [NULL] 2,000

3 John Churchill English 1 2,350

4 Sara Parker Math 2 3,000

Classes

id grade teacher_id number_of_students

1 10 3 21

2 11 4 25

3 12 1 28

SELECT *
FROM students
WHERE GPA > (
SELECT AVG(GPA)
FROM students);

DATABASE MANAGEMENT SYSTEMS Page 79


result:

id name class_id GPA

1 Jack Black 3 3.45

3 Kathrine Star 1 3.85

SELECT AVG(number_of_students)
FROM classes
WHERE teacher_id IN (
SELECT id
FROM teachers
WHERE subject = 'English' OR subject = 'History');

Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the fields from one or more tables present in the
database.
o A view can either have specific rows based on certain condition or all the rows of a
table.

Sample table:

Student_Detail

STU_ID NAME ADDRESS

1 Stephan Delhi

DATABASE MANAGEMENT SYSTEMS Page 80


2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram

Student_Marks

STU_ID NAME MARKS AGE

1 Stephan 97 19

2 Kathrin 86 21

3 David 74 18

4 Alina 90 20

5 John 96 18

1. Creating view

A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.

Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;

DATABASE MANAGEMENT SYSTEMS Page 81


2. Creating View from a single table

Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;

Just like table query, we can query the view to view the data.
SELECT * FROM DetailsView;

Output:

NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad

3. Creating View from multiple tables

View from multiple tables can be created by simply include multiple tables in the SELECT
statement.

In the given example, a view is created named MarksView from two tables Student_Detail
and Student_Marks.

Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;

DATABASE MANAGEMENT SYSTEMS Page 82


To display data of View MarksView:
SELECT * FROM MarksView;

NAME ADDRESS MARKS

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90

4. Deleting View

A view can be deleted using the Drop View statement.

Syntax
1. DROP VIEW view_name;

Example:

If we want to delete the View MarksView, we can do this as:


1. DROP VIEW MarksView;

Uses of a View :
A good database should contain views due to the given reasons:
1. Restricting data access –
Views provide an additional level of table security by restricting access to a
predetermined set of rows and columns of a table.
2. Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.

DATABASE MANAGEMENT SYSTEMS Page 83


3. Simplify commands for the user –
Views allows the user to select information from multiple tables without requiring the
users to actually know how to perform a join.
4. Store complex queries –
Views can be used to store complex queries.
5. Rename Columns –
Views can also be used to rename the columns without affecting the base tables
provided the number of columns in view must match the number of columns specified
in select statement. Thus, renaming helps to to hide the names of the columns of the
base tables.
6. Multiple view facility –
Different views can be created on the same table for different users.

Trigger: A trigger is a stored procedure in database which automatically invokes


whenever a special event in the database occurs. For example, a trigger can be invoked
when a row is inserted into a specified table or when certain table columns are being
updated.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Explanation of syntax:

1. create trigger [trigger_name]: Creates or replaces an existing trigger with the


trigger_name.
2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. on [table_name]: This specifies the name of the table associated with the trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for
each row being affected.
6. [trigger_body]: This provides the operation to be performed as trigger is fired

DATABASE MANAGEMENT SYSTEMS Page 84

You might also like