Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
42 views

RDBMS NOTES (1)

Uploaded by

Saritha Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

RDBMS NOTES (1)

Uploaded by

Saritha Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 227

RELATIONAL DATABASE MANAGEMENT SYSTEM

UNIT I
Basic Concepts
What is Data?
The Raw facts are called as Data. The word “Raw” indicates that
they have not been processed.

For example, 89 is the data.

What is Information?
The processed data is known as Information.

Ex: Marks: 89; then it becomes information.

What is Knowledge?
1. Knowledge refers to the practical use of information.
2. Knowledge necessarily involves a personal experience.

Data / Information Processing


The Process of converting the data (raw facts) into meaningful
information is called as data / information processing.

Difference between Data and Information


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.

For example: The College Database organizes the data about the
admin, staff, students and faculty etc.

Using the database, you can easily retrieve, insert, and delete the
information.

What is DBMS?
o Database Management System is a software which is used to
manage the database. For example: MySQL, Oracle, etc are a
very popular commercial database which is used in different
applications.
o DBMS provides an interface to perform various operations like
database creation, storing data in it, updating data,
creating a table in the database and more.
o It provides protection and security to the database. In case of
multiple users, it also maintains data consistency(database
must be consistent before and after transaction)

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

o multiple user interface: It provides different types of user


interfaces like graphical user interfaces, application program interfaces

Disadvantages of DBMS
o Cost of Hardware and Software: It requires a high speed of
data processor and large memory size to run DBMS software.
o Size: It occupies a large space of disks and large memory to run
them efficiently.
o Complexity: Database system creates additional complexity and
requirements.
o Higher impact of failure: Failure is highly impacted(strongly
affected by something) 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.
What is RDBMS?

 RDBMS stands for Relational Database Management


System.
 All modern database management systems like SQL, MS SQL
Server, IBM DB2, ORACLE, My-SQL, and Microsoft Access
are based on RDBMS.

 It is called Relational Database Management System


(RDBMS) because it is based on the relational model introduced
by E.F. Codd.

How it works

 Data is represented in terms of Tuples (rows) in RDBMS.


 A relational database is the most commonly used database. It
contains several tables, and each table has its primary key.

 Due to a collection of an organized set of tables, data can be


accessed easily in RDBMS.

File based System

The systems that are used to organize and maintain data files are
known as file based data systems. These file systems are used to
handle a single or multiple files and are not very efficient.

Advantages of File Based System


 The file Based system is not complicated and is simpler to use.
 Because of the above point, this system is quite inexpensive.
 Because the file based system is simple and cheap, it is normally
suitable for home users and owners of small businesses.
 The file based system is used by smaller organizations or
individual users, it stores comparatively lesser amount of data.
Hence, the data can be accessed faster and more easily.

Disadvantages of File Based System


 The File based system is limited to a smaller size and cannot
store large amounts of data.
 This system cannot support complicated queries, data
recovery etc.
 There may be redundant data in the file based system as it does
not have a complex mechanism to get rid of it.
 The data is not very secure in a file based system and may be
corrupted or destroyed.
 The data files in the file based system may be stored across
multiple locations. Consequently, it is difficult to share the data
easily with multiple users.

Database Approach

The database approach is a method of designing and


implementing a database, that emphasizes(highlight) the use of a
specific set of characteristics to ensure that the data is accurate,
consistent, and easily accessible.
Data Independence
One of the most important characteristics of the database
approach is data independence. This refers to the ability to change
the structure of the database without affecting the programs that
access the data.

Data Integrity
Another important characteristic of the database approach is
data integrity. This refers to the accuracy and consistency of the
data in the database. The database approach uses a variety of
techniques to ensure data integrity, such as data validation, data
constraints, and data normalization.

Data validation is the process of checking the data entered into the
database to ensure that it is correct and consistent.

Data constraints are used to ensure that the data in the database
follows specific rules.

Data normalization is the process of organizing the data in the


database to reduce data redundancy and increase data consistency.

Data Sharing
Another important characteristic of the database approach is
data sharing. This refers to the ability of multiple users to access and
update the data in the database at the same time. The database
approach uses a variety of techniques to ensure data sharing, such as
locking and concurrency control.

Locking is the process of preventing other users from accessing a


specific piece of data while it is being updated.
Concurrency control is the process of managing access to the data
in the database by multiple users.

Backup and Recovery


Another important characteristic of the database approach is the
ability to back up and recover data. This is important in case of system
failures or other unexpected

events that may cause data loss. The database approach uses a
variety of techniques to ensure that data can be backed up and
recovered, such as database backups, transaction logs, and
replication.

Database backups are copies of the entire database or specific parts


of the database that can be used to restore the data in case of data
loss.

Transaction logs are a record of all the changes made to the


database, such as data insertions, updates, and deletions. These logs
can be used to reconstruct the state of the database at a specific point
in time, which can be useful in case of data loss.

Replication is the process of copying the data in a database to


multiple servers, which can provide a level of redundancy in case of
data loss.

Three Level Architecture / ANSI-SPARC


database Architecture
This architecture has three levels:

1. External level

2. Conceptual level

3. Internal level
1. External level

 It is also known as view level.

 This is highest level architecture and closest to the user.

 The user doesn’t need to know the database schema details such
as data structure, table definition etc.

 External level is related to the data which is viewed by individual


end users.

2. Conceptual level

 It is also known as logical level.

 The conceptual level is a higher level than the physical level.

 This level is maintained by DBA(database administrator)

 The whole design of the database such as relationship among data


, schema of data etc. are described in this level.

 It is the middle level between external or internal levels.

3. Internal level

 It is also known as physical level.

 This is the lowest level of the architecture.

 This data is stored in the external hard drives in the form of bits.
 This level describes how the data actually stored in the storage
device.

 This physical level also discuss encryption techniques.

 This level is also responsible for allocating space of the data.

Database Administrator(DBA)
A Database Administrator (DBA) is an individual person or
group of persons who is responsible for controlling, maintaining,
coordinating, and operating a database management system in an
organization.

Functions of DBA

Some specific functions of a DBA may include


 Installing and configuring database management systems (DBMS)
 Designing and implementing database structures
 Importing and exporting data to and from databases
 Setting up user accounts and managing access to the database
 Monitoring and optimizing database performance.
 Ensuring data security and integrity through backups, testing, and
recovery processes
 Troubleshooting and resolving issues with the database
 Staying up-to-date with new technologies and best practices in
database management.
 Installing and upgrading the database management system
(DBMS) related software.
 Creating and maintaining databases, including backup and
recovery procedures.
 Setting up user accounts and managing access to the database.
 Developing and enforcing database policies and procedures.
 Providing support and training to users.
 Coordinating with developers to design and optimize database
structures and schemes.
 Performing data migration between different DBMS platforms or
between different versions of the same DBMS.

Roles of DBA
A database administrator (DBA) plays a crucial role in the
management of a database management system (DBMS). The DBA is
responsible for the overall design, implementation, maintenance, and
security of the database.
A database administrator (DBA) is responsible for managing the
performance, integrity, and security of a database.

Some roles of the DBA are

1. Setting up and configuring the database server


2. Loading and organizing data into the database
3. Ensuring the database is secure and protecting it from
unauthorized access
4. Monitoring the performance of the database and optimizing it as
needed
5. Backing up and restoring the database
6. Troubleshooting any issues that arise with the database
7. Developing and enforcing database policies and procedures
8. Designing and implementing the database structure
9. Installing and configuring the database management system
(DBMS)
10.Setting up user accounts and maintaining system security
11. Ensuring the database is available and accessible to users
12. Monitoring and optimizing the performance of the database
13.Backing up and restoring the database in case of data loss
14. Ensuring data integrity and implementing measures to prevent
data loss
15.Planning for future expansion and upgrades to the database
The role of a DBA is important because the database is at the heart of
many business operations, and ensuring that it is well-managed is
critical for the smooth functioning of the organization.

Types of Databases
The evolution of database systems are as follows:

1. File Management System


2. Hierarchical database system
3. Network database system
4. Relational database system

1. File Management System

The File Management System also called as FMS in short is on


which all data is stored on a single large file. The main disadvantage
in this system is searching a record or data takes a long time. This
leads to the introduction of the concept of indexing in this system.
Then also the FMS system had a lot of drawbacks to name a few like
updating or modifications to the data cannot handled easily. Sorting
the records look long time and so on. All these drawbacks led to the
introduction of the Hierarchical Database System.

2. Hierarchical database system


The previous system FMS drawback of accessing records and
sorting records which look a long time was removed in this by the
introduction of Parent-Child relationship between records in database.
The origin of the data is called the Root from which several branches
have data at different levels and the last level is called leaf. The main
drawback in this was if there is any modification or addition made to
the structure then the whole structure needed alteration which made
the task a dull one. In order to avoid this, next system Network
Database System was introduced.

3. Network database system


A network database system is based on a traditional hierarchical
database system, except it allows each object to have multiple
parents instead of a single parent. This allows you to model more
complex relationships.

Network databases can be represented as a graph instead of a


tree structure. Network databases provide a lot of flexibility, but are
still limited to access patterns and design limitations of hierarchical
databases. These limitations were later overcome by relational
database management systems.

4.Relational database system


In order to overcome all the drawbacks of the previous systems,
the Relational Database System got introduced in which data get
organized as tables and each record forms a row with many fields or
attributes in it. Relations between tables are also formed in this
system.
RELATIONAL MODEL

What is the Relational Model ?

The Relational Model represents how data is stored in Relational


Databases. A relational database consists of a collection of tables,
each of which is assigned a unique name. Consider a relation
STUDENT with attributes ROLL_NO, NAME, ADDRESS, PHONE, and AGE
shown in the table.

Table Student

ROLL_N
O NAME ADDRESS PHONE AGE

94551234 1
1 RAM DELHI
51 8

RAMES GURGAO 96524315 1


2
H N 43 8

91562531 2
3 SUJIT ROHTAK
31 0

SURES 1
4 DELHI
H 8

Important Terminologies
 Attribute: Attributes are the properties that define an entity.
e.g.; ROLL_NO, NAME, ADDRESS
 Relation Schema: A relation schema defines the structure of the
relation and represents the name of the relation with its attributes.
e.g.; STUDENT (ROLL_NO, NAME, ADDRESS, PHONE, and AGE) is the
relation schema for STUDENT. If a schema has more than 1 relation,
it is called Relational Schema.
 Tuple: Each row in the relation is known as a tuple. The above relation contains 4 tuples, one of which is
shown as:

RA DEL 94551234 1
1
M HI 51 8

 Relation Instance: The set of tuples of a relation at a particular

instance of time is called a relation instance. Table 1 shows the

relation instance of STUDENT at a particular time. It can change

whenever there is an insertion, deletion, or update in the database.

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

degree of the relation. The STUDENT relation defined above has

degree 5.

 Cardinality: The number of tuples in a relation is known

as cardinality. The STUDENT relation defined above has cardinality

4.

 Column: The column represents the set of values for a particular

attribute. The column ROLL_NO is extracted from the relation STUDENT.

ROLL_
NO

1
ROLL_
NO

 NULL Values: The value which is not known or unavailable is


called a NULL value. It is represented by blank space. e.g.; PHONE
of STUDENT having ROLL_NO 4 is NULL.

 Relation Key: These are basically the keys that are used to
identify the rows uniquely or also help in identifying tables.
 Domain: Domain is the data type used by a column in a
database. This data type can be a built-in type (such as an integer
or a string) or a custom type that defines constraints on the data.

Keys in Relational Model


o Keys play an important role in the relational database.
o It is used to uniquely identify any record or row of data from the
table. It is also used to establish and identify relationships
between tables.

For example, ID is used as a key in the Student table because it is


unique for each student. In the PERSON table, passport_number,
license_number, SSN are keys since they are unique for each person.
Types of keys

1. Primary Key
2. Candidate Key
3. Super Key
4. Foreign Key
5. Alternate Key
6. Composite Key

1. Primary key
o It is the first key used to identify one and only one instance of an
entity uniquely. An entity can contain multiple keys, as we saw in
the PERSON table. The key which is most suitable from those lists
becomes a primary key.
o In the EMPLOYEE table, ID can be the primary key since it is
unique for each employee. In the EMPLOYEE table, we can even
select License_Number and Passport_Number as primary keys
since they are also unique.
o For each entity, the primary key selection is based on
requirements and developers.
2. Candidate key
o A candidate key is an attribute or set of attributes that can
uniquely identify a tuple.
o Except for the primary key, the remaining attributes are
considered a candidate key. The candidate keys are as strong as
the primary key.

For example: In the EMPLOYEE table, id is best suited for the


primary key. The rest of the attributes, like SSN, Passport_Number,
License_Number, etc., are considered a candidate key.
3. Super Key
Super key is an attribute set that can uniquely identify a tuple. A super
key is a superset of a candidate key.

For example: In the above EMPLOYEE table, for(EMPLOEE_ID,


EMPLOYEE_NAME), the name of two employees can be the same, but
their EMPLYEE_ID can't be the same. Hence, this combination can also
be a key.

The super key would be EMPLOYEE-ID (EMPLOYEE_ID, EMPLOYEE-


NAME), etc.
4. Foreign key
o Foreign keys are the column of the table used to point to the
primary key of another table.
o Every employee works in a specific department in a company,
and employee and department are two different entities. So we
can't store the department's information in the employee table.
That's why we link these two tables through the primary key of
one table.
o We add the primary key of the DEPARTMENT table,
Department_Id, as a new attribute in the EMPLOYEE table.
o In the EMPLOYEE table, Department_Id is the foreign key, and
both the tables are related.

5. Alternate key

There may be one or more attributes or a combination of


attributes that uniquely identify each tuple in a relation. These
attributes or combinations of the attributes are called the candidate
keys. One key is chosen as the primary key from these candidate keys,
and the remaining candidate key, if it exists, is termed the alternate
key. In other words, the total number of the alternate keys is the
total number of candidate keys minus the primary key. The alternate
key may or may not exist. If there is only one candidate key in a
relation, it does not have an alternate key.

For example, employee relation has two attributes, Employee_Id and


PAN_No, that act as candidate keys. In this relation, Employee_Id is
chosen as the primary key, so the other candidate key, PAN_No, acts
as the Alternate key.

6. Composite key

Whenever a primary key consists of more than one attribute, it is


known as a composite key. This key is also known as Concatenated
Key.
For example, in employee relations, we assume that an employee
may be assigned multiple roles, and an employee may work on
multiple projects simultaneously. So the primary key will be composed
of all three attributes, namely Emp_ID, Emp_role, and Proj_ID in
combination. So these attributes act as a composite key since the
primary key comprises more than one attribute.

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.

Types of Integrity Constraints


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.

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

Example:

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.

Example:
Relational Algebra / Relational Operations
Relational algebra is a procedural query language. It gives a
step by step process to obtain the result of the query. It uses operators
to perform queries.

Types of Relational operations

1. Select Operation
o The select operation selects tuples that satisfy a given predicate.
o It is denoted by sigma (σ).

Notation: σ p(r)

Where: σ is used for selection prediction


r is used for relation
p is used as a propositional logic formula which may use
connectors like: AND, OR and NOT. These relational can use
as relational operators like =, ≠, ≥, <, >, ≤.

For example: LOAN Relation

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

Input:

1. σ BRANCH_NAME="perryride" (LOAN)

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300


2. Project Operation
o This operation shows the list of those attributes that we wish to
appear in the result. Rest of the attributes are eliminated from the
table.
o It is denoted by ∏.

Notation: ∏ A1, A2, An (r)

Where: A1, A2, An is used as an attribute name of relation r.

Example: CUSTOMER Relation

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:

1) ∏ NAME, CITY (CUSTOMER)

Output:

NAME CITY
Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

3. Union Operation
o Suppose there are two tuples R and S. The union operation
contains all the tuples that are either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.

Notation: R ∪ S

A union operation must hold the following conditions:

o R and S must have the attribute of the same number.


o Duplicate tuples are eliminated automatically.

Example: 1) 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
2) BORROW Relation

CUSTOMER_NAME LOAN_NO

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17

Input:

1)
∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Johnson

Smith
Hayes

Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes

4. Set Intersection
o Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in both R & S.
o It is denoted by intersection ∩.

Notation: R ∩ S

Example: Using the above DEPOSITOR table and BORROW table

Input:

1) ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:
CUSTOMER_NAM
E

Smith

Jones

5. Set Difference
o Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).

Notation: R - S

Example: Using the above DEPOSITOR table and BORROW table

Input:

1) ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NA
ME

Jackson

Hayes

Willians

Curry
6. Cartesian product
o The Cartesian product is used to combine each row in one table
with each row in the other table. It is also known as a cross
product.
o It is denoted by X.

Notation: E X D

Example: 1) EMPLOYEE Relation

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B

2) DEPARTMENT Relation

DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal

Input:
1) EMPLOYEE X DEPARTMENT

Output:

EMP_ID EMP_NAM EMP_DEPT DEPT_N DEPT_NA


E O ME

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

3 John B C Legal

7. Rename Operation

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.
1) ρ(STUDENT1, STUDENT)

ENTITY-RELATIONSHIP MODEL (E – R MODEL)

E-R 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.

Symbols Used in ER Model


E-R Model is used to model the logical view of the system from a data
perspective which consists of these symbols:

 Rectangles: Rectangles represent Entities in ER Model.


 Ellipses: Ellipses represent Attributes in ER Model.
 Diamond: Diamonds represent Relationships among Entities.
 Lines: Lines represent attributes to entities and entity sets with
other relationship types.
 Double Ellipse: Double Ellipses represent Multi-Valued
Attributes.
 Double Rectangle: Double Rectangle represents a Weak Entity.

Components 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.

Consider an organization as an example- manager, product,


employee, department etc. can be taken as an entity.

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.
1) Key Attribute

 The key attribute is used to represents the main characteristics


of an entity. It represents a primary key. The key attribute is
represented by an ellipse with the text underlined.

2) 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.
3) Multi valued Attribute

 An attribute can have more than one value. These attributes


are known as a multi valued attribute. The double oval is
used to represent multi valued attribute.

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

4) 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:

1) 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.
2) 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.

3) 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.
4) 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.
Defining relationship for College Database
Conversion of E-R Diagram to Relational Database
Conversion of an E-R diagram into a relational model is required
because E-R diagrams represent the conceptual level of the
database design while the relational model represents the logical
level. The relational models can be easily implemented using RDBMS
like Oracle, MySQL, etc.

In general, conversion of E-R diagram into a relational model


involves the following:

1. Mapping of an entity set into relation (tables) of the database.


2. The attributes of a table include the attributes of an entity
3. The key attribute of an entity becomes the primary key of the
relation
For example,

Consider the following E-R diagram in the figure below. The E-R
diagram consists of Employee as an entity set
and EmpNo, EmpName, and Salary as its attributes. Here we map
entity set into a relation Employee and attributes of an entity set will
become the attributes inside the table. The key attribute will become
the primary key of the table.
Entity set with a composite attribute

While converting an E-R diagram consisting of a composite attribute


we do not include the composite attribute in the relational model. The
compositions of the composite attribute will become the attributes in
the relational model. For example in the figure given below, Salary is
the composite attribute, and Basic, DA, and HRA are its compositions.
Conver
sion of an E-R diagram containing composite attribute

Entity set with multivalued attributes

If an entity contains a multivalued attribute, we split the attributes into


two relations in the relational model. One with key attribute and all
simple attributes and other with key attribute and all multivalued
attributes. For example, in the figure given below, PhoneNo is the
multivalued attribute.

If we include the PhoneNo in the table with all other attributes, then
for a single-valued tuple we may have multiple entries as shown in the
table below
However, to avoid duplicate values in the table, we split the attributes
into two different relations as shown in the figure below

Likewise, we map the entity set into the relation in a relational model,
we can also map a relationship set into a relation. The attribute of such
a relation includes key attributes of the participating relations. The
attributes are will become a foreign key.

For example, in the figure given below, there are two entity
sets Employee and Department. These entity sets are participating in a
relationship works in. The relationship set is converted into relation
with attributes EmpNo from Employee relation, D_id
from Department relation and Since, the attribute of the relationship
set itself.
UNIT II
Dependency
 Dependency is a relation between two or more attributes.

 Mainly the Four types of Dependencies are available.

It has the following types in DBMS −

 Functional Dependency
 Transitive Dependency
 Multivalued Dependency
 Partial Dependency

Functional Dependency

If the information stored in a table can uniquely determine another


information in the same table, then it is called Functional
Dependency. Consider it as an association between two attributes of
the same relation.

If P functionally determines Q, then

P -> Q

Let us see an example −

<Employee>

EmpID EmpName EmpAge


E01 Amit 28
E02 Rohit 31
In the above table, EmpName is functionally dependent
on EmpID because EmpName can take only one value for the given
value of EmpID:

EmpID -> EmpName

The same is displayed below −

Transitive Dependency
When an indirect relationship causes functional dependency it is called
Transitive Dependency.

If P -> Q and Q -> R is true, then P-> R is a transitive dependency.

Multivalued Dependency
When existence of one or more rows in a table implies one or more
other rows in the same table, then the Multi-valued dependencies
occur.

If a table has attributes P, Q and R, then Q and R are multi-valued


facts of P.

It is represented by double arrow −

->->
For our example:

P->->QQ->->R
In the above case, Multivalued Dependency exists only if Q and R are
independent attributes.
Partial Dependency
Partial Dependency occurs when a nonprime attribute is
functionally dependent on part of a candidate key.

The 2nd Normal Form (2NF) eliminates the Partial Dependency. Let us
see an example −

<StudentProject>

StudentID ProjectNo StudentName ProjectNam


e
S01 199 Katie Geo Location
S02 120 Ollie Cluster
Exploration

In the above table, we have partial dependency; let us see


how −

The prime key attributes are StudentID and ProjectNo.

As stated, the non-prime attributes


i.e. StudentName and ProjectName should be functionally
dependent on part of a candidate key, to be Partial Dependent.

The StudentName can be determined by StudentID that makes the


relation Partial Dependent.

The ProjectName can be determined by ProjectID, which that the


relation Partial Dependent.

What is Normalization?

o Normalization is the process of organizing the data in the


database.
o Normalization is used to minimize the redundancy from a relation
or set of relations.
o Normalization divides the larger table into smaller and links them
using relationships.
o The normal form is used to reduce redundancy from the database
table.
Normal Forms

Mainly the five types of Normal Forms are available.

 First Normal Form(1NF)


 Second Normal Form(2NF)
 Third Normal Form(3NF)
 Boyce-Codd Normal Form
 Fourth Normal Form(4NF)

First Normal Form (1NF)


o A relation will be 1NF if it contains an atomic(single) value.
o It states that an attribute of a table cannot hold multiple
values. It must hold only single-valued attribute.
o First normal form disallows the multi-valued attribute,
composite attribute, and their combinations.

Example: Relation EMPLOYEE is not in 1NF because of multi-


valued attribute EMP_PHONE.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_PHONE EMP_STAT


E

14 John 7272826385, UP
9064738238

20 Harry 8574783832 Bihar

12 Sam 7390372389, Punjab


8589830302
The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385 UP

14 John 9064738238 UP

20 Harry 8574783832 Bihar

12 Sam 7390372389 Punjab

12 Sam 8589830302 Punjab

Second Normal Form (2NF)


o In the 2NF, relational must be in 1NF.
o In the second normal form, all non-key attributes are fully
functional dependent on the primary key

Example: Let's assume, a school can store the data of teachers and
the subjects they teach. In a school, a teacher can teach more than
one subject.

TEACHER table

TEACHER_ID SUBJECT TEACHER_AGE

25 Chemistry 30

25 Biology 30

47 English 35

83 Math 38
83 Computer 38

In the given table, non-prime attribute (attributes which are not part
of any candidate key) TEACHER_AGE is dependent on TEACHER_ID
which is a proper subset of a candidate key. That's why it violates the
rule for 2NF.

To convert the given table into 2NF, we decompose it into two


tables:

TEACHER_DETAIL table

TEACHER_ID TEACHER_AGE

25 30

47 35

83 38

TEACHER_SUBJECT table

TEACHER_ID SUBJECT

25 Chemistry

25 Biology

47 English
83 Math

83 Computer

Third Normal Form (3NF)


o A relation will be in 3NF if it is in 2NF and not contain any
transitive partial dependency.
o 3NF is used to reduce the data duplication. It is also used to
achieve the data integrity.
o If there is no transitive dependency for non-prime attributes, then
the relation must be in third normal form.

A relation is in third normal form if it holds atleast one of the following


conditions for every non-trivial function dependency X → Y.

1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some
candidate key.

Example:

EMPLOYEE_DETAIL table

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CIT


Y

222 Harry 201010 UP Noida

333 Stephan 02228 US Boston

444 Lan 60007 US Chicago


555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Super key in the table above:

1. {EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP}....


so on

Candidate key: {EMP_ID}

Non-prime attributes: In the given table, all attributes except


EMP_ID are non-prime.

Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and


EMP_ZIP dependent on EMP_ID. The non-prime attributes
(EMP_STATE, EMP_CITY) transitively dependent on super
key(EMP_ID). It violates the rule of third normal form.

That's why we need to move the EMP_CITY and EMP_STATE to the


new <EMPLOYEE_ZIP> table, with EMP_ZIP as a Primary key.

EMPLOYEE table

EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228

444 Lan 60007


555 Katharine 06389

666 John 462007

EMPLOYEE_ZIP table

EMP_ZIP EMP_STATE EMP_CITY

201010 UP Noida

02228 US Boston

60007 US Chicago

06389 UK Norwich

462007 MP Bhopal

Boyce Codd normal form (BCNF)


o BCNF is the advance version of 3NF. It is stricter than 3NF.
o A table is in BCNF if every functional dependency X → Y, X is the
super key of the table.
o For BCNF, the table should be in 3NF, and for every FD, LHS is
super key.

Example: Let's assume there is a company where employees work in more than one
department.

EMPLOYEE table

EMP_ID EMP_COUNTR EMP_DEPT DEPT_TYPE EMP_DEPT_N


Y O

264 India Designing D394 283

264 India Testing D394 300

364 UK Stores D283 232

364 UK Developing D283 549

In the above table Functional dependencies are as follows:

1.EMP_ID → EMP_COUNTRY
2.EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Candidate key: {EMP-ID, EMP-DEPT}

The table is not in BCNF because neither EMP_DEPT nor EMP_ID alone
are keys.

To convert the given table into BCNF, we decompose it into three


tables:

EMP_COUNTRY table

EMP_ID EMP_COUNTRY

264 India

264 India

EMP_DEPT table
EMP_DEPT DEPT_TYPE EMP_DEPT_NO

Designing D394 283

Testing D394 300

Stores D283 232

Developing D283 549

EMP_DEPT_MAPPING table

EMP_ID EMP_DEPT

D394 283

D394 300

D283 232

D283 549

Functional dependencies:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Candidate keys:

For the first table: EMP_ID


For the second table: EMP_DEPT
For the third table: {EMP_ID, EMP_DEPT}

Now, this is in BCNF because left side part of both the functional
dependencies is a key.
Fourth normal form (4NF)
o A relation will be in 4NF if it is in Boyce Codd normal form and has
no multi-valued dependency.
o For a dependency A → B, if for a single value of A, multiple values
of B exists, then the relation will be a multi-valued dependency.

Example:

STUDENT table

STU_ID COURSE HOBBY

21 Computer Dancing

21 Math Singing

34 Chemistry Dancing

74 Biology Cricket

59 Physics Hockey

The given STUDENT table is in 3NF, but the COURSE and HOBBY are
two independent entity. Hence, there is no relationship between
COURSE and HOBBY.

In the STUDENT relation, a student with STU_ID, 21 contains two


courses, Computer and Math and two
hobbies, Dancing and Singing. So there is a Multi-valued dependency
on STU_ID, which leads to unnecessary repetition of data.

So to make the above table into 4NF, we can decompose it into two
tables:
STUDENT_COURSE table

STU_ID COURSE

21 Computer

21 Math

34 Chemistry

74 Biology

59 Physics

STUDENT_HOBBY table

STU_ID HOBBY

21 Dancing

21 Singing

34 Dancing

74 Cricket

59 Hockey

File Organization and its Types

 The File is a collection of records. Using the primary key, we can


access the records.
 File organization is a logical relationship among various
records. This method defines how file records are mapped onto disk
blocks.
 File Organization is also defined as storing the files in a specific
order.

The Objective of File Organization


 It helps in the faster selection of records i.e. it makes the process
faster.
 Different Operations like inserting, deleting, and update on
different records are faster and easier.
 It prevents us from inserting duplicate records via various
operations.
 It helps in storing the records or the data very efficiently at a
minimal cost

Types of File Organizations


Various methods have been introduced to Organize files. These
particular methods have advantages and disadvantages on the basis
of access or selection. Thus it is all upon the programmer to decide
the best-suited file Organization method according to his
requirements.

Some types of File Organizations are :

 Sequential File Organization


 Heap File Organization
 Indexed File Organization
 Hash File Organization

Sequential File Organization


This method is the easiest method for file organization. In this method,
files are stored sequentially. This method can be implemented in two
ways:

1. Pile File Method

o It is a quite simple method. In this method, we store the record


in a sequence, i.e., one after another. Here, the record will be
inserted in the order in which they are inserted into tables.
o In case of updating or deleting of any record, the record will be
searched in the memory blocks. When it is found, then it will be
marked for deleting, and the new record is inserted.

Insertion of the new record:

Suppose we have four records R1, R3 and so on upto R9 and R8 in a


sequence. Hence, records are nothing but a row in the table. Suppose
we want to insert a new record R2 in the sequence, then it will be
placed at the end of the file. Here, records are nothing but a row in any
table.
2. Sorted File Method

o In this method, the new record is always inserted at the file's end,
and then it will sort the sequence in ascending or descending
order. Sorting of records is based on any primary key or any other
key.
o In the case of modification of any record, it will update the record
and then sort the file, and lastly, the updated record is placed in
the right place.

Insertion of the new record:

Suppose there is a preexisting sorted sequence of four records R1, R3


and so on upto R6 and R7. Suppose a new record R2 has to be inserted
in the sequence, then it will be inserted at the end of the file, and then
it will sort the sequence.
Pros of sequential file organization

o It contains a fast and efficient method for the huge amount of


data.
o In this method, files can be easily stored in cheaper storage
mechanism like magnetic tapes.
o It is simple in design. It requires no much effort to store the data.

Cons of sequential file organization

o It will waste time as we cannot jump on a particular record that is


required but we have to move sequentially which takes our time.
o Sorted file method takes more time and space for sorting the
records.

Heap File Organization


o It is the simplest and most basic type of organization. It works
with data blocks. In heap file organization, the records are
inserted at the file's end. When the records are inserted, it
doesn't require the sorting and ordering of records.
o When the data block is full, the new record is stored in some
other block. This new data block need not to be the very next
data block, but it can select any data block in the memory to
store new records. The heap file is also known as an unordered
file.
o In the file, every record has a unique id, and every page in a file is
of the same size. It is the DBMS responsibility to store and
manage the new records.

Insertion of a new record

Suppose we have five records R1, R3, R6, R4 and R5 in a heap and
suppose we want to insert a new record R2 in a heap. If the data block
3 is full then it will be inserted in any of the database selected by the
DBMS, let's say data block 1.

If we want to search, update or delete the data in heap file


organization, then we need to traverse the data from staring of the file
till we get the requested record.

If the database is very large then searching, updating or deleting of


record will be time-consuming because there is no sorting or ordering
of records. In the heap file organization, we need to check all the data
until we get the requested record.

Pros of Heap file organization


o It is a very good method of file organization for bulk insertion. If
there is a large number of data which needs to load into the
database at a time, then this method is best suited.
o In case of a small database, fetching and retrieving of records is
faster than the sequential record.
Cons of Heap file organization
o This method is inefficient for the large database because it takes
time to search or modify the record.
o This method is inefficient for large databases.

Indexed Sequential File Organization / Indexed


Sequential Access Method(ISAM)

ISAM method is an advanced sequential file organization. In this


method, records are stored in the file using the primary key. An
index value is generated for each primary key and mapped with the
record. This index contains the address of the record in the file.

If any record has to be retrieved based on its index value, then the
address of the data block is fetched and the record is retrieved from
the memory.

Pros of ISAM
o In this method, each record has the address of its data block,
searching a record in a huge database is quick and easy.
o This method supports range retrieval and partial retrieval of
records. Since the index is based on the primary key values, we
can retrieve the data for the

given range of value. In the same way, the partial value can also
be easily searched, i.e., the student name starting with 'JA' can be
easily searched.

Cons of ISAM

o This method requires extra space in the disk to store the index
value.
o When the new records are inserted, then these files have to be
reconstructed to maintain the sequence.
o When the record is deleted, then the space used by it needs to be
released. Otherwise, the performance of the database will slow
down.

Hash File Organization

Hash File Organization uses the computation of hash function on


some fields of the records. The hash function's output determines the
location of disk block where the records are to be placed.
When a record has to be received using the hash key columns, then
the address is generated, and the whole record is retrieved using that
address. In the same way, when a new record has to be inserted, then
the address is generated using the hash key and record is directly
inserted. The same process is applied in the case of delete and update.

In this method, there is no effort for searching and sorting the entire
file. In this method, each record will be stored randomly in the
memory.

Indexing
 Indexing is a data structure technique which allows you to
quickly retrieve records from a database file.
 An Index is a small table having only two columns.

Index structure:
Indexes can be created using some database columns.

o The first column of the database is the search key that contains

a copy of the primary key or candidate key of the table. The

values of the primary key are stored in sorted order so that the

corresponding data can be accessed easily.

o The second column of the database is the data reference. It

contains a set of pointers holding the address of the disk block

where the value of the particular key can be found.

Types of Indexes
Primary Index

Primary Index is an ordered file which is fixed length size with two
fields. The first field is the same a primary key and second, filed is
pointed to that specific data block. In the primary Index, there is
always one to one relationship between the entries in the index table.

The primary Indexing in DBMS is also further divided into two


types.

 Dense Index
 Sparse Index

Dense Index

In a dense index, a record is created for every search key valued in


the database. This helps you to search faster but needs more space to
store index records. In this Indexing, method records contain search
key value and points to the real record on the disk.
Sparse Index

It is an index record that appears for only some of the values in the
file. Sparse Index helps you to resolve the issues of dense Indexing in
DBMS. In this method of indexing technique, a range of index
columns stores the same data block address, and when data needs to
be retrieved, the block address will be fetched.

However, sparse Index stores index records for only some search-key
values. It needs less space, less maintenance overhead for insertion,
and deletions but It is slower compared to the dense Index for locating
records.

Below is an database index Example of Sparse Index


 Secondary Index
The secondary Index in DBMS can be generated by a field which
has a unique value for each record, and it should be a candidate key. It
is also known as a non-clustering index.

This two-level database indexing technique is used to reduce the


mapping size of the first level. For the first level, a large range of
numbers is selected because of this; the mapping size always remains
small.

Secondary Index Example

Let’s understand secondary indexing with a database index example:

In a bank account database, data is stored sequentially by acc_no;


you may want to find all accounts in of a specific branch of ABC bank.

Here, you can have a secondary index in DBMS for every search-key.
Index record is a record point to a bucket that contains pointers to all
the records with their specific search-key value.

Clustering Index

 In a clustered index, records themselves are stored in the Index


and not pointers.

 Sometimes the Index is created on non-primary key columns


which might not be unique for each record.

 In such a situation, you can group two or more columns to get


the unique values and create an index which is called clustered
Index. This also helps you to identify the record faster.

Example:

Let’s assume that a company recruited many employees in


various departments. In this case, clustering indexing in DBMS
should be created for all employees who belong to the same dept.
It is considered in a single cluster, and index points point to the
cluster as a whole. Here, Department _no is a non-unique key.

UNIT III

What is SQL?

SQL stands for Structured Query Language which is a computer


language for storing, manipulating and retrieving data stored in a
relational database.

Why SQL?
SQL is widely popular because it offers the following
advantages −

 Allows users to access data in the relational database


management systems.
 Allows users to describe the data.
 Allows users to define the data in a database and manipulate that
data.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a
database.
 Allows users to set permissions on tables, procedures and views.

A Brief History of SQL

 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of


relational databases. He described a relational model for
databases.
 1974 − Structured Query Language (SQL) appeared.
 1978 − IBM worked to develop Codd's ideas and released a
product named System/R.
 1986 − IBM developed the first prototype of relational database
and standardized by ANSI. The first relational database was
released by Relational Software which later came to be known as
Oracle.
 1987 − SQL became the part of the International Organization for
Standardization (ISO).

SQL Operators

Operators are the foundation of any programming language. We can


define operators as symbols that help us to perform specific
mathematical and logical computations on operands.

Types of SQL Operators

1) Arithmetic operators
2) Comparison operators
3) Logical operators
1) Arithmetic operators
We can use various Arithmetic Operators on the data stored in the
tables.

+ [Addition]
- [Subtraction]
/ [Division]
* [Multiplication]
% [Modulus]

Example
SELECT employee_id, employee_name, salary, salary + 100
AS "salary + 100" FROM addition;

Output
employee_na
employee_id me salary salary+100

1 alex 25000 25100

2 rr 55000 55100

3 jpm 52000 52100

4 ggshmr 12312 12412

2) Comparison operators

There are six comparison operators available which help us run


queries to perform various operations. We will use the
WHERE command along with the conditional operator.

> Greater than

< Less than

>= Greater than or equals to

>= Less than or equals to

= Equals to
<> Not Equal to

Example

SELECT * FROM MATHS WHERE MARKS>=80;

Output
3) Logical Operators

In SQL, the AND & OR operators are used for filtering the data and
getting precise results based on conditions. The
SQL AND & OR operators are also used to combine multiple
conditions.

AND Operator:
This operator displays only those records where both the conditions
condition1 and condition2 evaluates to True.

Syntax:

SELECT * FROM table_name WHERE condition1 AND condition2


AND……...conditionN;

OR Operator:
This operator displays the records where either one of the conditions
condition1 and condition2 evaluates to True. That is, either condition1
is True or condition2 is True.

Syntax:

SELECT * FROM table_name WHERE condition1 OR condition2


OR... ..conditionN;
Now, we consider a table database to demonstrate AND & OR
operators with multiple cases:

If suppose we want to fetch all the records from the Student table
where Age is 18 and ADDRESS is Delhi. then the query will be:

Query:
SELECT * FROM Student WHERE Age = 18 AND ADDRESS =
'Delhi';

Output:

ROLL_ NAM ADDRE


NO E SS PHONE Age

XXXXXXXX 1
1 Ram Delhi
XX 8
ROLL_ NAM ADDRE
NO E SS PHONE Age

SURE XXXXXXXX 1
4 Delhi
SH XX 8

Take another example, to fetch all the records from the Student
table where NAME is Ram and Age is 18.

Query:

SELECT * FROM Student WHERE Age = 18 AND NAME = 'Ram';

Output:

ROLL_ NAM ADDRE


NO E SS PHONE Age

XXXXXXXX 1
1 Ram Delhi
XX 8

To fetch all the records from the Student table where NAME is Ram
or NAME is SUJIT.
Query:
SELECT * FROM Student WHERE NAME = 'Ram' OR NAME = 'SUJIT';

Output:

ROLL_ NAM ADDRES


NO E S PHONE Age

XXXXXXXX 1
1 Ram Delhi
XX 8

ROHTA XXXXXXXX 2
3 SUJIT
K XX 0

ROHTA XXXXXXXX 2
3 SUJIT
K XX 0

Types of Languages

SQL commands are like instructions to a table. It is used


to interact with the database with some operations. It is also used to
perform specific tasks, functions, and queries of data. SQL can
perform various tasks like creating a table, adding data to tables,
dropping the table, modifying the table, set permission for users.

These SQL commands are mainly categorized into five


categories:
1) DDL – Data Definition Language
2) DML – Data Manipulation Language
3) DCL – Data Control Language
4) TCL – Transaction Control Language
5) DQL – Data Query Language
1) DDL – Data Definition Language

CREATE TABLE Command


A Table is a combination of rows and columns. For creating a table
we have to define the structure of a table by adding names to
columns and providing data type and size of data to be stored in
columns.

Syntax:
CREATE table table_name

( Column1 datatype (size),

column2 datatype (size),

columnN datatype(size));

Here table_name is name of the table, column is the name of


column

CREATE TABLE Example


Let us create a table to store data of Customers, so the table name is
Customer, Columns are Name, Country, age, phone, and so on.

CREATE TABLE Customer

( CustomerID NUMBER PRIMARY KEY,

CustomerName VARCHAR2(50),

LastName VARCHAR2(50),
Country VARCHAR(50),

Age NUMBER(2),

Phone NUMBER(10));

Output:

DESCRIBE Command
As the name suggests, DESCRIBE is used to describe something. Since
in a database, we have tables, that’s why do we
use DESCRIBE or DESC(both are the same) commands to describe
the structure of a table.
Syntax:
DESCRIBE Table_name;

OR

DESC Table_name;

Example:

DESC users_info;

Output
Name Null? Type
------------------------------ -------- ----------------------------

NO NOT NULL NUMBER(3)


NAME VARCHAR2(30)
ADDRESS VARCHAR2(70)
CONTACT_NO VARCHAR2(12)
ALTER TABLE Command
The ALTER TABLE statement is used to add, delete, or modify columns
in an existing table.

Look at the "Persons" table:

ID LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

ALTER TABLE - ADD Column


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

ALTER TABLE table_name


ADD column_name datatype;

Example

Now we want to add a column named "DateOfBirth" in the


"Persons" table.
ALTER TABLE Persons
ADD ADD DateOfBirth date;

Output
The "Persons" table will now look like this:

ID LastName FirstName Address City DateOfBirth

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

ALTER TABLE - DROP Column


To delete a column in a table, use the following syntax (notice that
some database systems don't allow deleting a column):

ALTER TABLE table_name


DROP Column column_name;

The following SQL deletes the "DateOfBirth" column from the "Persons"
table:
Example

ALTER TABLE Persons


DROP COLUMN DateOfBirth;

The "Persons" table will now look like this:

ID LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

ALTER TABLE - MODIFY DATATYPE


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

ALTER TABLE table_name


MODIFY column_name datatype;

DROP
DROP is used to delete a whole table(Records with structure)

Syntax:
DROP TABLE table_name;
Example:
DROP TABLE Persons;

TRUNCATE
The TRUNCATE TABLE Command is used to delete the data inside a
table, but not the table itself.

Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE Employee;

RENAME
RENAME Command is used to change the Name of the existing
table.

Syntax:

RENAME old_table_name To new_table_name;

Example:

RENAME Employee To Customer;

2) DML – Data Manipulation Language

Insert Command
To add data to the table, we use INSERT INTO command, the syntax
is as shown below:
Syntax:
//Below query adds data in specific column, (like Column1=Value1)//

Insert into Table_name(Column1, Column2, Column3)


Values (Value1, value2, value3);

//Below query adds data in table in sequence of column name(Value1 will


be added in Column1 and so on)//

Insert into Table_name


Values (Value1, value2, value3);

//Adding multiple data in the table in one go//

Insert into Table_name


Values (Value01, value02, value03),

(Value11, value12, value13),

(Value21, value22, value23),

(ValueN1, valueN2, valueN3)

Example Query
This query will add data in the table named Subject

-- Insert some sample data into the Customers table

INSERT INTO Customer (CustomerID, CustomerName, LastName,


Country, Age, Phone)

VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),

(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),


(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),

(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),

(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');

Output:

Create a Table Using Another Table


We can also use CREATE TABLE to create a copy of an existing table.
In the new table, it gets the exact column definition all columns or
specific columns can be selected.

If an existing table was used to create a new table, by default the new
table would be populated with the existing values from the old table.

Syntax:
CREATE TABLE new_table_name AS

SELECT column1, column2,…

FROM existing_table_name ;

Query:
CREATE TABLE SubTable AS

SELECT CustomerID, CustomerName

FROM customer;
Output:

UPDATE Command
UPDATE Command is used to modify the existing records in a
table. It only modifies the data present in a table without affecting the
table's structure.
Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
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 query will update the ADDRESS for a customer whose
ID number is 6 in the table.

UPDATE CUSTOMERS

SET ADDRESS = 'Pune'

WHERE ID = 6;

Output

The query produces the following output −

(1 row affected)

Verification

To verify whether the records of the table are modified or not, use the
following SELECT query below −

SELECT * FROM CUSTOMERS;

Now, the CUSTOMERS table would have 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 | Pune | 4500.00 |

| 7 | Muffy | 24 | Indore | 10000.00 |

+----+----------+-----+-----------+----------+

DELETE Command

DELETE Command is used to delete one or more records from a


table.

Syntax
DELETE FROM table_name [WHERE condition];

Here table_name is the table which has to be deleted. The WHERE


clause is optional here.

Let us take a table, named "EMPLOYEE" table.

ID EMP_NAME CITY SALARY

101 Adarsh Singh Obra 20000

102 Sanjay Singh Meerut 21000

103 Priyanka Sharma Raipur 25000


104 Esha Singhal Delhi 26000

Example1

DELETE FROM EMPLOYEE WHERE ID=101;

Output

ID EMP_NAME CITY SALARY

102 Sanjay Singh Meerut 21000

103 Priyanka Sharma Raipur 25000

104 Esha Singhal Delhi 26000

Example2

DELETE FROM EMPLOYEE;

Output

ID EMP_NAME CITY SALARY

 It will delete all the records of EMPLOYEE table.


 It will delete the all the records of EMPLOYEE table where ID is
101.

 WHERE clause is used to prevent the deletion of all the rows in the
table, If you don't use the WHERE clause you might loss all the
rows.

3) DQL – Data Query Language


The SELECT Command is used in Data Query Language Command.
The SELECT Command is used to retrieve or fetch data from
a database. We can fetch either the entire table or according to
some specified rules.

Let us a take an Example Table as CUSTOMER

Syntax1:
SELECT column1,column2 FROM table_name;

Example:

SELECT CustomerName, LastName FROM Customer;


Output:

Syntax2:
SELECT * FROM table_name;

It fetches all the columns from the required table.

3) DCL – Data Control Language


DCL includes commands such as GRANT and REVOKE which mainly
deal with the rights, permissions, and other controls of the
database system.

List of DCL commands:

GRANT: This command gives users access privileges to the


database.
Syntax:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_US
ER;
REVOKE: This command withdraws the user’s access privileges
given by using the GRANT command.
Syntax:
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
4) TCL – Transaction Control Language
The TCL commands are:

1. COMMIT
2. ROLLBACK
3. SAVEPOINT
1. COMMIT :
This command is used to save the data permanently.
Whenever we perform any of the DML command like -INSERT,
DELETE or UPDATE, these can be rollback if the data is not stored
permanently. So in order to be at the safer side COMMIT command is
used.
Syntax:
commit;

2. ROLLBACK :
This command is used to get the data or restore the data to the last
savepoint or last committed state. If due to some reasons the data
inserted, deleted or updated is not correct, you can rollback the data
to a particular savepoint or if savepoint is not done, then to the last
committed state.
Syntax:
rollback;

3. SAVEPOINT :
This command is used to save the data at a particular point
temporarily, so that whenever needed can be rollback to that
particular point.
Syntax:
Savepoint A;

Consider the following Table Student:


Mar
Name ks

John 79

Jolly 65

Shuz
70
an

UPDATE STUDENT

SET NAME = ‘Sherlock’

WHERE NAME = ‘Jolly’;

COMMIT;

ROLLBACK;

By using this command you can update the record and save it
permanently by using COMMIT command.

Now after COMMIT :

Mar
Name ks

John 79
Mar
Name ks

Sherlo
65
ck

Shuza
70
n

If commit was not performed then the changes made by the


update command can be rollback.

Now if no COMMIT is performed.

UPDATE STUDENT

SET NAME = ‘Sherlock’

WHERE STUDENT_NAME = ‘Jolly’;

After update command the table will be:

Mar
Name ks

John 79

Sherlo
65
ck

Shuza
70
n
Now if ROLLBACK is performed on the above table:
rollback;

After Rollback:

Mar
Name ks

John 79

Jolly 65

Shuz
70
an

If on the above table savepoint is performed:

INSERT into STUDENT

VALUES ('Jack', 95);

Commit;

UPDATE NAME

SET NAME= ‘Rossie’

WHERE marks= 70;

SAVEPOINT A;

INSERT INTO STUDENT


VALUES (‘Zack’, 76);

Savepoint B;

INSERT INTO STUDENT

VALUES (‘Bruno’, 85);

Savepoint C;

SELECT * FROM STUDENT;

Nam Mar
e ks

John 79

Jolly 65

Ross
70
ie

Jack 95

Zack 76

Brun
85
o
Now if we Rollback to Savepoint B:

Rollback to B;

The resulting Table will be-

Nam Mar
e ks

John 79

Jolly 65

Ross
70
ie

Jack 95

Zack 76

Now if we Rollback to Savepoint A:

Rollback to A;

The resulting Table will be-

Nam Mar
e ks

John 79

Jolly 65

Ross 70
Nam Mar
e ks

ie

Jack 95
WHERE Clause

WHERE keyword is used for fetching filtered data in a result set. It


is used to fetch data according to particular
criteria. WHERE keyword can also be used to filter data by matching
patterns.

Basic Syntax

SELECT column1,column2 FROM table_name WHERE column_name


operator value;

Parameter Explanation:

1. column1,column2: fields in the table


2. table_name: name of table
3. column_name: name of field used for filtering the data
4. operator: operation to be considered for filtering
5. value: exact value or pattern to get related data in result

WHERE Clause in SELECT statement


We can use the WHERE clause in a SELECT statement to retrieve
filtered rows based on a specific condition or expression. Following is
the syntax for it −

SELECT column1, column2,……FROM table_name WHERE condition;

Example

Assume we have created a table with name CUSTOMERS in SQL


database using CREATE TABLE statement as shown below −
CREATE TABLE CUSTOMERS (

ID INT NOT NULL,

NAME VARCHAR (20) NOT NULL,

AGE INT NOT NULL,

ADDRESS CHAR (25),

SALARY DECIMAL (18, 2),

PRIMARY KEY (ID)

);

Following query inserts values into this table using the INSERT
statement −

insert INTO CUSTOMERS VALUES(1, 'Ramesh', 32, 'Ahmedabad',


2000.00);

insert INTO CUSTOMERS VALUES(2, 'Khilan', 25, 'Delhi', 1500.00);

insert INTO CUSTOMERS VALUES(3, 'kaushik', 23, 'Kota', 2000.00);

insert INTO CUSTOMERS VALUES(4, 'Chaitali', 25, 'Mumbai', 6500.00);

insert INTO CUSTOMERS VALUES(5, 'Hardik', 27, 'Bhopal', 8500.00);

insert INTO CUSTOMERS VALUES(6, 'Komal', 22, 'MP', 4500.00);

insert INTO CUSTOMERS VALUES(7, 'Muffy', 24, 'Indore', 10000.00);

If we verify the contents of the CUSTOMERS table using the


SELECT statement, we can observe the inserted records as shown
below −

SELECT * from CUSTOMERS;


+----+----------+-----+-----------+----------+
| 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 query is an example which would fetch the ID, Name
and Salary fields from the CUSTOMERS table created above using
the SELECT statement, where the salary is greater than 2000 −

SELECT ID, NAME, SALARY

FROM CUSTOMERS

WHERE SALARY > 2000;

Output

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 |
+----+----------+----------+

WHERE Clause in UPDATE statement


We can also use the WHERE clause in a UPDATE statement to update rows in a table which
satisfy a certain condition. If the WHERE clause is not used, the
UPDATE statement would affect all the records of a table. Following is
the syntax −

UPDATE table_name SET column1 = value1, column2 = value2, ...


WHERE condition;

Example

In the following query we are trying to update the age of all the
customers whose age is ‘25’ and updating it to ‘30’ using UPDATE
statement −

UPDATE CUSTOMERS set AGE = 30 where AGE = 25;

Output

We get the following result. We can observe that the age of 2


customers have been modified −

(2 rows affected)
Verification

To verify if the changes are reflected in the tables, we can use SELECT
statement to print the tables as shown in the following query −

SELECT * from CUSTOMERS;

The table is displayed as follows −

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

As we can see in the above table, the AGE of ‘Khilan’ and ‘Chaitali’ has
been updated to ‘30’.

WHERE Clause with IN operator


The WHERE clause, when with IN operator, compares the records of
a table with a certain list of values. If this clause is used with the
SELECT statement, it allows us to retrieve the rows in a table that
match any of the values in the specified list. Following is the syntax for
it −

WHERE column_name IN (value1, value2, ...);

Where, the column_name is the column of a table and value1,


value2, etc. are the list of values that we want to compare with the
column_name.

Example

Suppose you want to display records with NAME equalling to ‘Khilan’,


‘Hardik’ and ‘Muffy’ (string values) from the CUSTOMERS table, you
can use the following query IN operator −

SELECT * from CUSTOMERS WHERE NAME IN ('Khilan', 'Hardik',


'Muffy');

Output

The result obtained is as follows −


+----+--------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+--------+-----+---------+----------+

WHERE Clause with NOT IN operator


Using the WHERE clause with NOT IN operator will perform the
negation of WHERE clause with IN operation. The IN operator will
compare the rows of table with the list of values and the NOT operator
will except the rows that are matched. Hence, when used with SELECT
statement, the rows that do not match the list of values are retrieved.
Following is the syntax −

WHERE column_name NOT IN (value1, value2, ...);


Example

In this example, we are trying to display the records from CUSTOMERS


table, where AGE is NOT equal to ‘25’, ‘23’ and ‘22’ as shown in the
query below −

SELECT * from CUSTOMERS

WHERE AGE NOT IN (25, 23, 22);

Output

We obtain the result as given below −

+----+--------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+--------+-----+-----------+----------+

WHERE Clause with LIKE operator


The WHERE clause with LIKE operator allows us to filter rows that
matches a specific pattern. This specific pattern is represented by
wildcards (such as %, _, [] etc). Following is the syntax −

WHERE column_name LIKE pattern;

Where, column_name is the column that we want to compare the


pattern against and pattern is a string that can contain wildcards
(such as %, _, [] etc).

Example

Following is the query, which would display all the records where the
name starts with K and is at least 4 characters in length −

SELECT * FROM CUSTOMERS

WHERE NAME LIKE 'K___%';

Output

The result obtained is given below −

+----+---------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+---------+-----+---------+---------+
WHERE Clause with AND, OR operators
We can use AND and OR operators together in SQL to combine multiple
conditions in a WHERE clause to filter rows that meets the specified
criteria. AND operator will make sure only those rows are filtered that
satisfy all the conditions and OR operator will filtered records that
satisfy any one condition specified. However, this is only used when
specifying one condition is not enough to filter all the required rows.

Following is the syntax for using the AND and OR operators in


a WHERE clause −

WHERE (condition1 OR condition2) AND condition3;

Example

In the following query, we are trying to retrieve all rows from the
"CUSTOMERS" table based on some conditions. The parentheses
control the order of evaluation so that the OR operator is applied first,
followed by the AND operator −

SELECT * FROM CUSTOMERS

WHERE (AGE = 25 OR salary < 4500) AND (name = 'Komal' OR name


= 'Kaushik');

Output

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+
ORDER BY Clause / Statement

The ORDER BY clause is used to sort the data in either ascending or


descending order based on one or more columns.

ORDER BY is used with the SELECT statement and is usually


specified after the WHERE, HAVING and GROUP BY clauses, if
present in the query.

Note −

 Some databases sort the query results in an ascending order by


default.
 To sort the data in ascending order, we use the keyword ASC.
 To sort the data in descending order, we use the
keyword DESC.

Sort According To One Column


To sort in ascending or descending order we can use the keywords
ASC or DESC respectively.

Syntax

SELECT * FROM table_name ORDER BY column_name ASC |


DESC

Sort According To Multiple Columns


To sort in ascending or descending order we can use the keywords
ASC or DESC respectively. To sort according to multiple columns,
separate the names of columns by the (,) operator.
Syntax:

SELECT * FROM table_name ORDER BY column1 ASC|DESC , column2


ASC|DESC

ORDER BY with ASC


We can use the ORDER BY clause with the ASC keyword to sort the
result set of a query in ascending order based on one or more columns.
When using the ORDER BY clause, if you do not explicitly specify the
sort order, ASC is used by default.

Example

Assume we have created a table with name CUSTOMERS in SQL


database using CREATE TABLE statement as shown below −

CREATE TABLE CUSTOMERS

( ID INT NOT NULL,

NAME VARCHAR (20) NOT NULL,

AGE INT NOT NULL,

ADDRESS CHAR (25),

SALARY DECIMAL (18, 2),

PRIMARY KEY (ID)

);

Following query inserts values into this table using the INSERT
statement −
insert INTO CUSTOMERS VALUES(1, 'Ramesh', 32, 'Ahmedabad',
2000.00);

insert INTO CUSTOMERS VALUES(2, 'Khilan', 25, 'Delhi', 1500.00);

insert INTO CUSTOMERS VALUES(3, 'kaushik', 23, 'Kota', 2000.00);

insert INTO CUSTOMERS VALUES(4, 'Chaitali', 25, 'Mumbai', 6500.00);

insert INTO CUSTOMERS VALUES(5, 'Hardik', 27, 'Bhopal', 8500.00);

insert INTO CUSTOMERS VALUES(6, 'Komal', 22, 'MP', 4500.00);

insert INTO CUSTOMERS VALUES(7, 'Muffy', 24, 'Indore', 10000.00);

If we verify the contents of the CUSTOMERS table using the


SELECT statement, we can observe the inserted records as
shown below −

SELECT * from CUSTOMERS;

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
In the following query we are trying to sort the result in an ascending
order by the name and the salary of the customers −

SELECT * FROM CUSTOMERS ORDER BY NAME ASC;

Output

This would produce the following result −

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

ORDER BY with DESC


We can also use the ORDER BY clause with the DESC keyword to sort
the result set of a query in descending order based on one or more
columns.

Example

The following query sorts the result in the descending order by the
name of the customers −

SELECT * FROM CUSTOMERS ORDER BY NAME DESC;


Output

This would produce the result as follows −

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

ORDER BY Multiple Columns


 We can use the ORDER BY clause to sort the result set of a query
by multiple (more than one) columns.

 When sorting by multiple columns, the sorting is done in the order


that is specified in the ORDER BY clause.

 In other words, the table will be sorted first by sorting the first
column specified, then the second column, and so on.

Example

In the following query, we are trying to retrieve all records from the
CUSTOMERS table and sorts them first by their address in ascending
order, and then by their salary in descending order −

SELECT * FROM CUSTOMERS ORDER BY AGE ASC, SALARY DESC;

Output

Following is the result produced −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00|
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00|
+----+----------+-----+-----------+----------+
In the above output, we can see that first the result is sorted in
ascending order according to AGE. There are multiple rows of
having the same Age. Now, sorting further this result-set according to
SALARY will sort the rows with the same Age according to SALARY in
descending order.

ORDER BY with WHERE clause


In SQL, we can use the WHERE clause with the ORDER BY
clause to sort only the rows that meet certain specified conditions.
This can be useful when we want to sort a subset of the data in a table
based on the specified criteria.

Example

Now, we are trying to retrieve all records from the CUSTOMERS table
where the age of the customer is 25 and sort them in descending order
based on their name −

SELECT * FROM CUSTOMERS

WHERE AGE = 25

ORDER BY NAME DESC;


Output

Following is the output of the above query −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+

ORDER BY with TOP clause


We can use the TOP clause with ORDER BY clause to limit the
specified number of rows by sorting it in either ascending or
descending order.

Syntax

Following is the syntax of using the TOP clause with the ORDER BY
clause in SQL −

SELECT TOP N column1, column2, ...


FROM table_name
ORDER BY column_name1 [ASC | DESC], column_name2 [ASC | DESC],
...

Example

In here, we are trying to retrieve the top 4 records from the


CUSTOMERS table on the basis of their salary, and sort them in
ascending order based on their name −

SELECT TOP 4 SALARY

FROM CUSTOMERS

ORDER BY NAME;
Output

Following is the output of the above query −

+----------+
| SALARY |
+----------+
| 6500.00 |
| 8500.00 |
| 2000.00 |
| 1500.00 |
+----------+

GROUP BY Clause/Statement

The GROUP BY Statement is used to arrange identical data into


groups with the help of some functions. i.e. if a particular column
has the same values in different rows then it will arrange these rows
in a group.

Features

 GROUP BY clause is used with the SELECT statement.

 In the query, the GROUP BY clause is placed after

the WHERE clause.

 In the query, the GROUP BY clause is placed before

the ORDER BY clause if used.


 In the query, the Group BY clause is placed before the Having

clause.

 Place condition in the having clause.


Syntax:
SELECT column1, function_name(column2)

FROM table_name

WHERE condition

GROUP BY column1, column2

ORDER BY column1, column2;

Explanation:
1. function_name: Name of the function used for example, SUM() ,
AVG().
2. table_name: Name of the table.
3. condition: Condition used.

Let’s assume that we have two tables Employee and Student


Sample Table is as follows after adding two tables we will do some
specific operations to learn about GROUP BY.

Employee Table:
CREATE TABLE emp (

emp_no INT PRIMARY KEY,

name VARCHAR(50),

sal DECIMAL(10,2),

age INT

);

Insert some random data into a table and then we will perform some
operations in GROUP BY.
Query:
INSERT INTO emp (emp_no, name, sal, age) VALUES

(1, 'Aarav', 50000.00, 25),

(2, 'Aditi', 60000.50, 30),

(3, 'Amit', 75000.75, 35),

(4, 'Anjali', 45000.25, 28),

(5, 'Chetan', 80000.00, 32),

(6, 'Divya', 65000.00, 27),

(7, 'Gaurav', 55000.50, 29),

(8, 'Isha', 72000.75, 31),

(9, 'Kavita', 48000.25, 26),

(10, 'Mohan', 83000.00, 33);

Output:

Student Table:
Query:
CREATE TABLE student

( name VARCHAR(50),

year INT,

subject VARCHAR(50));

INSERT INTO student (name, year, subject) VALUES

('Alice', 1, 'Mathematics'),

('Bob', 2, 'English'),

('Charlie', 3, 'Science'),

('David', 1, 'History'),

('Emily', 2, 'Art'),

('Frank', 3, 'Computer Science');

Output:

Group By single column

Group By single column means, placing all the rows with the same
value of only that particular column in one group. Consider the query
as shown below:

Query:
SELECT NAME, SUM(SALARY) FROM emp

GROUP BY NAME;

The above query will produce the below output:

As you can see in the above output, the rows with duplicate
NAMEs are grouped under the same NAME and their corresponding
SALARY is the sum of the SALARY of duplicate rows. The SUM()
function of SQL is used here to calculate the sum.

Group By Multiple Columns

Group by multiple columns is say, for example, GROUP BY column1,


column2. This means placing all the rows with the same values of
columns column 1 and column 2 in one group. Consider the below
query:
Query:
SELECT SUBJECT, YEAR, Count(*)

FROM Student

GROUP BY SUBJECT, YEAR;


Output:

As you can see in the above output the students with both the
same SUBJECT and YEAR are placed in the same group. And those
whose only SUBJECT is the same but not YEAR belong to different
groups. So here we have grouped the table according to two columns
or more than one column.

HAVING Clause in GROUP BY Clause

We know that the WHERE clause is used to place conditions on


columns but what if we want to place conditions on groups? This is
where the HAVING clause comes into use. We can use the HAVING
clause to place conditions to decide which group will be part of the
final result set. Also, we can not use aggregate functions like SUM(),
COUNT(), etc. with the WHERE clause. So we have to use the 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;

Explanation:
1. function_name: Name of the function used for example, SUM() ,
AVG().
2. table_name: Name of the table.
3. condition: Condition used.
Example:
SELECT NAME, SUM(sal) FROM Emp

GROUP BY name

HAVING SUM(sal)>3000;

Output:

As you can see in the above output only one group out of the
three groups appears in the result set as it is the only group where
sum of SALARY is greater than 3000. So we have used the HAVING
clause here to place this condition as the condition is required to be
placed on groups not columns.

Nested Queries / Sub Query

A Subquery or Inner query or a Nested query is a query within


another SQL query and embedded within the WHERE clause.

Important Rules:
o A subquery can be placed in a number of SQL clauses like
WHERE clause, FROM clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE
statements along with the operators like =, <, >, >=, <=, IN,
BETWEEN, etc.
o A subquery is a query within another query. The outer query is
known as the main query, and the inner query is known as a
subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But
GROUP BY command can be used to perform the same function as
ORDER BY command.

1. Subqueries with the Select Statement


SQL subqueries are most frequently used with the Select statement.

Syntax

1.SELECT column_name
2.FROM table_name
3.WHERE column_name expression operator
4.( SELECT column_name from table_name WHERE ... );

Example

Consider the EMPLOYEE table have the following records:

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

1. SELECT * FROM EMPLOYEE


2. WHERE ID IN (SELECT ID
3. FROM EMPLOYEE
4. WHERE SALARY > 4500);

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

2. Subqueries with the INSERT Statement


o SQL subquery can also be used with the Insert statement. In
the insert statement, data returned from the subquery is used to
insert into another table.
o In the subquery, the selected data can be modified with any of
the character, date functions.

Syntax:

1. INSERT INTO table_name (column1, column2, column3....)


2. SELECT *
3. FROM table_name
4. WHERE VALUE OPERATOR

Example:

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

Now use the following syntax to copy the complete EMPLOYEE


table into the EMPLOYEE_BKP table.

1. INSERT INTO EMPLOYEE_BKP


2. SELECT * FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE);

3. Subqueries with the UPDATE Statement


The subquery of SQL can be used in conjunction with the Update
statement. When a subquery is used with the Update statement, then
either single or multiple columns in a table can be updated.

Syntax:

1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);

Example:

Let's assume we have an EMPLOYEE_BKP table available which is


backup of EMPLOYEE table. The given example updates the SALARY
by .25 times in the EMPLOYEE table for all employee whose AGE is
greater than or equal to 29.

1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
4. WHERE AGE >= 29);

This would impact three rows, and finally, the EMPLOYEE table would
have the following records.

ID NAME AGE ADDRESS SALAR


Y
1 John 20 US 2000.0
0

2 Stephan 26 Dubai 1500.0


0

3 David 27 Bangkok 2000.0


0

4 Alina 29 UK 1625.0
0

5 Kathrin 34 Bangalore 2125.0


0

6 Harry 42 China 1125.0


0

7 Jackson 25 Mizoram 10000.


00

4. Subqueries with the DELETE Statement


The subquery of SQL can be used in conjunction with the Delete
statement just like any other statements mentioned above.

Syntax

1. DELETE FROM TABLE_NAME


2. WHERE VALUE OPERATOR
3. (SELECT COLUMN_NAME
4. FROM TABLE_NAME
5. WHERE condition);
Example

Let's assume we have an EMPLOYEE_BKP table available which is


backup of EMPLOYEE table. The given example deletes the records
from the EMPLOYEE table for all EMPLOYEE whose AGE is greater
than or equal to 29.

1. DELETE FROM EMPLOYEE


2. WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP
3. WHERE AGE >= 29 );

This would impact three rows, and finally, the EMPLOYEE table would
have the following records.

ID NAME AGE ADDRESS SALAR


Y

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.0


0

JOINS

SQL Join statement is used to combine data or rows from two or


more tables based on a common field between them.

Types of JOINS

Different types of Joins are as follows:


 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN
 NATURAL JOIN
Consider the two tables below as follows:

Student

StudentCourse

 INNER JOIN
The INNER JOIN keyword selects all rows from both the tables
as long as the condition is satisfied. This keyword will create the
result-set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be the same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

INNER JOIN table2

ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as
INNER JOIN.

Example Queries(INNER JOIN)


This query will show the names and age of students enrolled in
different courses.

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE


FROM Student

INNER JOIN StudentCourse

ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:

 LEFT JOIN

This join returns all the rows of the table on the left side of the
join and matches rows for the table on the right side of the
join. For the rows for which there is no matching row on the right
side, the result-set will contain null. LEFT JOIN is also known as
LEFT OUTER JOIN.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

LEFT JOIN table2

ON table1.matching_column = table2.matching_column;

table1: First table.

table2: Second table

matching_column: Column common to both the tables.

Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both
are the same.
Example Queries(LEFT JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID

FROM Student

LEFT JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

 RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of
the table on the right side of the join and matching rows for the table
on the left side of the join. For the rows for which there is no matching
row on the left side, the result-set will contain null. RIGHT JOIN is also
known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1

RIGHT JOIN table2

ON table1.matching_column = table2.matching_column;

Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN,
both are the same.

Example Queries(RIGHT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID

FROM Student

RIGHT JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:
 FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from both
tables. For the rows for which there is no matching, the result-set will
contain NULL values.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

FULL JOIN table2

ON table1.matching_column = table2.matching_column;
Example Queries(FULL JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID

FROM Student

FULL JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

COURSE
NAME _ID

HARSH 1

PRATIK 2

RIYANK
2
A

DEEP 3

SAPTAR
1
HI
COURSE
NAME _ID

DHANR
NULL
AJ

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5

NULL 4

 Natural join (⋈)

Natural join can join tables based on the common columns in

the tables being joined. A natural join returns all rows by matching

values in common columns having same name and data type of

columns and that column should be present in both tables.

Both tables must have atleast one common column with same

column name and same data type.

The two table are joined using Cross join.


DBMS will look for a common column with same name and data type

Tuples having exactly same values in common columns are kept in

result.

Example:

Employee

Emp_ Emp_na Dept_


id me id

1 Ram 10

2 Jon 30

3 Bob 50

Department

Dept_ Dept_na
id me

10 IT

30 HR

40 TIS

Query: Find all Employees and their respective departments.

Solution: (Employee) ⋈ (Department)


Emp_ Emp_na Dept_ Dept_ Dept_na
id me id id me

1 Ram 10 10 IT

2 Jon 30 30 HR

Department
Employee data data

VIEWS

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

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:

1. CREATE VIEW view_name AS


2. SELECT column1, column2.....
3. FROM table_name
4. WHERE condition;

2. Creating View from a single table


In this example, we create a View named DetailsView from the table
Student_Detail.

Query:

1. CREATE VIEW DetailsView AS


2. SELECT NAME, ADDRESS
3. FROM Student_Details
4. 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:

1. CREATE VIEW MarksView AS


2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Stu
dent_Marks.MARKS
3. FROM Student_Detail, Student_Mark
4. WHERE Student_Detail.NAME = Student_Marks.NAME;

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

DROP VIEW view_name;

Example:

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

DROP VIEW MarksView;

Types of Views:

There are two types of views.


1. Join View: A join view is a view that has more than one table or
view in its from clause and it does not use any Group by Clause,
Rownum, Distinct and set operation.
2. Inline View: An inline view is a view which is created by
replacing a subquery in the from clause which defines the data
source that can be referenced in the main query. The sub query
must be given an alias for efficient working.

Sequences in SQL

 The sequences in SQL is a database object that generates a


sequence of unique integer values.

 They are frequently used in databases because many applications


require each row in a table to contain a unique value and sequences
provide an easy way to generate them.

 Sequences are a feature of many SQL database management


systems, such as Oracle, SQL server, and IBM DB2.

 A sequence is created using the CREATE SEQUENCE statement


in SQL.

 The statement specifies the name of the sequence, the starting value,
the increment, and other properties of the sequence.
Syntax

Following is the syntax to create a sequence in SQL −

CREATE SEQUENCE Sequence_Name


START WITH Initial_Value
INCREMENT BY Increment_Value
MINVALUE Minimum_Value
MAXVALUE Maximum_Value
CYCLE|NOCYCLE;

Here,

 Sequence_Name − This specifies the name of the sequence.


 Initial_Value − This specifies the starting value from where the
sequence should start.
 Increment_Value − This specifies the value by which the
sequence will increment by itself. This can be valued positively or
negatively.
 Minimum_Value − This specifies the minimum value of the
sequence.
 Maximum_Value − This specifies the maximum value of the
sequence.
 Cycle − When the sequence reaches its Maximum_Value, it starts
again from the beginning.
 Nocycle − An exception will be thrown if the sequence exceeds
the Maximum_Value.
Example

First of all, let us try to create a table “STUDENTS” using the following
query −

SQL> CREATE TABLE STUDENTS (ID INT, NAME CHAR(20), AGE INT NOT
NULL);
Now, let us insert some records in the table using INSERT statements
as shown in the query below −

SQL> INSERT INTO STUDENTS(ID, NAME, AGE) VALUES(NULL, 'Dhruv',


'20');

INSERT INTO STUDENTS(ID, NAME, AGE) VALUES(NULL, 'Arjun', '23');

INSERT INTO STUDENTS(ID, NAME, AGE) VALUES(NULL, 'Dev', '25');

INSERT INTO STUDENTS(ID, NAME, AGE) VALUES(NULL, 'Riya', '19');

INSERT INTO STUDENTS(ID, NAME, AGE) VALUES(NULL, 'Aarohi','24');

INSERT INTO STUDENTS(ID, NAME, AGE) VALUES(NULL, 'Lisa', '20');

INSERT INTO STUDENTS(ID, NAME, AGE) VALUES(NULL, 'Roy', '24');

Let’s verify whether the table STUDENTS is created or not using


the following query −

SQL> SELECT * FROM STUDENTS;

The table is successfully created in the SQL database.

+------+-----------+------+
| ID | NAME | AGE |
+------+-----------+------+
| NULL | Dhruv | 20 |
| NULL | Arjun | 23 |
| NULL | Dev | 25 |
| NULL | Riya | 19 |
| NULL | Aarohi | 24 |
| NULL | Lisa | 20 |
| NULL | Roy | 24 |
+------+-----------+------+

Now, let us try to create a sequence in SQL using the following


statement −
SQL> CREATE SEQUENCE My_Sequence AS INT

START WITH 1

INCREMENT BY 1

MINVALUE 1

MAXVALUE 5

CYCLE;

In the above query, the sequence is named “My_Sequence” and it


starts with the value 1 and increments by 1 each time a value is
generated. The sequence has a maximum value of 5 and cycles back
to the starting value when it reaches the maximum value.

Once the sequence is created, it can be used to generate unique


integer values. Now,

let us try to update the data in the “ID” column of the


STUDENTS table using the following query −

SQL> UPDATE STUDENTS SET ID = NEXT VALUE FOR My_Sequence;

Output

When you execute the above query, the output is obtained as follows −

Commands completed successfully.

Verification

Let us verify whether is sequence is updated in the ID column of the


table or not using the following query −

SQL> SELECT * FROM STUDENTS;

+------+-----------+------+
| ID | NAME | AGE |
+------+-----------+------+
| 1| Dhruv | 20 |
| 2| Arjun | 23 |
| 3| Dev | 25 |
| 4| Riya | 19 |
| 5| Aarohi | 24 |
| 1| Lisa | 20 |
| 2| Roy | 24 |
+------+-----------+------+
UNIT IV

Transactions and Concurrency


Management
What are Transactions?
o The transaction is a set of logically related operation. It
contains a group of tasks.
o A transaction is an action or series of actions. It is performed
by a single user to perform operations for accessing the contents
of the database.

Example: Suppose an employee of bank transfers Rs 800 from X's


account to Y's account. This small transaction contains several low-
level tasks:

X's Account

1. Open_Account(X)
2. Old_Balance = X.balance
3. New_Balance = Old_Balance - 800
4. X.balance = New_Balance
5. Close_Account(X)

Y's Account

1. Open_Account(Y)
2. Old_Balance = Y.balance
3. New_Balance = Old_Balance + 800
4. Y.balance = New_Balance
5. Close_Account(Y)

Operations of Transaction:

Following are the main operations of transaction:

Read(X): Read operation is used to read the value of X from the


database and stores it in a buffer in main memory.

Write(X): Write operation is used to write the value back to the


database from the buffer.

Let's take an example to debit transaction from an account which


consists of following operations:

1. R(X);
2. X = X - 500;
3. W(X);

Let's assume the value of X before starting of the transaction


is 4000.

o The first operation reads X's value from database and stores it in
a buffer.
o The second operation will decrease the value of X by 500. So
buffer will contain 3500.
o The third operation will write the buffer's value to the database.
So X's final value will be 3500.

But it may be possible that because of the failure of hardware,


software or power, etc. that transaction may fail before finished all the
operations in the set.
For example: If in the above transaction, the debit transaction fails
after executing operation 2 then X's value will remain 4000 in the
database which is not acceptable by the bank.

To solve this problem, we have two important operations:

Commit: It is used to save the work done permanently.

Rollback: It is used to undo the work done.

Properties of Transactions

Transactions have the following four standard properties, usually


referred to by the acronym ACID.

 Atomicity − ensures that all operations within the work unit are
completed successfully. Otherwise, the transaction is aborted at
the point of failure and all the previous operations are rolled back
to their former state.
 Consistency − ensures that the database properly changes
states upon a successfully committed transaction.
 Isolation − enables transactions to operate independently of and
transparent to each other.
 Durability − ensures that the result or effect of a committed
transaction persists in case of a system failure.

Concurrent Transactions

The main advantage of DBMS is that it allows ‘n’ number of


users to access the data from the database in the concurrent
manner.
In a multi-programming mode, many transactions are
executed concurrently. In such a mode, while one transaction
waits for the completion of an input/output operation, in the
mean time, the processor can be used to do the computation of
another transaction. That means, number of transactions
alternatively share CPU and desk which will increase the
throughput of the system.

Among the transactions running in the system, few may be


short and other may be long. In case of serial transactions, short
transactions may have to wait for the preceding long transaction
to complete. Thus, there is wastage of time. This drawback is
avoided in concurrent execution of the transaction which allows
the sharing of CPU and disk read/write operations.

If the database is shared by the transactions for read-only


purpose, it does not cause any problem. Problem arises when
any transaction need to perform write operation in database.

Example: Suppose that two ticket agents are dealing with the
seat booking system of a flight. If both agents book last
available seat in the flight, it would result in the overbooking or
double booking of that seat. This leaves the database in an
inconsistent state.
To avoid this inconsistency, some type of isolation should be
enforced among the transactions so that they may affect each
other –

Consider two concurrent transactions as shown below –


Concurrent transactions (where few operations of transaction
T1 are executed, the T2 and again the remaining operations of
T1).

In above transactions, transaction T1 transfers Rs. 50 from


an account a to another account b. Transaction T2 just add Rs.
10 in the first account a referenced in the transaction T1.

Each transaction read some data items, performs some


operations on the data item that change its value and then
writes out the modified data item. The modifications are
reflected in the database only after the write operation which
implies that the changes are committed.

Locking Protocol

In this type of protocol, any transaction cannot read or write data


until it acquires an appropriate lock on it. There are two types of lock:

1. Shared lock:

o It is also known as a Read-only lock. In a shared lock, the data


item can only read by the transaction.
o It can be shared between the transactions because when the
transaction holds a lock, then it can't update the data on the data
item.

2. Exclusive lock:

o In the exclusive lock, the data item can be both reads as well as
written by the transaction.
o This lock is exclusive, and in this lock, multiple transactions do
not modify the same data simultaneously.

Types of Lock-Based Protocols


 Simplistic lock protocol
 Pre-claiming Lock Protocol
 Two-phase locking (2PL)
 Strict Two-Phase Locking Protocol
 Strong strict 2PL/ Rigorous 2PL

Two-Phase Locking(2PL)

A transaction is said to follow the Two-Phase Locking protocol if


Locking and Unlocking can be done in two phases.

1. Growing Phase: New locks on data items may be acquired but


none can be released.
2. Shrinking Phase: Existing locks may be released but no new locks
can be acquired.

Note – If lock conversion is allowed, then upgrading of lock( from S(a)


to X(a) ) is allowed in the Growing Phase, and downgrading of lock
(from X(a) to S(a)) must be done in shrinking phase.
Let’s see a transaction implementing 2-PL.

T1 T2
1 lock-S(A)
2 lock-S(A)
3 lock-X(B)
4 ……. ……
5 Unlock(A)
6 Lock-X(C)
7 Unlock(B)
8 Unlock(A)
9 Unlock(C)
10 ……. ……

This is just a skeleton transaction that shows how unlocking and


locking work with 2-PL. Note for:
Transaction T1:
 The growing Phase is from steps 1-3.
 The shrinking Phase is from steps 5-7.
 Lock Point at 3
Transaction T2:
 The growing Phase is from steps 2-6.
 The shrinking Phase is from steps 8-9.
 Lock Point at 6

Serializable Schedules

What is a Schedule?

Schedule, as the name suggests, is a process of lining the


transactions and executing them one by one. When there are multiple
transactions that are running in a concurrent manner and the order of
operation is needed to be set so that the operations do not overlap
each other, Scheduling is brought into play and the transactions are
timed accordingly.

Serializable Schedule

This is used to maintain the consistency of the database.


 It is mainly used in the Non-Serial scheduling to verify whether the
scheduling will lead to any inconsistency or not.
 On the other hand, a serial schedule does not need the
serializability because it follows a transaction only when the
previous transaction is complete.
 The non-serial schedule is said to be in a serializable schedule only
when it is equivalent to the serial schedules, for an n number of
transactions.
 Since concurrency is allowed in this case thus, multiple transactions
can execute concurrently.
 A serializable schedule helps in improving both resource
utilization and CPU throughput.
These are of two types:
Conflict Serializable:
A schedule is called conflict serializable if it can be transformed
into a serial schedule by swapping non-conflicting operations.
Two operations are said to be conflicting if all conditions satisfy:
 They belong to different transactions
 They operate on the same data item
 At Least one of them is a write operation
View Serializable:
A Schedule is called view serializable if it is view equal to a serial
schedule (no overlapping transactions). A conflict schedule is a
view serializable but if the serializability contains blind writes,
then the view serializable does not conflict serializable.

Deadlock and its Prevention

A deadlock is a condition where two or more transactions are


waiting indefinitely for one another to give up locks. Deadlock is said to
be one of the most feared complications in DBMS as no task ever gets
finished and is in waiting state forever.

For example: In the student table, transaction T1 holds a lock on


some rows and needs to update some rows in the grade table.
Simultaneously, transaction T2 holds locks on some rows in the grade
table and needs to update the rows in the Student table held by
Transaction T1.

Now, the main problem arises. Now Transaction T1 is waiting for T2 to


release its lock and similarly, transaction T2 is waiting for T1 to release
its lock. All activities come to a halt state and remain at a standstill. It
will remain in a standstill until the DBMS detects the deadlock and
aborts one of the transactions.
Deadlock Avoidance

o When a database is stuck in a deadlock state, then it is better to


avoid the database rather than aborting or restating the
database. This is a waste of time and resource.
o Deadlock avoidance mechanism is used to detect any deadlock
situation in advance. A method like "wait for graph" is used for
detecting the deadlock situation but this method is suitable only
for the smaller database. For the larger database, deadlock
prevention method can be used.

Deadlock Detection

o In a database, when a transaction waits indefinitely to obtain a


lock, then the DBMS should detect whether the transaction is
involved in a deadlock or not.
o The lock manager maintains a Wait for the graph to detect the
deadlock cycle in the database.

Deadlock Prevention Techniques

o Deadlock prevention method is suitable for a large database. If


the resources are allocated in such a way that deadlock never
occurs, then the deadlock can be prevented.
o The Database management system analyzes the operations of
the transaction whether they can create a deadlock situation or
not. If they do, then the DBMS never allowed that transaction to
be executed.

Wait-Die scheme

In this scheme, if a transaction requests for a resource which is


already held with a conflicting lock by another transaction then the
DBMS simply checks the timestamp of both transactions. It allows the
older transaction to wait until the resource is available for execution.

Let's assume there are two transactions Ti and Tj and let TS(T) is a
timestamp of any transaction T. If T2 holds a lock by some other
transaction and T1 is requesting for resources held by T2 then the
following actions are performed by DBMS:

1. Check if TS(Ti) < TS(Tj) - If Ti is the older transaction and Tj has


held some resource, then Ti is allowed to wait until the data-item
is available for execution. That means if the older transaction is
waiting for a resource which is locked by the younger transaction,
then the older transaction is allowed to wait for resource until it is
available.
2. Check if TS(Ti) < TS(Tj) - If Ti is older transaction and has held
some resource and if Tj is waiting for it, then Tj is killed and
restarted later with the random delay but with the same
timestamp.

Wound wait scheme


o In wound wait scheme, if the older transaction requests for a
resource which is held by the younger transaction, then older
transaction forces younger one to kill the transaction and release
the resource. After the minute delay, the younger transaction is
restarted but with the same timestamp.
o If the older transaction has held a resource which is requested by
the Younger transaction, then the younger transaction is asked to
wait until older releases it.

Database Recovery and Security


What is Database Recovery?

It is the method of restoring the database to its correct state


in the event of a failure at the time of the transaction or after
the end of a process.

Recovery processes vary depending on the type of failure that


occurred, the structures affected, and the type of recovery that you
perform. If no files are lost or damaged, recovery may amount to no
more than restarting an instance. If data has been lost, recovery
requires additional steps.

Kinds of Failures

To find that where the problem has occurred, we generalize a failure


into the following categories:

1. Transaction failure
2. System crash
3. Disk failure

1. Transaction failure

The transaction failure occurs when it fails to execute or when it


reaches a point from where it can't go any further. If a few transaction
or process is hurt, then this is called as transaction failure.

Reasons for a transaction failure could be -

 Logical errors: If a transaction cannot complete due to


some code error or an internal error condition, then the logical
error occurs.

 Syntax error: It occurs where the DBMS itself terminates an


active transaction because the database system is not able to
execute it. For example, The system aborts an active transaction,
in case of deadlock or resource unavailability.
2. System Crash: System failure can occur due to power failure or
other hardware or software failure. Example: Operating system
error.

Fail-stop assumption: In the system crash, non-volatile storage is


assumed not to be corrupted.

3. Disk Failure: It occurs where hard-disk drives or storage drives


used to fail frequently. It was a common problem in the early days
of technology evolution.
Disk failure occurs due to the formation of bad sectors, disk head
crash, and unreachability to the disk or any other failure, which
destroy all or part of disk storage.

Database Errors
Backup and Recovery Techniques
It is imperative to have a backup of the database in case the original is
corrupted or lost because of any reason. Using this backup, the
database can be recovered as it was before the failure.

Database backup basically means that a duplicate of the database


information and data is created and stored in backup server just to be
on the safe side. Transaction logs are also stored in the backup along
with the database data because without them, the data would be
useless.

Backup Techniques / Methods


The different methods of backup in a database are:

 Full Backup - This method takes a lot of time as the full copy of
the database is made including the data and the transaction
records.
 Transaction Log - Only the transaction logs are saved as the
backup in this method. To keep the backup file as small as
possible, the previous transaction log details are deleted once a
new backup record is made.
 Differential Backup - This is similar to full backup in that it
stores both the data and the transaction records. However only
that information is saved in the backup that has changed since the
last full backup. Because of this, differential backup leads to
smaller files.

Recovery Techniques
There are four different recovery techniques are available in the
Database.

1. Mirroring
2. Recovery using Backups
3. Recovery using Transaction Logs
4. Shadow Paging

Mirroring:

Two complete copies of the database maintains on-line on different


stable storage devices. This method mostly uses in environments that
require non-stop, fault-tolerant operations.

Recovery using Backups:

Backups are useful if there has been extensive damage to database.


Backups are mainly two types :

 Immediate Backup
 Archival Backup
Immediate Backup:
Immediate Backup are kept in a floppy disk, hard disk or magnetic
tapes. These come in handy when a technical fault occurs in the
primary database such as a system failure, disk crash, or network
failure. Damage due to virus attacks repaired using the immediate
backup.

Archival Backup:
Archival Backups are kept in mass storage devices such as magnetic
tape, CD-ROMs, Internet Servers etc. They are very useful for
recovering data after a disaster such as fire, earthquake, flood etc.
Archival Backup should be kept at a different site other than where the
system is functioning. Archival Backup at a separate place remains
safe from thefts and international destruction by user staff.

Recovery using Transaction Logs:


In Recovery using Transaction Logs, some following steps are :
Step1: The log searches for all the transaction that have recorded
a [ start transaction, ‘ ‘] entry, but haven’t recorded a
corresponding [commit, ‘ ‘] entry.
Step2: These transactions are rolling back.
Step3: Transactions which have recorded a [commit, ‘ ‘] entry in the
log, it must have recorded the changes, they did to the database in the
log. These changes will follow to undo their effects on the database.

Shadow Paging:
These systems can use for data recovery instead of using
transaction logs. In Shadow Paging, a database is divided into
several fixed-sized disk pages, say n, thereafter a current directory
creates. It has n entries with each entry pointing to a disk page in the
database. the current directory transfer to the main memory.

When a transaction begins executing, the current directory copies into


a shadow directory. Then, the shadow directory saves on the disk. The
transaction will be using the current directory. During the transaction
execution, all the modifications are made on the current directory and
the shadow directory is never modified.

Database Security
Database Security means keeping sensitive information safe and
prevent the loss of data. Security of data base is controlled by
Database Administrator (DBA).
The following are the main control measures are used to
provide security of data in databases:

1. Authentication
2. Access control
3. Inference control
4. Flow control
5. Database Security applying Statistical Method
6. Encryption

These are explained as following below.

1. Authentication :
Authentication is the process of confirmation that whether the
user log in only according to the rights provided to him to perform
the activities of data base. A particular user can login only up to his
privilege but he can’t access the other sensitive data. The privilege
of accessing sensitive data is restricted by using Authentication.
By using these authentication tools for biometrics such as retina
and figure prints can prevent the data base from
unauthorized/malicious users.
2. Access Control :
The security mechanism of DBMS must include some provisions for
restricting access to the data base by unauthorized users. Access
control is done by creating user accounts and to control login
process by the DBMS. So, that database access of sensitive data is
possible only to those people (database users) who are allowed to
access such data and to restrict access to unauthorized
persons. The database system must also keep the track of all
operations performed by certain user throughout the entire login
time.
3. Inference Control :
This method is known as the counter measures to statistical
database security problem. It is used to prevent the user from
completing any inference channel. This method protect sensitive
information from indirect disclosure.
Inferences are of two types, identity disclosure or attribute
disclosure.
4. Flow Control :
This prevents information from flowing in a way that it reaches
unauthorized users. Channels are the pathways for information to
flow implicitly in ways that violate the privacy policy of a company
are called convert channels.
5. Database Security applying Statistical Method :
Statistical database security focuses on the protection of
confidential individual values stored in and used for statistical
purposes and used to retrieve the summaries of values based on
categories. They do not permit to retrieve the individual
information.
This allows to access the database to get statistical information
about the number of employees in the company but not to access
the detailed confidential/personal information about the specific
individual employee.
6. Encryption :
This method is mainly used to protect sensitive data (such as credit
card numbers, OTP numbers) and other sensitive numbers. The
data is encoded using some encoding algorithms.
An unauthorized user who tries to access this encoded data will
face difficulty in decoding it, but authorized users are given
decoding keys to decode data.

Authorization
Authorization is a privilege provided by the Database
Administer. Users of the database can only view the contents they
are authorized to view. The rest of the database is out of bounds to
them.

The different permissions for authorizations available are:

 Primary Permission - This is granted to users publicly and


directly.
 Secondary Permission - This is granted to groups and
automatically awarded to a user if he is a member of the group.
 Public Permission - This is publicly granted to all the users.
 Context sensitive permission - This is related to sensitive
content and only granted to a select users.
UNIT V

Distributed and Client Server


Database
Need for Distributed Database System

Below are the needs for the distributed database:

1. Flexibility/Tunability
One of the main reasons for the need for distributed systems is its
Tunability. With the complex nature of organizations and various
transactions that happen every second, it becomes important that the
servers and the application are flexible enough to accommodate their
ever-changing needs without hampering the overall functions of the
database management system. For example, a machine that houses a
web server would service a high volume of small transactions whereas
a database server with a data warehouse would serve the low volume
of large or complex transactions. In distributed database systems
these functions are mutually separated and therefore can be
configured by end-users and developers as per their requirements.

2. Fault Tolerance
Imagine a system where the applications and the server are physically
located on the same computer or system and one of the components
fails and disrupts the entire system! With DDMS since the server and
application are located on a network of computers, failure of a
component doesn’t affect the system as a whole and thus becomes
fault-tolerant which is extremely important especially when used by
large organizations.

3. Security
Since the components of a DDMS are completely independent of each
other both in working and location if one of the components gets
compromised it wouldn’t affect the system as a whole and this greatly
increases the security of the database system.

4. Scalability
As an organization grows, so does its data and need for a better
database management system. With distributed systems,
organizations can scale their existing network of the system easily and
maneuver the system as per their needs.

5. Cost
It costs less to create a network of smaller computers spread across
geographies than a single large computer.

Distributed Database and its Types

A distributed database is basically a database that is not limited to


one system, it is spread over different sites, i.e, on multiple
computers or over a network of computers. A distributed database
system is located on various sites that don’t share physical
components. This may be required when a particular database needs
to be accessed by various users globally. It needs to be managed
such that for the users it looks like one single database.

Types:
1. Homogeneous Database:
In a homogeneous database, all different sites store database
identically. The operating system, database management system, and
the data structures used – all are the same at all sites. Hence, they’re
easy to manage.

2. Heterogeneous Database:
In a heterogeneous distributed database, different sites can use
different schema and software that can lead to problems in query
processing and transactions. Also, a particular site might be
completely unaware of the other sites. Different computers may use a
different operating system, different database application. They may
even use different data models for the database. Hence, translations
are required for different sites to communicate.

Structure of Distributed Databases

There are several different architectures for distributed


database systems, including:

Client-server architecture: In this architecture, clients connect


to a central server, which manages the distributed database system.
The server is responsible for coordinating transactions, managing
data storage, and providing access control.
Peer-to-peer architecture: In this architecture, each site in the
distributed database system is connected to all other sites. Each site
is responsible for managing its own data and coordinating
transactions with other sites.
Federated architecture: In this architecture, each site in the
distributed database system maintains its own independent database,
but the databases are integrated through a middleware layer that
provides a common interface for accessing and querying the data.
Distributed database systems can be used in a variety of
applications, including e-commerce, financial services, and
telecommunications. However, designing and managing a distributed
database system can be complex and requires careful consideration
of factors such as data distribution, replication, and consistency.

Advantages and Disadvantages of DDBMS

Advantages of Distributed Database System :


1) There is fast data processing as several sites participate in request
processing.
2) Reliability and availability of this system is high.
3) It possess reduced operating cost.
4) It is easier to expand the system by adding more sites.
5) It has improved sharing ability and local autonomy.

Disadvantages of Distributed Database System :


1) The system becomes complex to manage and control.
2) The security issues must be carefully managed.
3) The system require deadlock handling during the transaction
processing otherwise
the entire system may be in inconsistent state.
4) There is need of some standardization for processing of distributed
database
system.

Data Replication

Data replication is a process of making the multiple copies of


database available on servers. This is done to achieve distributed
database. This is to minimize the load on the database and provide
better performance to the users.

Types of Data Replication –


1. Transactional Replication – In Transactional replication users
receive full initial copies of the database and then receive updates
as data changes. Data is copied in real time from the publisher to
the receiving database(subscriber) in the same order as they occur
with the publisher therefore in this type of
replication, transactional consistency is
guaranteed. Transactional replication is typically used in server-
to-server environments. It does not simply copy the data changes,
but rather consistently and accurately replicates each change.
2. Snapshot Replication – Snapshot replication distributes data
exactly as it appears at a specific moment in time does not monitor
for updates to the data. The entire snapshot is generated and sent
to Users. Snapshot replication is generally used when data
changes are infrequent. It is bit slower than transactional
because on each attempt it moves multiple records from one end to
the other end. Snapshot replication is a good way to perform initial
synchronization between the publisher and the subscriber.
3. Merge Replication – Data from two or more databases is
combined into a single database. Merge replication is the most
complex type of replication because it allows both publisher and
subscriber to independently make changes to the database. Merge
replication is typically used in server-to-client environments. It
allows changes to be sent from one publisher to multiple
subscribers.
Data Fragmentation

 Fragmentation is a process of dividing the whole or full


database into various subtables or sub relations so that
data can be stored in different systems.
 The small pieces or sub relations or subtables are
called fragments.
 These fragments are called logical data units and are stored at
various sites.
 It must be made sure that the fragments are such that they can
be used to reconstruct the original relation (i.e, there isn’t any
loss of data).
 In the fragmentation process, let’s say, If a table T is
fragmented and is divided into a number of fragments say T1,
T2, T3….TN.
 The fragments contain sufficient information to allow the
restoration of the original table T.
 This restoration can be done by the use of UNION or JOIN
operation on various fragments. This process is called data
fragmentation.
 All of these fragments are independent which means these
fragments can not be derived from others.
 The users needn’t be logically concerned about fragmentation
which means they should not concerned that the data is
fragmented and this is called fragmentation Independence or
we can say fragmentation transparency.

Advantages :
 As the data is stored close to the usage site, the efficiency of the
database system will increase
 Local query optimization methods are sufficient for some queries as
the data is available locally
 In order to maintain the security and privacy of the database
system, fragmentation is advantageous
Disadvantages :
 Access speeds may be very high if data from different fragments
are needed
 If we are using recursive fragmentation, then it will be very
expensive

We have three methods for data fragmenting of a table:

 Horizontal fragmentation
 Vertical fragmentation
 Mixed or Hybrid fragmentation

Client Server Databases


Client Server Architecture

Client-server architecture is a type of computer network where


multiple clients request and receive files and services from a
centralized server over a local or internet connection. A client uses an
application as an interface to connect to the server. After which, the
server processes any further operations and information storage.

Take a look at the image below to better understand this


concept:
How Does the Client-Server Model Work?
The client-server model works in three steps, as you can see
below:

1.The client, such as a workstation or smart phone, connects to the


network using a physical or wireless LAN or internet connection.
2.The client sends various requests to the server in order to submit,
retrieve, or modify the data located on the server.

3.The server processes each client request.

Structure of Client Server systems and its


Advantages

In client server computing, the clients requests a resource and the


server provides that resource. A server may serve multiple clients at
the same time while a client is in contact with only one server.

The different structures for two tier and three tier are given as
follows −
Two - Tier Client/Server Structure
The two-tier architecture primarily has two parts, a client tier and a
server tier.The client tier sends a request to the server tier and the
server tier responds with the desired information.

An example of a two tier client/server structure is a web server. It


returns the required web pages to the clients that requested them.

An illustration of the two-tier client/server structure is as


follows −

Advantages of Two - Tier Client/Server Structure


Some of the advantages of the two-tier client/server structure are −

 This structure is quite easy to maintain and modify.


 The communication between the client and server in the form of
request response messages is quite fast.
Three - Tier Client/Server Structure
The Three- Tier architecture has three layers namely client,
application and data layer. The client layer is the one that requests the
information. In this case it could be the GUI, web interface etc. The
application layer acts as an interface between the client and data
layer. It helps in communication and also provides security. The data
layer is the one that actually contains the required data.
An illustration of the three-tier client/server structure is as
follows −

Advantages of Three - Tier Client/Server Structure


Some of the advantages of the three-tier client/server
structure are −

 The Three - Tier structure provides much better service and fast
performance.
 The structure can be scaled according to requirements without
any problem.
 Data security is much improved in the three tier structure.
INDIRA PRIYADARSHINI GOVERNMENT DEGREE COLLEGE FOR WOMEN,
NAMPALLY - HYDERABAD - 500001
(An Autonomous college of Osmania University)
Re-Accredited by NAAC with ‘A’ Grade
B.Com (CA) II Year Examination
Semester – III
Subject: Computer Applications
RELATIONAL DATABASE MANAGEMENT SYSTEM
Practical Question Bank

H.P.W: 4 Credits: 1
Max Marks: 25M

A. Create a Supplier table as shown below : (for questions from 1 to 10)

Sup_No Sup_Name Item_Supplied Item_Price City


(Primary Key)
S1 Suresh Keyboard 400 Hyderabad
S2 Kiran Processor 8000 Delhi
S3 Mohan Mouse 350 Delhi
S4 Ramesh Processor 9000 Bangalore
S5 Manish Printer 6000 Mumbai
S6 Srikanth Processor 8500 Chennai

1. Write sql query to display the name of suppliers who supply Processors and whose city is Delhi.
2. Write sql query to increase the price of Keyboard by 200.
3. Write sql query to display supplier numbers, Suplier names and itemprice for suppliers in delhi in the
ascending order of itemprice.
4. Write sql query to add a new column called CONTACTNO.

5. Write sql query to delete the record whose itemprice is the lowest of all the items supplied .
6. Create a view on the table which displays only supplier numbers and supplier names.

B. Below are the details of Employees working for a software Company. (For questions from 11 to20)
Create the table called EmpDetails with the below mentioned details.
Eid Ename DOB Designation Salary DOJ
(Primary Key)
E101 Suma 29-Dec-89 Designer 20000 01-Apr-10
E102 Amit 10-Jan-95 Programmer 25000 18-Feb-18
E103 Payal 15-Aug-85 Tester 35000 13-Jun-11
E104 Kiran 20-Apr-90 Programmer 40000 7-Mar-14
E105 Meenal 29-May-83 DBA 50000 9-Dec-11
E106 Sheila 1-May-70 Analyst 60000 25-Sep-18
E107 Swamy 13-Jan-85 Programmer 45000 14-Feb-16
E108 Sushma 22-Dec-76 DBA 45000 31-Jan-12

7. Write sql query to display all the employees whose designation is Programmer.
8. Write sql query to display all the employees whose name ends with ‘a’.
9. Write sql query to display the total salary of all the employees whose designation is
programmer.
10. Write sql query to display all the employee names in upper case.
11. Write sql query to display the details of the employee with highest experience.
12. Write sql query to increase the salaries of employees by 5000 whose designation is DBA.

C. Create the two tables as shown below with the given constraints: (for questions 21 to 30) Table name:
Employee Tablename: Department
Constraints: Eid is Primary key and DeptId is foreign key Constraints: DeptId Primary key Salary
should not be less than 10000 and Dname is NOT NULL

Eid Ename DeptId Designation Salary DOJ DeptId Dname


(Primary Key) (Foreign Key) ( > 10000) (Primary Key)
101 Sudha D2 Clerk 20000 01-Apr-10 D1 Sales
102 David D1 Manager 50000 18-Feb-18 D2 Marketing
103 Preethi D3 Clerk 35000 13-Jun-11 D3 Finance
104 Kiran D1 Salesman 20000 7-Mar-14
105 Meenal D2 Clerk 50000 9-Dec-11
106 Sunitha D3 Manager 60000 25-Sep-18
107 Akhil D3 Clerk 25000 14-Feb-16
108 Sushma D2 Manager 45000 31-Jan-12

13. Write sql query to display the fields Eid, Ename and Dname.
14. Write sql query to sort the employee table in the descending order of salaries.
15. Write sql query to list all the job designations in the employee table without repetitions.
16. Write sql query to display all the employees who joined in the year 2011.
17. Write sql query to display all the employees whose salary is between 30000 and 45000.
18. Write sql query to display all the employee details along with their work experience in the company till
current date.

D. Below are the details of Students enrolled in various course of B.Com (For questions from 31 to 40) Create
the table called Student with the below mentioned details.
Sid Sname DOB State Gender Category Course
(Primary Key)
1001 Neha 29-Dec-02 Telangana F Gen Comp
1002 Arun 10-Jan-02 Telangana M OBC Honors
1003 Payal 15-Aug-01 Maharashtra F Gen Appl
1004 Amrita 20-Apr-02 Karnataka F OBC Honors
1005 Pavan 29-May-03 AndhraPradesh M ExServicemen Comp
1006 Anchal 1-May-03 Gujarat F OBC Comp
1007 Ramya 13-Jan-02 Telangana F Gen Appl
1008 Rakesh 22-Dec-01 AndhraPradesh M Sports Comp

19. Write sql query to display the students who are not from Telangana or AndhraPradesh.
20. Write sql query to create an index on column Sname.
21. Write sql query to display all the female students enrolled under Comp course and who belong to OBC.
22. Write sql query to display the students in the ascending order of their names for each course.
23. Write sql query to delete all the students records who have enrolled for Comp course and who are born
after 2002.
24. Write a sql query to add two new columns Contactno and Email to the existing fields.

E. Create a Table for Library Information : (for questions from 41 to 50) Table name: Library
Constraints: BookId is primary key and BookName is NOT NULL

BookId BookName Author DatePurchased Publisher Price


(Primary Key)
B101 Cost Accounting Jain Narang 11-Feb-13 Kalyani 800
B102 Business Statistics OP Aggarwal 22-Dec-11 Himalaya 750
B103 Rdbms C J Date 2-Mar-15 TMH 900
B104 Mgmt Accounting RK Sharma 19-Apr-16 Kalyani 450
B105 Operating Systems Galvin 25-Nov-13 PHI 750
B106 Advanced Accounting SC Gupta 16-Apr-18 Himalaya 600

25. Write sql query to display the list of authors from Himalaya publications.

26. Write sql query to display the total cost of books purchased Publisher wise.
27. Write sql query to count the total number of books under Kalyani publications.

28. Write sql query to rename the column Publisher as Publications.

29. Write sql query to display the books whose price is between 500 and 700

Write sql query to increase the price of all the books by 200 for publishers other than Himalaya or
Kalyani.
B.Com III Semester (New)
RELATIONAL DATABASE MANAGEMENT SYSTEM
Practical Question Bank Solutions 2023-24

Paper No.DSC 303

Time: 60 Minutes Questions from 1 to 10 for


the Queries given below

SQL> Create table Supplier(snovarchar2(2) primary key,sname varchar2(8), item varchar2(10),price


number(4),city varchar2(10));

SQL> insert into Supplier values('&sno','&sname','&item',&price,'&city');


Enter value for sno: s1
Enter value for sname: Suresh
Enter value for item: Keyboard
Enter value for price: 400
Enter value for city:Hyderabad
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Supplier values('s1','Suresh','Keyboard',400,'Hyderabad')

1 row

created.

SQL> /
Enter value for sno: s2
Enter value for sname: Kiran
Enter value for item: Processor
Enter value for price: 8000
Enter value for city: Delhi
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Supplier values('s2','Kiran','Processor',8000,'Delhi')

1 row

created.

SQL> /
Enter value for sno: s3
Enter value for sname: Mohan
Enter value for item: Mouse
Enter value for price: 350
Enter value for city: Delhi
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Supplier values('s3','Mohan','Mouse',350,'Delhi')

1 row
created.

SQL> /
Enter value for sno: s4
Enter value for sname: Ramesh
Enter value for item: Processor
Enter value for price: 9000
Enter value for city: Banglore
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Suppliervalues('s4','Ramesh','Processor',9000,'Banglore')

1 row
created.
SQL> /
Enter value for sno: s5
Enter value for sname: Manish
Enter value for item: Printer
Enter value for price: 6000
Enter value for city: Mumbai
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Supplier values('s5','Manish','Printer',6000,'Mumbai')

1 row
created.

SQL> /
Enter value for sno: s6
Enter value for sname: Srikanth
Enter value for item: Processor
Enter value for price: 8500
Enter value for city: Chennai
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Supplier values('s6','Srikanth','Processor',8500,'Chennai')

1 row created.

SQL> select *from supplier;

SN SNAME ITEM PRICE CITY


-
s1 Suresh Keyboard 400 Hyderabad
s2 Kiran Processor 8000 Delhi
s3 Mohan Mouse 350 Delhi
s4 Ramesh Processor 9000 Banglore
s5 Manish Printer 6000 Mumbai
s6 Srikanth Processor 8500 Chennai

6 rows selected.

Q1) Write sql query to display supplier numbers and supplier names whose name starts with ‘R’.
SQL> select sno,sname from supplier where sname like 'R%';

SN SNAME

s4 Ramesh

Q2) Write sql query to display the name of suppliers who supply Processors and whose city is Delhi.
SQL> select sname from supplier where item='Processor' and city='Delhi';
SNAME
Kiran
Q3) Write sql query to display the names of suppliers who lsupply the same items as supplied by
Ramesh.
SQL> select sname from supplier where item=(select item from supplier where sname='Ramesh');

SNAME

Kiran
Ramesh
Srikanth

Q4)Writesql query to increase the price of keyboard by 200.


SQL> update supplier set price=price+200 where item='Keyboard';

1 row updated.

SQL> select *from supplier;

SN SNAME ITEM PRICECITY


-
s1 Suresh Keyboard 600 Hyderabad
s2 Kiran Processor 8000 Delhi
s3 Mohan Mouse 350 Delhi
s4 RameshProcessor 9000 Banglore
s5 Manish Printer 6000 Mumbai
s6 Srikanth Processor 8500 Chennai

6 rows selected.

Q5) Write sql query to display supplier numbers, supplier names and item price for suppliers in delhi in
the ascending order of itemprice.
SQL> select sno,sname,price from supplier where city='Delhi' order by price;

SN SNAME PRICE

s3 Mohan 350
s2 Kiran 8000

Q6)Writesql query to add a new column called contact no.


SQL> alter table supplier add(contact number(10));

Table altered.
SQL>desc supplier;
Name Null? Type

SNO NOTNULL VARCHAR2(2)


SNAME VARCHAR2(8)
ITEM VARCHAR2(10)
PRICE NUMBER(4)
CITY VARCHAR2(10)
CONTACT NUMBER(10)
Q7)Writesql query to delete the record whose itemprice is lowest of all the items supplied.
SQL> delete from supplier where price<=(select min(price) from supplier);

1 row deleted.

SQL> select *from supplier;

SN SNAME ITEM PRICE CITY CONTACT

s1 Suresh Keyboard 600 Hyderabad


s2 Kiran Processor 8000 Delhi
s4 Ramesh Processor 9000 Banglore
s5 Manish Printer 6000 Mumbai
s6 Srikanth Processor 8500 Chennai

Q8)Create a view on the table which displays only supplier numbers and supplier names.
SQL> create view supplier_v as select sno,sname from supplier;

View created.

SQL> select *from supplier_v;

SN SNAME

s1 Suresh
s2 Kiran
s4 Ramesh
s5 Manish
s6 Srikanth

Q9)Write sql query to display the records in the descending order of itemprice for each itemsupplied.
SQL> select *from supplier order by price desc;

SN SNAME ITEM PRICE CITY CONTACT

s4 RameshProcessor 9000 Banglore


s6 Srikanth Processor 8500 Chennai
s2 Kiran Processor 8000 Delhi
s5 Manish Printer 6000 Mumbai
s1 Suresh Keyboard 600 Hyderabad

Q10)Write sql query to display the records of suppliers who supply items other than processors or
keyboard.
SQL> select *from supplier where item notin('Processor','Keyboard');

SN SNAME ITEM PRICE CITY CONTACT

s5 Manish Printer 6000 Mumbai


A) Questions from 11 to 20 for the Queries given below

SQL> Create table emp(eidvarchar2(4) primary key, ename varchar2(8), dob date, desg varchar2(10), sal
number(5),doj date);

SQL> insert into empvalues('&eid','&ename','&dob','&desg',&sal,'&doj');


Enter value for eid: e101
Enter value for ename: suma
Enter value for dob: 29-dec-89
Enter value for desg: designer
Enter value for sal: 20000
Enter value for doj: 01-apr-10
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e101','suma','29-dec-89','designer',20000,'01-a pr-10')

1 row created.

SQL> /
Enter value for eid: e102
Enter value for ename: amit
Enter value for dob: 10-jan-95
Enter value for desg:programmer
Enter value for sal:25000
Enter value for doj: 18-feb-18
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e102','amit','10-jan-95','programmer',25000,'18-feb-18')

1 row created.

SQL> /
Enter value for eid: e103
Enter value for ename: payal
Enter value for dob: 15-aug-85
Enter value for desg: tester
Enter value for sal: 35000
Enter value for doj: 13-jun-11
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e103','payal','15-aug-85','tester',35000,'13-Jun-11')

1 row created.

SQL> /
Enter value for eid: e104
Enter value for ename: kiran
Enter value for dob: 20-apr-
90
Enter value for desg:programmer
Enter value for sal:40000
Enter value for doj: 7-mar-14
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e104','kiran','20-apr-90','programmer',40000,'7-mar-14')
1 row created.
SQL> /
Enter value for eid:e105
Enter value for ename: meenal
Enter value for dob:29-may-83
Enter value for desg:dba
Enter value for sal: 50000
Enter value for doj: 9-dec-11
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e105','meenal','29-may-83','dba',50000,'9-dec-11')

1 row created.

SQL> /
Enter value for eid: e106
Enter value for ename: sheila
Enter value for dob: 1-may-70
Enter value for desg: analyst
Enter value for sal: 60000
Enter value for doj: 25-sep-18
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e106','sheila','1-may-70','analyst',60000,'25-s ep-18')

1 row created.

SQL> /
Enter value for eid: e107
Enter value for ename:swamy
Enter value for dob:13-jan-85
Enter value for desg: programmer
Enter value for sal: 45000
Enter value for doj: 14-feb-16
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e107','swamy','13-jan-85','programmer',45000,'14-feb-16')

1 row created.

SQL> /
Enter value for eid:e108
Enter value for ename:sushma
Enter value for dob: 22-dec-76
Enter value for desg:dba
Enter value for sal: 45000
Enter value for doj: 31-jan-12
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e108','sushma','22-dec-76','dba',45000,'31-jan- 12')

1 row created.
SQL> select *from emp;

EID ENAME DOB DESG SAL DOJ

e101 suma 29-DEC-89 designer 20000 01-APR-10


e102 amit 10-JAN-95 programmer 25000 18-FEB-18
e103 payal 15-AUG-85 tester 35000 13-JUN-11
e104 kiran 20-APR-90 programmer 40000 07-MAR-14
e105 meenal 29-MAY-83 dba 50000 09-DEC-11
e106 sheila 01-MAY-70 analyst 60000 25-SEP-18
e107 swamy 13-JAN-85 programmer 45000 14-FEB-16
e108 sushma 22-DEC-76 dba 45000 31-JAN-12

8 rows selected.

Q11)Write sql query to display all the employees whose designation is programmer.
SQL> select *from emp where desg='programmer';

EID ENAME DOB DESG SAL DOJ

e102 amit 10-JAN-95 programmer 25000 18-FEB-18


e104 kiran 20-APR-90 programmer 40000 07-MAR-14
e107 swamy 13-JAN-85 programmer 45000 14-FEB-16

Q12)Write sql query to display employees who have joined after 2014.
SQL> select *from emp where extract(year from doj)>2014;

EID ENAME DOB DESG SAL DOJ

e102 amit 10-JAN-95 programmer 25000 18-FEB-18


e106 sheila 01-MAY-70 analyst 60000 25-SEP-18
e107 swamy 13-JAN-85 programmer 45000 14-FEB-16

Q13)Write sql query to display all the employees whose name ends with ‘a’.
SQL> select *from emp where enamelike'%a';
EID ENAME DOB DESG SAL DOJ

e101 suma 29-DEC-89 designer 20000 01-APR-10


e106 sheila 01-MAY-70 analyst 60000 25-SEP-18
e108 sushma 22-DEC-7 dba 45000 31-JAN-12

Q14)Write sql query to display the total salary of all the employees whose designation is programmer.

SQL> select sum(sal) from emp where desg='programmer';

SUM(SAL)

110000

Q15)Write sql query to display all the employee names in upper case.

SQL> select upper(ename) from emp;


UPPER(ENAME)

SUMA
AMIT
PAYAL
KIRAN
MEENAL
SHEILA
SWAMY
SUSHMA

8 rows selected.

Q16)Write sql query to display the details of the employee with highest experience.

SQL> alter table empadd(experience number(3));

Table altered.

SQL> update emp set experience=extract(year from sysdate)-extract(year from 2 doj);

8 rows updated.

SQL> select *from emp where experience>=(select max(experience) from emp);


EID ENAMEDOB DESG SAL DOJ EXPERIENCE

e101 suma 29-DEC-89 designer 20000 01-APR-10 9

Q17)Write sql query to display the details of the employees whose name contains ‘ee’.

SQL> select *from emp where ename like '%ee%';

EID ENAME DOB DESG SAL DOJ

e105 meenal29-MAY-83 dba 5000009-DEC-11

Q18)Write sql query to increase the salaries of employees by 5000 whose designation is dba.

SQL> update emp set sal=sal+5000 where desg='dba';

2 rows updated.

SQL> select *from emp;

EID ENAME DOB DESG SAL DOJ

e101 suma 29-DEC-89 designer 20000 01-APR-10


e102 amit 10-JAN-95 programmer 25000 18-FEB-18
e103 payal 15-AUG-85 tester 35000 13-JUN-11
e104 kiran 20-APR-90 programmer 40000 07-MAR-14
e105 meenal 29-MAY-83 dba 55000 09-DEC-11
e106 sheila 01-MAY-70 analyst 60000 25-SEP-18
e107 swamy 13-JAN-85 programmer 45000 14-FEB-16
e108 sushma 22-DEC-76 dba 50000 31-JAN-12

8 rows selected.

Q19)Write sql query to display the employees whose salary is more than the average salary of all the
employees.

SQL> select *from emp where sal>(select avg(sal) from emp);

EID ENAME DOB DESG SAL DOJ

e105 meenal 29-MAY-83 dba 5500009-DEC-11


e106sheila 01-MAY-70 analyst 60000 25-SEP-18
e107 swamy 13-JAN-85 programmer 45000 14-FEB-16
e108 sushma 22-DEC-76 dba 5000031-JAN-12

Q20)Write sql query to display the record in the following format:


xxxxxxx is working as xxxxxxxxx with a salary ofRs.xxxxxxxxxx.
eg: Suma is working as Designer with a Salary ofRs.20000

B) Questions from 21 to 30 for the Queries given below

SQL> create table dept(deptid varchar2(2) primary key,dname varchar2(10));


SQL> insert into deptvalues('&deptid','&dname');
Enter value for deptid: d1
Enter value for dname: sales
old 1: insert into dept values('&deptid','&dname')
new 1: insert into dept values('d1','sales')

1 row
created.

SQL> /
Enter value for deptid: d2
Enter value for dname: marketing
old 1: insert into dept values('&deptid','&dname')
new 1: insert into dept values('d2','marketing')

1 row
created.

SQL>.
SQL>/
Enter value for deptid: d3
Enter value for dname: finance
old 1: insert into dept values('&deptid','&dname')
new 1: insert into dept values('d3','finance')

1 row created.
SQL> select *fromdept;
DE DNAME

d1 sales
d2 marketing
d3 finance

SQL> create table employee(eid number(3) primary key,ename varchar2(8),deptid varchar2(2),desg


varchar2(10),sal number(5),dojdate,constraintfke foreign key(deptid) references dept(deptid));

SQL> insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj');


Enter value for eid: 101
Enter value for ename:
sudha Enter value for dept:
d2 Enter value for desg: clerk
Enter value for sal: 20000
Enter value for doj:01-apr-10
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(101,'sudha','d2','clerk',20000,'01-apr-10')

1 row

created.

SQL> /
Enter value for eid: 102
Enter value for ename:david
Enter value for dept:d1
Enter value for desg: manager
Enter value for sal: 50000
Enter value for doj: 18-feb-18
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(102,'david','d1','manager',50000,'18-feb-18 ')

1 row

created.

SQL> /
Enter value for eid:103
Enter value for ename:preethi
Enter value for dept:d3
Enter value for desg: clerk
Enter value for sal: 35000
Enter value for doj: 13-jun-11
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(103,'preethi','d3','clerk',35000,'13-jun-11 ')

1 row
created.

SQL> /
Enter value for eid: 104
Enter value for ename: kiran
Enter value for dept: d1
Enter value for desg: salesman
Enter value for sal: 20000
Enter value for doj: 7-mar-14
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(104,'kiran','d1','salesman',20000,'7-mar-14 ')

1 row created.

SQL> /
Enter value for eid:105
Enter value for ename:meenal
Enter value for dept:d2
Enter value for desg: clerk
Enter value for sal: 50000
Enter value for doj: 9-dec-11
old 1: insert into employee
values(&eid,'&ename','&dept','&desg',&sal,'&doj') new 1: insert into
employee values(105,'meenal','d2','clerk',50000,'9-dec-11') 1 row created.

SQL> /
Enter value for eid:106
Enter value for ename:sunitha
Enter value for dept:d3
Enter value for desg: manager
Enter value for sal: 60000
Enter value for doj: 25-sep-18
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(106,'sunitha','d3','manager',60000,'25-sep- 18')

1 row created.

SQL> /
Enter value for eid: 107
Enter value for ename: akhil
Enter value for dept: d3
Enter value for desg: clerk
Enter value for sal: 25000
Enter value for doj:14-feb-
16
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(107,'akhil','d3','clerk',25000,'14-feb-16')

1 row
created.

SQL> /
Enter value for eid:108
Enter value for ename:sushma
Enter value for dept:d2
Enter value for desg: manager
Enter value for sal: 45000
Enter value for doj: 31-jan-12
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(108,'sushma','d2','manager',45000,'31-jan-1 2')

1 row created.
SQL> select *from employee;

EIDENAME DE DESG SAL DOJ

101sudha d2 clerk 2000001-APR-10


102 david d1 manager 50000 18-FEB-18
103 preethi d3 clerk 35000 13-JUN-11
104 kiran d1 salesman 20000 07-MAR-14
105 meenal d2 clerk 50000 09-DEC-11
106 sunitha d3 manager 60000 25-SEP-18
107 akhil d3 clerk 25000 14-FEB-16
108 sushma d2 manager 45000 31-JAN-12

8 rowsselected.

21)Writesqlquerytodisplayalltheemployeeswhoearnmorethanaveragesalaryofalltheemployees in
thecompany.

SQL> select *from employee where sal>=(select avg(sal) from employee);

EIDENAME DE DESG SAL DOJ

102david d1 manager 50000 18-FEB-18


105 meenal d2 clerk 50000 09-DEC-11
106 sunitha d3 manager 60000 25-SEP-18
108 sushma d2 manager 45000 31-JAN-12

Q22)Write sql query to display the fields eid, ename and dname.

SQL> select eid,ename,dname from employee e,dept d where e.deptid=d.deptid;

EID ENAME DNAME

101 sudha marketing


102 david sales
103 preethi finance
104 kiran sales
105 meenal marketing
106 sunitha finance
107 akhil finance
108 sushma marketing

8 rows selected.

Q23)Write sql query to sort the employee table in the descending order of salaries.

SQL> select *from employee order by saldesc;

EID ENAME DEDESG SALDOJ


106 sunitha d3 manager 60000 25-SEP-18
102 david d1 manager 50000 18-FEB-18
105 meenal d2 clerk 50000 09-DEC-11
108 sushma d2 manager 45000 31-JAN-12
103 preethi d3 clerk 35000 13-JUN-11
107 akhil d3 clerk 25000 14-FEB-16
101 sudha d2 clerk 20000 01-APR-10
104 kirand1 salesman 20000 07-MAR-14 8

rows selected.

Q24)Write sql query to list all the job designations in the employee table without repetitions.

SQL> select desg from employee group by desg;

DESG

salesman
clerk
manager

Q25)Writesql query to display all the employee details department wise and in the ascending order. SQL>
select *from employee e,dept d where e.deptid=d.deptid order by dname;

EID ENAME DE DESG SAL DOJ DE DNAME


107 akhil d3 clerk 14-FEB-16 d3 finance
25000
103 preethi d3 clerk 35000 13-JUN-11 d3 finance
106 sunitha d3 manager 60000 25-SEP-18 d2 finance
101 sudha d2 clerk 20000 01-APR- d2 marketing
10
108 sushma d2 manager 45000 31-JAN-12 d2 marketing
105 meenal d2 clerk 50000 09-DEC-11 d2 marketing
102 david d1 manager 50000 18-FEB-18 d1 sales
104 kiran d1 salesman 20000 07-MAR- d1 sales
14

8 rows selected.

Q26)Write sql query to display all the clerks in deptid d2.

SQL> select *from employee where deptid='d2' anddesg='clerk';

EIDENAME DE DESG SAL DOJ

101 sudha d2 clerk 20000 01-APR-10


105meenal d2 Clerk 50000 09-DEC-11

Q27)Write sql query to display all the employees who joined in the year 2011.
SQL> select *from employee where doj between '01-jan-2011' and '31-dec-

2011'; EIDENAME DE DESG SAL DOJ

103 preethi d3 clerk 35000 13-JUN-11


105 meenal d2 clerk 50000 09-DEC-11

Q28)Write sql query to display all the employees who joined in the month of February.

SQL> select *from employee e where extract(month from e.doj)=2;

EID ENAME DE DESG SAL DOJ


102 David d1 Manager 50000 18-FEB-18
107 Akhil d3 Clerk 25000 14-FEB-16

Q29)Writesqlquerytodisplayalltheemployeeswhosesalaryisbetween30000and45000. SQL> select

*from employee where sal between 30000 and45000;

EID ENAME DE DESG SAL DOJ


103 Preethi d3 Clerk 35000 13-JUN-11
108 Sushma d2 Manager 45000 31-JAN-12

Q30) Write sql query to display all the employee details along with their work experience in the
company till current date.

SQL> select eid,ename,deptid,desg,sal,doj,extract(year from sysdate)-extract(


2 year from doj) as experience from employee;
EID ENAME DE DESG SAL DOJ EXPERIENCE
101 sudha d2 Clerk 20000 01-APR-10 9
102 david d1 Manager 50000 18-FEB-18 1
103 preethi d3 clerk 35000 13-JUN-11 8
104 kiran d1 salesman 20000 07-MAR-14 5
105 meenal d2 clerk 50000 09-DEC-11 8
106 sunitha d3 manager 60000 25-SEP-18 1
107 akhil d3 clerk 25000 14-FEB-16 3
108 sushma d2 manager 45000 31-JAN-12 7
8 rows selected.

C) Questions from 31 to 40 for the Queries given below


SQL> create table std(sid number(4) primary key,sname varchar2(8),dob date, state varchar2(15),gender
varchar2(1),category varchar2(15),course varchar2(8));

SQL> insert into stdvalues(&sid,'&sname','&dob','&state','&gender','&category', &course');


Enter value for sid: 1001
Enter value for sname: neha
Enter value for dob: 29-dec-02
Enter value for state:
telanganaEnter value for
gender: f
Enter value for category: gen
Enter value for course: comp
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1001,'neha','29-dec-02','telangana','f','gen','comp')

1 row

created.

SQL> /
Enter value for sid: 1002
Enter value for sname: arun
Enter value for dob: 10-jan-02
Enter value for state: telangana
Enter value for gender: m
Enter value for category: obc
Enter value for course:honors
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1002,'arun','10-jan-02','telangana','m','obc','honors')

1 row
created.

SQL> /
Enter value for sid: 1003
Enter value for sname: payal
Enter value for dob: 15-aug-01
Enter value for state: maharashtra
Enter value for gender: f
Enter value for category: gen
Enter value for course: appl
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1003,'payal','15-aug-01','maharashtra','f','gen','appl')

1 row
created.

SQL> /
Enter value for sid: 1004
Enter value for sname: amrita
Enter value for dob:20-apr-02
Enter value for state: karnataka
Enter value for gender: f
Enter value for category: obc
Enter value for course:honors
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1004,'amrita','20-apr-02','karnataka','f','obc', 'honors')

1 row

created.
SQL> /
Enter value for sid: 1005
Enter value for sname: pavan
Enter value for dob: 29-may-03
Enter value for state: andhrapradesh
Enter value for gender: m
Enter value for category:
exservicemenEnter value for course:
comp
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1005,'pavan','29-may-03','andhrapradesh','m','ex servicemen','comp')

1 row created.

SQL> /
Enter value for sid: 1006
Enter value for sname: anchal
Enter value for dob: 01-may-01
Enter value for state: gujarat
Enter value for gender: f
Enter value for category: obc
Enter value for course: comp
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1006,'anchal','01-may-01','gujarat','f','obc','comp')

1 row
created.

SQL> /
Enter value for sid: 1007
Enter value for sname: ramya
Enter value for dob:13-jan-02
Enter value for state: telangana
Enter value for gender: f
Enter value for category: gen
Enter value for course: appl
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1007,'ramya','13-jan-02','telangana','f','gen',' pl')

1 row
created.

SQL> /
Enter value for sid: 1008
Enter value for sname:rakesh
Enter value for dob: 22-dec-01
Enter value for state: andhrapradesh
Enter value for gender: m
Enter value for category: sports
Enter value for course: comp
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1008,'rakesh','22-dec-01','andhrapradesh','m','sports','comp')

1 row created.

SQL> select *from std;


SIDSNAMEDOB STATE GCATEGORY COURSE
- - -
1001 neha 29-DEC-02 telangana f gen comp
1002 arun 10-JAN-02 telangana m obc honors
1003 payal 15-AUG-01 maharashtra f gen appl
1004 amrita 20-APR-02 karnataka f obc honors
1005 pavan 29-MAY-03 andhrapradesh m exservicemen comp
1006 anchal 01-MAY-01 gujarat f obc comp
1007 ramya 13-JAN-02 telangana f gen appl
1008 rakesh 22-DEC-01 andhrapradesh m sports comp

8 rows selected.

Q31)Writesql query to display the students who are not from telangana or Andhra Pradesh.

SQL> select *from std where state not in('telangana','andhrapradesh');

SIDSNAME DOB STATE G CATEGORY COURSE


- - -
1003 payal 15-AUG-01 maharashtra f gen appl
1004 amrita 20-APR-02 karnataka f obc honors
1006 anchal 01-MAY-01 gujarat f obc comp

Q32)Create a view to display the columns sid, sname for students belonging to telangana.

SQL> create view std_telangana as select sid,sname from std where state in2 ('telangana');

View created.

SQL> select *Fromstd_telangana;


SID SNAME

1001 neha
1002 arun
1007 ramya

Q33)Writesql query to create an index on column sname.

SQL> create index sindex on std(sname);Index created.

Q34)Write sql query to display all the female students enrolled under comp course and who belong to
obc.

SQL> select *Fromstd where gender='f' and category='obc' and course='comp';

SIDSNAME DOB STATE G CATEGORY COURSE


- - -
1006 anchal 01-MAY-01 gujarat f obc comp

Q35)Writesql query to display the student ids, names and their present age.

SQL> select sid,sname,extract(year from sysdate)-extract(year from dob) as 2 age from


std; SIDSNAME AGE

1001 neha 17
1002 arun 17
1003 payal 18
1004 amrita 17
1005 pavan 16
1006 anchal 18
1007 ramya 17
1008 rakesh 18

8 rows selected.

Q36)Writesql query to display the students in the ascending order of their names from each course.

Q37)Writesql query to delete all the students records who have enrolled for comp course and who are
born after 2002.
SQL> delete from std where course='comp' and extract(year from dob)>2002;

1 row deleted.

Q38)Writesql query to add two new columns contactno and email to the existing fields.

SQL> alter table stdadd(contactno number(10),email varchar2(15));

Table altered.

SQL>descstd;
Name Null? Type

SID NOT NULL NUMBER(4)


SNAME VARCHAR2(8)
DOB DATE

STATE VARCHAR2(15)
GENDER VARCHAR2(1)
CATEGORY VARCHAR2(15)
COURSE VARCHAR2(8)
CONTACTNO NUMBER(10)
EMAIL VARCHAR2(15)

Q39)Write an sql query to display all the student names prefixed with Mr./Ms. Based on gender column.

Q40)Write an sql query to display all the student names where the length of the name is 5 characters.

SQL> select sname from std where length(sname)<=5;

SNAME

nehaa
runpa
yalra
mya
D) Questions from 41 to 50 for the Queries given below

SQL> create table library(bookid varchar2(4) primary key,bookname varchar2(20),author


varchar2(15),purchased date,publisher varchar2(10),price number(3));

SQL> insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price);


Enter value for bookid: b101
Enter value for bookname: costaccounting
Enter value for author: jainnarang
Enter value for purchased: 11-feb-13
Enter value for publisher: kalyani
Enter value for price: 800
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b101','costaccounting','jainnarang','11-feb-13','kalyani',800)

1 row

created.

SQL> /
Enter value for bookid: b102
Enter value for bookname: businessstatistics
Enter value for author: opaggarwal
Enter value for purchased: 22-dec-11
Enter value for publisher: himalaya
Enter value for price: 750
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b102','businessstatistics','opaggarwal','22-dec-11','himalaya',750)

1 row

created.

SQL> /
Enter value for bookid: b103
Enter value for bookname: rdbms
Enter value for author: cjdate
Enter value for purchased: 2-mar-15
Enter value for publisher: tmh
Enter value for price: 900
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b103','rdbms','cjdate','2-mar-15','tmh',900)

1 row
created.

SQL> /
Enter value for bookid: b104
Enter value for bookname: mgmtaccounting
Enter value for author: rksharma
Enter value for purchased: 19-apr-16
Enter value for publisher: kalyani
Enter value for price: 450
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b104','mgmtaccounting','rksharma','19-apr-1 ','kalyani',450)
1 row created.

SQL> /
Enter value for bookid: b105
Enter value for
bookname:operatingsystemEnter value for
author:galvin
Enter value for purchased:25-nov-13
Enter value for publisher:phi
Enter value for price: 750
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b105','operatingsystem','galvin','25-nov-13 ','phi',750)

1 row
created.

SQL> /
Enter value for bookid: b106
Enter value for bookname:
advanceaccounting Enter value for author:
scgupta
Enter value for purchased: 16-apr-18
Enter value for publisher: himalaya
Enter value for price: 600
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b106','advanceaccounting','scgupta','16-apr-18','himalaya',600)
1 row created.

SQL> select *from library;

BOOK BOOKNAME AUTHOR PURCHASED PUBLISHER PRICE


-
b101 costaccounting jainnarang 11-FEB-13 kalyani 800
b102 businessstatistics opaggarwal 22-DEC-11 himalaya 750
b103 rdbms cjdate 02-MAR-15 tmh 900
b104 mgmtaccounting rksharma 19-APR-16 kalyani 450
b105 operatingsystem galvin 25-NOV-13 phi 750
b106 advanceaccounting cgupta 16-APR-18 himalaya 600

6 rows selected.

Q41)Writesql query to display the list of authors from Himalaya publications.

SQL> select author From library where publisher='himalaya';


AUTHOR
opagarwals
cgupta

Q42)Writesql query to display the total cost of books purchased publisher wise.

SQL> select sum(price),publisher from library group by publisher;

SUM(PRICE) PUBLISHER

1250 kalyani
900 tmh
1350 himalaya
750 phi
Q43)Writesql query to count the total number of books under kalyani publications.

SQL> select count(*) from library where publisher='kalyani';

COUNT(*)

Q44)Writesql query to rename the column publisher as publications.

SQL> alter table library rename column publisher to publications;

Table altered.

SQL>desc library;
Name Null? Type

BOOKID NOT NULL VARCHAR2(4)


BOOKNAME VARCHAR2(20)
AUTHOR VARCHAR2(15)
PURCHASED DATE
PUBLICATIONS VARCHAR2(10)
PRICE NUMBER(3)

Q45)Write a sql query to display the books in the ascending order of date purchased.

SQL> select *From library order by purchased;

BOOK BOOKNAME AUTHOR PURCHASED PUBLICATIO PRICE


-
b102 business statistics opagarwal 22-DEC-11 himalaya 750
b101 cost accounting jainnarang 11-FEB-13 kalyani 800
b105 operating system galvin 25-NOV-13 phi 750
b103 rdbm cj date 02-MAR-15 tmh 900

b104 mgmt accounting rksharma 19-APR-16 kalyani 450


b106 advanced accounting scgupta 16-APR-18 himalaya 600

6 rows selected.

Q46)Write sql query to create an index on the fields book name and author.

SQL> create index lib_index on library(bookname,author);

Index created.

Q47)Write sql query to display the books whose price is between 500 and 700.

SQL> select *From library where price between 500 and 700;

BOOK BOOKNAME AUTHOR PURCHASED PUBLICATIO PRICE


- b106
advancedaccounting scgupta 16-APR-18 himalaya 600

Q48)Write sql query to increase the price of all the books by 200 for publishers other than himalaya or
kalyani.

SQL> update library set price=price+200 where publications not in ('himalaya',

'kalyani'); 2 rows updated.

SQL> select *From library;

BOOK BOOKNAME AUTHOR PURCHASED PUBLICATIO PRICE


-
b101 cost accounting jainnarang 11-FEB-13 kalyani 800
b102 business statistics opagarwal 22-DEC-11 himalaya 750
b103 rdbms cjdate02-MAR-15 tmh 1100
b104 mgmt accounting rksharma 19-APR-16 kalyani 450
b105 operating system galvin 25-NOV-13 phi 950
b106 advanced accounting scgupta 16-APR-18 himalaya 600

6 rows selected.

Q49)Writesql query to display the book details where author name contains the name sharma.

SQL> select *From library where author like '%sharma%';

BOOK BOOKNAME AUTHOR PURCHASED PUBLICATIO PRICE


- b104
mgmt accounting rkSharma 19-APR-16 kalyani 450

Q50)Create a view to display the fields bookid and bookname where the publisher is
Himalaya. SQL> create view library_himalaya as select bookid,bookname from library where
2 publications in ('himalaya');

View created.

SQL> select *from

library_himalaya; BOOK

BOOKNAME

b102 business statistics


b106

advancedaccounting

You might also like