0% found this document useful (0 votes)
90 views44 pages

Dbms Module-2 (Mmc103)

The document provides an overview of Relational Algebra, a formal system for querying relational databases, including its basic concepts such as relations, tuples, and attributes. It details unary operations like selection, projection, and renaming, as well as binary operations including union, intersection, difference, Cartesian product, and various types of joins. The document illustrates these operations with examples and SQL equivalents, emphasizing their application in managing and querying data effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views44 pages

Dbms Module-2 (Mmc103)

The document provides an overview of Relational Algebra, a formal system for querying relational databases, including its basic concepts such as relations, tuples, and attributes. It details unary operations like selection, projection, and renaming, as well as binary operations including union, intersection, difference, Cartesian product, and various types of joins. The document illustrates these operations with examples and SQL equivalents, emphasizing their application in managing and querying data effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DATABASE MANAGEMENT SYSTEM (MMC103)

MODULE-2
Relational Algebra and Overview of the SQL Query Language
Introduction to Relational Algebra

Relational Algebra is a formal system for manipulating and querying relational databases. It
provides a set of operations that take one or more relations (tables) as input and produce a new
relation as output. Relational algebra is the theoretical foundation of relational databases and is
used for querying and managing data.

It was introduced by Edgar F. Codd in 1970 as part of his relational model for databases. The
main purpose of relational algebra is to offer a theoretical framework for querying databases,
ensuring that operations on data follow a set of principles that make querying efficient and logical.

Basic Concepts

 Relation: A relation is essentially a table in a database. It consists of a set of tuples (rows)


and attributes (columns). Each relation represents a different entity in the database (e.g.,
employees, departments).
 Tuple: A tuple is a single row in a relation, which contains a set of values corresponding to
the relation’s attributes.
 Attribute: An attribute is a column in a relation, representing a property or characteristic of
the entity represented by the relation.

In relational algebra, operations are used to manipulate relations (tables). These operations can be
classified into two types based on the number of relations they operate on: unary and binary
operations.

1. Unary Operations
Unary operations in relational algebra are operations that operate on only one relation at a time.
These operations are applied to a single relation and produce a new relation as the result.

Some common unary operations in relational algebra include:

a. SELECTION (σ):
o The selection operation is used to filter rows from a relation based on a given
condition.
o It selects a subset of rows that satisfy a specified predicate.
o Syntax: σ <selection condition> (Relation)

where,
 The symbol σ(sigma) is used to denote the SELECT operator
 The selection condition is a Boolean (conditional) expression specified on the attributes of
relation R
 Tuples that make the condition true are selected
 appear in the result of the operation
 Tuples that make the condition false are filtered out
 discarded from the result of the operation

Prof.Kallappa Huddar,VTU Belagavi Page 1


DATABASE MANAGEMENT SYSTEM (MMC103)

Examples:
1. Select the EMPLOYEE tuples whose department number is 4.
σDNO = 4 (EMPLOYEE)

would to the following SQL query:


SELECT * FROM EMPLOYEE WHERE Dno=4;

2. Select the employee tuples whose salary is greater than $30,000.


σSALARY > 30,000 (EMPLOYEE)

would to the following SQL query:


SELECT * FROM EMPLOYEE WHERE Salary>30000;

3. Select the tuples for all employees who either work in department 4 and make over
$25,000 per year, or work in department 5 and make over $30,000
σ (Dno=4 AND Salary>25000) (EMPLOYEE)

would to the following SQL query:


SELECT * FROM EMPLOYEE WHERE Dno=4 AND Salary>25000;

b. PROJECTION (π):
o The projection operation is used to select specific columns from a relation.
o It removes duplicate rows and keeps only the specified attributes.
o Syntax: π <attribute list> (Relation)

where
 symbol π (pi)used to represent the PROJECT operation
 <attributelist> - desired sublist of attributes from the attributes of relation R.
 The result of the PROJECT operation has only the attributes specified in <attribute
list> in the same order as they appear in the list. Hence, its degree is equal to the
number of attributes in <attribute list>
Example:

 π Name,Age(Employees)
 would to the following SQL query:
SELECT Name, Age FROM Employees;

This means we are selecting the Name and Age columns from the Employees relation
and removing any duplicate rows.

Result of Projection:
Name Age
Alice 30
Bob 25
Charlie 28
David 35
Eve 29

Prof.Kallappa Huddar,VTU Belagavi Page 2


DATABASE MANAGEMENT SYSTEM (MMC103)

c. RENAMING (ρ):
o The renaming operation is used to rename the attributes of a relation or even the
entire relation.
o This is useful when we need to avoid ambiguity or for clarity in further operations.
o Syntax: ρ_new_relation_name(new_attribute1, new_attribute2)(Relation)

Where:

 Symbol ρ(rho) used to represent the RENAME operation


 new_relation_name: The new name for the relation (table).
 new_attribute1, new_attribute2, ...: The new names for the attributes
(columns) of the relation.
 Relation: The original relation (table) that you want to rename.

Example:

ρ(Emp, Employee_Name, Employee_Age, Employee_Department)(Employees)

would to the following SQL query:


SELECT Name AS Employee_Name,
Age AS Employee_Age,
Department AS Employee_Department
FROM Employees AS Emp;
This operation would rename the Employees relation to Emp, and rename the attributes as
follows:
 Name → Employee_Name
 Age → Employee_Age
 Department → Employee_Department

Original Relation: Employees


Employee_ID Name Age Department
101 Alice 30 HR
102 Bob 25 IT
103 Charlie 28 IT
104 David 35 HR
105 Eve 29 Marketing

Result of SQL Query:

Employee_Name Employee_Age Employee_Department


Alice 30 HR
Bob 25 IT
Charlie 28 IT
David 35 HR
Eve 29 Marketing

Prof.Kallappa Huddar,VTU Belagavi Page 3


DATABASE MANAGEMENT SYSTEM (MMC103)

2. Binary Operations

Binary operations in relational algebra involve two relations. These operations combine, compare,
or relate two different relations to produce a new relation as the result.

Some common binary operations in relational algebra include:

A. UNION (∪):

 The union operation combines the tuples of two relations, eliminating duplicate
tuples. Both relations must have the same number of attributes and corresponding
attributes must have the same domain.
 Syntax: Relation1 ∪ Relation2

B. INTERSECTION (∩):

 The intersection operation returns the tuples that appear in both relations. Similar to
union, the two relations must have the same number of attributes.
 Syntax: Relation1 ∩ Relation2

C. DIFFERENCE/MINUS (−):

 The difference operation returns the tuples that are in the first relation but not in the
second relation.
 Syntax: Relation1 − Relation2

Example: Consider the following two relations: STUDENT & INSTRUCTOR

Prof.Kallappa Huddar,VTU Belagavi Page 4


DATABASE MANAGEMENT SYSTEM (MMC103)

Prof.Kallappa Huddar,VTU Belagavi Page 5


DATABASE MANAGEMENT SYSTEM (MMC103)

D. CARTESIAN PRODUCT (×):

 The Cartesian product operation combines every tuple from the first relation with every
tuple from the second relation. This results in a relation that contains all possible pairs
of tuples from the two relations.
 Syntax: Relation1 × Relation2

Employees: Departments:

Employee_ID Name Age Department Department_ID Department_Name


101 Alice 30 HR 1 HR
2 IT
102 Bob 25 IT

Example: Employees × Departments

Let’s consider Employees and Departments:

Employee_ID Name Age Department Department_ID Department_Name


101 Alice 30 HR 1 HR
101 Alice 30 HR 2 IT
102 Bob 25 IT 1 HR
102 Bob 25 IT 2 IT

E. JOIN (⨝):

In relational algebra, the join operation combines two relations based on a common attribute
or condition. This operation allows you to merge tuples from different relations in a
meaningful way, creating new relations. There are several types of joins in relational algebra,
each serving different purposes for combining data from multiple relations.

Types of Joins in Relational Algebra

1. Theta Join (⨝θ)


2. Equi Join (⨝eq)
3. Natural Join (⨝)
4. Outer Joins (Left Outer Join, Right Outer Join, Full Outer Join)

Prof.Kallappa Huddar,VTU Belagavi Page 6


DATABASE MANAGEMENT SYSTEM (MMC103)

1. Theta Join (⨝θ)

A Theta Join is the most general type of join. It allows you to combine tuples from two relations
based on a condition (θ) that can be any comparison operator, such as =, >, <, !=, etc.

The condition can be any boolean expression that compares attributes from the two relations, not
necessarily equality.

Syntax: Relation1 ⨝θ <join condition>Relation2

Example:

Let’s consider two relations:

Employees: Departments:

Employee_ID Name Age Department_ID Department_ID Min_Age


101 Alice 30 1
1 25
102 Bob 40 2
2 35
103 Charlie 28 1

Relational Algebra: Employees ⨝ (Employees.Age > Departments.Min_Age) Departments

Employee_ID Name Age Department_ID Min_Age

102 Bob 40 2 35

Prof.Kallappa Huddar,VTU Belagavi Page 7


DATABASE MANAGEMENT SYSTEM (MMC103)

2. Equi Join (⨝eq)

An Equi Join is a special case of the Theta Join where the condition is specifically an equality
condition (=) between attributes from both relations.

The condition used in an equi join is always equality (=) between attributes from the two
relations.

Syntax: Relation1 ⨝eq Relation2

Example:

Consider the following relations:

Employees: Departments:

Employee_ID Name Department_ID Department_ID Department_Name


101 Alice 1 1 HR
102 Bob 2
2 IT
103 Charlie 1

Relational Algebra: Employees ⨝eq Departments

Employees.Department_ID = Departments.Department_ID:

Employee_ID Name Department_ID Department_Name

101 Alice 1 HR

102 Bob 2 IT

103 Charlie 1 HR

Prof.Kallappa Huddar,VTU Belagavi Page 8


DATABASE MANAGEMENT SYSTEM (MMC103)

3. Natural Join (⨝)

A Natural Join is a type of Equi Join, but with two key differences:

1. It automatically joins the two relations on all attributes with the same name.
2. It removes duplicate columns that are common between the two relations.

The condition is based on equality of all common attributes between the two relations, and it
automatically eliminates duplicate columns in the result.

Syntax: Relation1 ⨝ Relation2

Example:

Let’s consider the following relations:

Employees: Departments:

Employee_ID Name Department_ID Department_ID Department_Name


101 Alice 1 1 HR
102 Bob 2
2 IT
103 Charlie 1

Relational Algebra: Employees ⨝ Departments

Employee_ID Name Department_ID Department_Name

101 Alice 1 HR

102 Bob 2 IT

103 Charlie 1 HR

4. Outer Joins
Outer joins are extensions of the join operation that include unmatched tuples from one or both
relations in the result. There are three types of outer joins:

A. Left Outer Join (⨝L)


B. Right Outer Join (⨝R)
C. Full Outer Join (⨝F)

Prof.Kallappa Huddar,VTU Belagavi Page 9


DATABASE MANAGEMENT SYSTEM (MMC103)

A. Left Outer Join (⨝L)

A left outer join returns all tuples from the left relation (Relation1), and the matching tuples from
the right relation (Relation2). If there is no match, the result will contain NULL values for
attributes of the right relation.

Syntax: Relation1 ⨝L Relation2


Example: Let’s perform a left outer join on Employees and Departments, assuming that some
employees may not belong to any department.

Employees: Departments:

Employee_ID Name Department_ID Department_ID Department_Name


101 Alice 1
1 HR
102 Bob 2
2 IT
103 Charlie 3

Relational Algebra: Employees ⨝L Departments


Employee_ID Name Department_ID Department_Name
101 Alice 1 HR
102 Bob 2 IT
103 Charlie 3 NULL

B. Right Outer Join (⨝R)

A right outer join returns all tuples from the right relation (Relation2), and the matching tuples
from the left relation (Relation1). If there is no match, the result will contain NULL values for
attributes of the left relation.

Syntax: Relation1 ⨝R Relation2

Relational Algebra: Employees ⨝R Departments


Employee_ID Name Department_ID Department_Name

101 Alice 1 HR

102 Bob 2 IT

NULL NULL 3 IT

Prof.Kallappa Huddar,VTU Belagavi Page 10


DATABASE MANAGEMENT SYSTEM (MMC103)

C. Full Outer Join (⨝F)


A full outer join combines the results of both left outer join and right outer join. It returns all
tuples from both relations. If there is no match, the result will contain NULL values for attributes
from the relation that does not have a match.
Syntax: Relation1 ⨝F Relation

Relational Algebra: Employees ⨝F Departments

Employee_ID Name Department_ID Department_Name


101 Alice 1 HR
102 Bob 2 IT
103 Charlie 3 NULL
NULL NULL 3 IT

Let's combine selection (σ) and projection (π) operations with the binary operations (union,
intersection, difference) in relational algebra to see how these can be applied together. This will
allow us to filter data (selection) and choose specific columns (projection) while combining or
manipulating relations.

1. Selection (σ) and Union (∪)

Selection (σ) is used to filter rows based on a condition, and Union (∪) combines all tuples from
two relations. When combined, you can filter data first, then perform a union operation between
two filtered relations.
Example:Let's assume you have two relations:

Employees: Contractors:

Employee_ID Name Age Department Employee_ID Name Age Department


101 Alice 30 HR 103 Charlie 28 IT
104 David 35 HR
102 Bob 25 IT 105 Eve 29 Marketing
103 Charlie 28 IT
104 David 35 HR

Relational Algebra: σ(Age > 30)(Employees) ∪ σ(Department = 'IT')(Contractors)

Employee_ID Name Age Department

104 David 35 HR

103 Charlie 28 IT

105 Eve 29 Marketing

Prof.Kallappa Huddar,VTU Belagavi Page 11


DATABASE MANAGEMENT SYSTEM (MMC103)

2. Selection (σ) and Intersection (∩)

The intersection (∩) operation returns tuples that are common in both relations. By combining it
with selection (σ), you can first filter relations, then find the intersection of the filtered results.

Example: Let’s select employees older than 30 and contractors from the HR department, and then
find the common tuples between these two relations.

Relational Algebra: σ(Age > 30)(Employees) ∩ σ(Department = 'HR')(Contractors)

Employee_ID Name Age Department


104 David 35 HR

3. Selection (σ) and Difference (−)

The difference (−) operation returns tuples that are in the first relation but not in the second. By
applying selection first, you can filter the data before performing the difference.

Example: Let’s find employees who are older than 30 but not contractors in the IT department.
Relational Algebra: σ(Age > 30)(Employees) − σ(Department = 'IT')(Contractors)

Employee_ID Name Age Department


104 David 35 HR

Division Operation in Relational Algebra


The Division operation in relational algebra is used to handle queries that involve finding tuples from one
relation that are related to all tuples in another relation. It is a bit more specialized than other operations
like Selection or Union. Division is typically used to solve queries like "find all employees who work in all
departments" or "retrieve all products that have been supplied by every supplier."

Concept of Division
In simple terms, division is used when you want to retrieve rows from one relation that are associated with
all tuples in another relation. It is applied between two relations: one representing the dividend (the relation
from which you want to select) and the other representing the divisor (the relation whose tuples must be
fully matched with those in the dividend).

The result of a division operation is a new relation that contains all tuples from the dividend relation that are
associated with every tuple in the divisor relation.
Syntax: Dividend ÷ Divisor
Where:
 Dividend is the relation containing the tuples you are interested in.
 Divisor is the relation whose tuples should be matched against all tuples in the dividend.

Prof.Kallappa Huddar,VTU Belagavi Page 12


DATABASE MANAGEMENT SYSTEM (MMC103)

Steps Involved in Division

1. Projection: First, you project the attributes from the dividend that are not present in the
divisor. These are the attributes you are interested in finding.
2. Difference: Then, you find the tuples in the dividend that have all the corresponding values
in the divisor.

Example of Division
Let's take an example to better understand how division works.

Relation 1 (Employee_Department): This relation contains tuples where each employee is


associated with a department they work in.

Employee_ID Department_ID
1 D1
1 D2
2 D1
2 D2
3 D1

Relation 2 (Departments): This relation contains the departments we are interested in.

Department_ID
D1
D2

Problem: Find all employees who work in all departments (i.e., both D1 and D2).

Solution using Division:


We can perform the Division operation to find the employees who work in both D1 and D2.

Step 1: Project the attributes of the Employee_Department relation that are not in the
Departments relation. Here, the only attribute we care about is Employee_ID.
Step 2: Divide Employee_Department by Departments.

Relational Algebra: Employee_Department ÷ Departments

Employee_ID
1
2

Explanation:

 Employee 1 works in both D1 and D2.


 Employee 2 works in both D1 and D2.
 Employee 3 only works in D1 and is excluded from the result because they do not work in
D2.

Prof.Kallappa Huddar,VTU Belagavi Page 13


DATABASE MANAGEMENT SYSTEM (MMC103)

Overview of Relational Calculus


Relational Calculus is a non-procedural query language used in relational databases. Unlike
relational algebra, which uses operations like selection, projection, and join to manipulate
relations, relational calculus focuses on specifying the what (i.e., what data we want) rather than
the how (i.e., how to retrieve it). It’s based on predicate logic and defines queries in terms of
mathematical predicates.
There are two types of relational calculus:
1. Tuple Relational Calculus (TRC)
2. Domain Relational Calculus (DRC)

1. Tuple Relational Calculus (TRC)

Tuple Relational Calculus (TRC) is a form of relational calculus where queries are
expressed in terms of tuples (rows) of a relation. It uses variables that represent tuples and
specifies conditions (predicates) that must be satisfied for the tuples in the result set.

Syntax: {T | P (T)}

Where:

 T represents a tuple variable.


 P(T) is a predicate or condition that specifies the constraints on the tuple variables.

A tuple variable T can range over a relation (table), and P(T) is a logical expression that must be
satisfied for the tuples that appear in the result.

Example: Consider a relation Employees with the following schema:

Employee_ID Name Age Department_ID


101 Alice 30 1
102 Bob 40 2
103 Charlie 28 1
104 David 50 2

Suppose we want to find the names of employees who are older than 30.

Relational Calculus (TRC) query: { T.Name | T ∈ Employees AND T.Age > 30 }

Explanation:

 T.Name is the attribute we want to retrieve (the name of the employee).


 T ∈ Employees means that T is a tuple in the Employees relation.
 T.Age > 30 is the condition specifying that the employee’s age must be greater than 30.

Name
Bob
David

Prof.Kallappa Huddar,VTU Belagavi Page 14


DATABASE MANAGEMENT SYSTEM (MMC103)

2. Domain Relational Calculus (DRC)

Domain Relational Calculus (DRC) is another form of relational calculus, but instead of
working with entire tuples, it works with domain variables (values of attributes). DRC
queries specify what values from the domain (column values) satisfy a given condition.

Syntax: {<attribute1, attribute2.., attributeN> | P (attribute1, attribute2,.. attributeN) }

Where:

 attribute1, attribute2, ..., attributeN are domain variables (representing values in the
relation).
 P(attribute1, attribute2, ..., attributeN) is the predicate (condition) that specifies the
values satisfying the query.
Example:
Let's use the same Employees relation, and we want to find the names and department
IDs of employees who are older than 30.

Relational Calculus (DRC) query:


{ Name, Department_ID | ∃ Employee_ID (Employees(Employee_ID, Name, Age,
Department_ID) AND Age > 30) }
Explanation:
 Name, Department_ID are the attributes we want to retrieve.
 The ∃ (exists) quantifier ensures that for each tuple in Employees, there exists an
Employee_ID, Name, Age, and Department_ID such that Age > 30.
 The condition Age > 30 filters the tuples.

Name Department_ID
Bob 2
David 2

Prof.Kallappa Huddar,VTU Belagavi Page 15


DATABASE MANAGEMENT SYSTEM (MMC103)

OVERVIEW OF SQL QUERY LANGUAGE

SQL (Structured Query Language) is the standard language for managing and manipulating
relational databases. It is a declarative language, meaning users specify what data they want,
rather than how to get it. SQL allows users to interact with databases by performing operations
such as data retrieval, insertion, updating, deletion, and database management.

SQL is used for tasks such as:

 Querying databases
 Inserting, updating, and deleting records
 Creating and modifying database structures (tables, schemas)
 Creating views, triggers, and stored procedures

Basic Structure of SQL Queries:


SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column1
GROUP BY column2
HAVING condition;

KEY COMPONENTS:

 SELECT: Specifies the columns to retrieve.


 FROM: this clause is mandatory in every SQL query, as it tells SQL where to look for the
data.
 WHERE: Filters records based on a condition.,Only the rows that satisfy the condition
specified in the WHERE clause will be included in the result set. This clause can use
operators like =, >, <, BETWEEN, LIKE, etc
 ORDER BY: Sorts the result set, You can specify ascending (ASC) or descending (DESC)
order for sorting. By default, sorting is done in ascending order.
 GROUP BY: This clause is used to aggregate data into groups based on the specified
columns.
 HAVING: Filters groups after applying GROUP BY. Typically used with aggregate
functions to filter the result set after the grouping operation.

Prof.Kallappa Huddar,VTU Belagavi Page 16


DATABASE MANAGEMENT SYSTEM (MMC103)

Data Types in SQL

SQL supports various data types that define what kind of data a column in a table can store.
Different data types help in maintaining the integrity of data by ensuring that only appropriate
types of values are stored in each column. These data types are typically categorized into numeric
types, character types, date and time types, boolean types, and binary types.

Here’s a detailed overview of the common SQL data types:

1. Numeric Data Types

These types are used to store numbers, both integers and floating-point numbers.

 INT (Integer): Used to store whole numbers (positive, negative, or zero) without decimals.
o Example: INT is typically used for storing employee IDs or age.
o Range: Typically from -2,147,483,648 to 2,147,483,647 (depends on the database
system).
 FLOAT: Used to store approximate numeric values with floating decimal points.
o Example: Used to store scientific data or measurements with decimals, like 3.14 or
-0.006.
o Range: Typically stores up to 7 decimal digits.
 DECIMAL or NUMERIC: Stores exact numeric values with a specified precision and
scale. Unlike FLOAT, it ensures precise calculations.
o Example: Used to store financial data, like monetary values (DECIMAL(10, 2)
means 10 digits in total, with 2 digits after the decimal point).
o Syntax: DECIMAL(precision, scale) where precision is the total number of digits,
and scale is the number of digits to the right of the decimal.
 DOUBLE (Double Precision): Used to store approximate numeric values, with a larger
precision than FLOAT.
o Example: Used for precise scientific calculations that require more decimal places
than FLOAT.

Prof.Kallappa Huddar,VTU Belagavi Page 17


DATABASE MANAGEMENT SYSTEM (MMC103)

2. Character Data Types

These types are used to store text data, such as names, descriptions, and other strings.

 CHAR (Fixed Length): Used to store fixed-length strings. If the string is shorter than the
defined length, it will be padded with spaces.
o Example: CHAR(10) will always store 10 characters. If the string is shorter, the
remaining space will be filled with spaces.
o Use Case: Ideal for storing fixed-length values, like state abbreviations (e.g., NY,
CA).
 VARCHAR (Variable Length): Used to store variable-length strings. It stores only the
characters that are actually used, saving space.
o Example: VARCHAR(100) can store a string of any length up to 100 characters.
o Use Case: Used for text fields like names, addresses, and email addresses.
 TEXT: Used to store large amounts of text. Unlike CHAR or VARCHAR, the TEXT type
is used for storing long strings, such as large descriptions or articles.
o Example: Used for storing comments or large textual content.
o Use Case: Ideal for storing long notes, articles, or descriptions that exceed the
limits of VARCHAR.

3. Date and Time Data Types

These types are used to store date, time, or timestamp values.

 DATE: Used to store date values in the format YYYY-MM-DD.


o Example: 2024-12-25 (for Christmas Day).
o Use Case: Used for birth dates, product expiration dates, etc.
 TIME: Used to store time values in the format HH:MM:SS.
o Example: 15:30:00 (3:30 PM).
o Use Case: Used for storing times, such as working hours or event times.
 DATETIME: Used to store both date and time values together in the format YYYY-MM-
DD HH:MM:SS.
o Example: 2024-12-25 15:30:00.
o Use Case: Used when both the date and the time of an event or transaction are
important (e.g., order timestamps).
 TIMESTAMP: Similar to DATETIME, but it also includes information about time zones
and is typically used to record the exact time a record was created or updated.
o Example: 2024-12-25 15:30:00 with the time zone information.
o Use Case: Commonly used for auditing purposes to track when a record was
created or last modified.

Prof.Kallappa Huddar,VTU Belagavi Page 18


DATABASE MANAGEMENT SYSTEM (MMC103)

4. Boolean Data Types

These types are used to store binary (true/false) values.

 BOOLEAN: Stores boolean values, typically TRUE or FALSE.


o Example: TRUE (1) or FALSE (0) representing whether a condition is met.
o Use Case: Ideal for flags, such as indicating if a user is active or if an order is
shipped.
 BIT: Another data type that can be used to store boolean values, typically stored as 1
(TRUE) or 0 (FALSE).
o Example: BIT can store values like 0 or 1.
o Use Case: Commonly used in flags or binary decisions.

5. Binary Data Types

These types are used to store binary data, such as images, files, or multimedia.

 BLOB (Binary Large Object): Used to store large binary objects like images, audio files,
or any kind of file data.
o Example: Storing an image file or a PDF document.
o Use Case: Ideal for storing files that need to be retrieved and used within the
application.
 VARBINARY: Similar to BLOB, but with a variable length. Used to store binary data
where the length of the data can vary.
o Example: Used to store encrypted data or file paths in binary format.

Prof.Kallappa Huddar,VTU Belagavi Page 19


DATABASE MANAGEMENT SYSTEM (MMC103)

SQL CATEGORIES:

Categories Purpose Key Commands


DDL Defining and modifying database CREATE, ALTER, DROP, TRUNCATE,
structure. RENAME
DML Manipulating data (insert, update, INSERT, SELECT, UPDATE, DELETE
delete, retrieve).
DCL Controlling access to the database GRANT, REVOKE
(permissions).
TCL Managing transactions (ensuring COMMIT, ROLLBACK, SAVEPOINT, SET
data integrity). TRANSACTION
DQL Querying data from the database. SELECT

1. DDL Commands (Data Definition Language)

DDL commands are used to define and manage the structure of the database objects (such as
tables, schemas, and indexes). They do not manipulate the data itself, but rather the schema and its
components.

A. CREATING A DATABASE

The CREATE DATABASE statement is a foundational SQL command used to create new
databases in SQL-based Database Management Systems (DBMS), including MySQL,
PostgreSQL, SQL Server, and others. Understanding how to use this command effectively is
crucial for developers, database administrators, and anyone working with relational databases.

CREATE DATABASE in SQL


The CREATE DATABASE command establishes a new database within your SQL ecosystem.
A database is a repository that organizes data in structured formats through tables, views, stored
procedures, and other components.

There are two main types of databases:

1. Relational Databases (e.g., MySQL, PostgreSQL, SQLite)

2. Non-relational Databases (e.g., MongoDB, Firebase, Cassandra)

Syntax:
CREATE DATABASE database_name;

Example:
CREATE DATABASE College;

Prof.Kallappa Huddar,VTU Belagavi Page 20


DATABASE MANAGEMENT SYSTEM (MMC103)

key points for using the CREATE DATABASE statement in SQL:

1. Naming Conventions: Use unique, descriptive names without spaces (use underscores).
Example: my_database.
2. Max Length: Database names are typically limited to 128 characters.
3. Permissions: You need administrative privileges to create a database.
4. Case Sensitivity: Most SQL systems are case-insensitive, but it’s best to use lowercase
consistently.
5. Cross-DB Compatibility: While the syntax is similar across systems (e.g., MySQL,
PostgreSQL, SQL Server), some systems have specific options (like character set or
storage engine).

CREATE A DATABASE in MongoDB

In MongoDB, you don’t need to explicitly create a database; just use the use command to switch
to a database, and MongoDB will create it when you insert data.

Syntax:
use database_name;
Example:
use College;

List Databases in SQL


We use the SHOW DATABASES command and it will return a list of databases that exist in our
system. Now we will look for the name of the database (GeeksForGeeks) that we have just
created.
SQL Query:
SHOW DATABASES;

USE Database in SQL


Once your database is created, we can switch to that database to begin adding tables, inserting
data, and performing queries. To do this, use the USE command.

Select the Database to Use

After creating the database, switch to it:

Syntax: USE database_name;

Example:
use College;

Prof.Kallappa Huddar,VTU Belagavi Page 21


DATABASE MANAGEMENT SYSTEM (MMC103)

CREATE TABLE

SQL Syntax to Create a Table:

CREATE TABLE table_name (


column1 datatype [constraint],
column2 datatype [constraint],
column3 datatype [constraint],
...
);

Example: Create a students table

CREATE TABLE students (


student_id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
date_of_birth DATE,
);

Steps:

1. Define the table's structure: List the columns with their data types.
2. Specify constraints: Indicate primary keys, unique fields, or not-null constraints.

B. ALTER TABLE
The most common use of ALTER is to modify a table. Here's how you can use it in different
scenarios
ADD A COLUMN
You can add one or more columns to an existing table using the ALTER TABLE statement with
the ADD keyword.

Syntax: ALTER TABLE table_name ADD column_name datatype;

Example: ALTER TABLE students ADD email VARCHAR(100);

 This adds a new column named email with a VARCHAR(100) data type to the students
table.

DROP A COLUMN
You can remove a column from a table using the ALTER TABLE statement with the DROP COLUMN
keyword.

Syntax: ALTER TABLE table_name DROP COLUMN column_name;

Example: ALTER TABLE students DROP COLUMN email;


 This removes the email column from the students table.

Prof.Kallappa Huddar,VTU Belagavi Page 22


DATABASE MANAGEMENT SYSTEM (MMC103)

MODIFY A COLUMN (CHANGE DATA TYPE OR SIZE)

You can change the data type or size of an existing column using the ALTER TABLE statement with
the MODIFY or CHANGE keyword (depending on the DBMS).

Syntax (MySQL): ALTER TABLE table_name MODIFY column_name new_datatype;

Example: ALTER TABLE students MODIFY age INT;

 This changes the age column data type to INT (if it was something else previously).

Syntax (SQL SERVER OR POSTGRESQL):

ALTER TABLE table_name ALTER COLUMN column_name SET DATA TYPE new_datatype;

Example (POSTGRESQL):

ALTER TABLE students ALTER COLUMN age TYPE INT;

RENAME A COLUMN

You can rename an existing column using the ALTER TABLE statement with the RENAME COLUMN
keyword.

Syntax (PostgreSQL):

ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;

Example:

ALTER TABLE students RENAME COLUMN email TO contact_email;

RENAME A TABLE

You can rename a table using the ALTER TABLE statement with the RENAME TO keyword.

Syntax: ALTER TABLE old_table_name RENAME TO new_table_name;

Example: ALTER TABLE students RENAME TO student_info;

C.DELETE/DROP A DATABASE IN SQL


If you ever need to remove a database, the DROP DATABASE command can be used to delete
the database and all its contents:

Syntax: Drop database database_name

Prof.Kallappa Huddar,VTU Belagavi Page 23


DATABASE MANAGEMENT SYSTEM (MMC103)

Important Considerations:

 Irreversible: Dropping a database will remove all data and structures associated with it, so
ensure that you have a backup if necessary.
 Permissions: You need administrative privileges to drop a database.

Before Dropping a Database:

 Make sure that no active connections are using the database, as some systems may prevent
dropping a database if it is in use.

Drop table

To drop a table in SQL, you use the DROP TABLE statement. This command permanently
deletes the table along with all the data and structure it contains.

SQL Syntax to Drop a Table:

DROP TABLE table_name;

Example: Drop a Table

DROP TABLE students;

Important Considerations:

 Irreversible: Dropping a table will permanently remove the table and all its data. Make
sure to back up the data if needed.
 Permissions: You need appropriate privileges to drop a table.
 Dependencies: If there are foreign keys or other dependencies (e.g., views, triggers), you
may need to drop them first or adjust them before dropping the table.

D. TRUNCATE IN SQL

The TRUNCATE command in SQL is used to remove all rows from a table quickly, while keeping
the table structure intact. This means that the table itself remains available for use, but all the data
within it is deleted.

Syntax for TRUNCATE: TRUNCATE TABLE table_name;

Example:If we have a table students and we want to remove all records from it, we would use:

TRUNCATE TABLE students;

Prof.Kallappa Huddar,VTU Belagavi Page 24


DATABASE MANAGEMENT SYSTEM (MMC103)

2.DML COMMANDS

DML (Data Manipulation Language) commands in SQL are used to manipulate and manage
data within existing database tables. These commands are focused on inserting, updating,
deleting, and querying the data. DML operations are typically non-structural and affect only the
data in the table, not the schema or the table structure itself.

Key DML Commands:

1. INSERT
2. SELECT
3. UPDATE
4. DELETE

1. INSERT

The INSERT command is used to add new rows of data into a table.

Syntax:

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


VALUES (value1, value2, value3, ...);

Example:

INSERT INTO students (student_id, first_name, last_name, age, email)


VALUES (1, 'Alice', 'Johnson', 22, '[email protected]');

 This adds a new row to the students table with the provided values.

2. SELECT

The SELECT command is used to retrieve data from one or more tables. You can use different
clauses like WHERE, ORDER BY, GROUP BY, etc., to filter, sort, or group the results.

Syntax:

SELECT column1, column2, column3, ...


FROM table_name
WHERE condition;

Example:

SELECT first_name, last_name, age FROM students WHERE age > 21;

 This retrieves the first_name, last_name, and age of students whose age is greater than
21.

Prof.Kallappa Huddar,VTU Belagavi Page 25


DATABASE MANAGEMENT SYSTEM (MMC103)

3. UPDATE

The UPDATE command is used to modify the existing data in a table. It allows you to change values
in one or more columns for specific rows.

Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Example:

UPDATE students
SET age = 23
WHERE student_id = 1;

 This updates the age of the student with student_id = 1 to 23.

Note: Always use the WHERE clause to specify which records should be updated. Without it, all
rows in the table will be updated.

4. DELETE

The DELETE command is used to remove rows from a table. You can use the WHERE clause to
specify which rows to delete.

Syntax:

DELETE FROM table_name


WHERE condition;

Example:

DELETE FROM students WHERE student_id = 1;

 This deletes the row where student_id = 1.

Prof.Kallappa Huddar,VTU Belagavi Page 26


DATABASE MANAGEMENT SYSTEM (MMC103)

DML Command Examples with students Table:

1. INSERT: To add a new student:

INSERT INTO students (student_id, first_name, last_name, age, email)


VALUES (4, 'David', 'Brown', 24, '[email protected]');

student_id first_name last_name age email


1 Alice Johnson 22 [email protected]
2 Bob Smith 23 [email protected]
3 Carol Lee 21 [email protected]
4 David Brown 24 [email protected]

2. SELECT: To get the names and ages of students who are 22 or older:

SELECT first_name, last_name, age FROM students WHERE age >= 22;

first_name last_name age


Alice Johnson 22
Bob Smith 23
David Brown 24

3. UPDATE: To update the age of the student with student_id = 3 to 22:

UPDATE students
SET age = 22
WHERE student_id = 3;

student_id first_name last_name age email


1 Alice Johnson 22 [email protected]
2 Bob Smith 23 [email protected]
3 Carol Lee 22 [email protected]
4 David Brown 24 [email protected]

4. DELETE: To delete the student with student_id = 2:

DELETE FROM students WHERE student_id = 2;

student_id first_name last_name age email


1 Alice Johnson 22 [email protected]
3 Carol Lee 22 [email protected]
4 David Brown 24 [email protected]

Prof.Kallappa Huddar,VTU Belagavi Page 27


DATABASE MANAGEMENT SYSTEM (MMC103)

CLAUSES IN SQL
In SQL, clauses are the components of a query that define its structure and functionality. They
specify the conditions, filters, sorting, grouping, and relationships between data. Here are the main
SQL clauses

1. SELECT Clause

Used to retrieve specific columns from a table.

SELECT column1, column2 FROM table_name;

2. FROM Clause

Specifies the table from which to retrieve the data.

SELECT * FROM employees;

3. WHERE Clause

The WHERE clause in SQL filters rows based on conditions. It supports comparison operators
(=, >, <, etc.), logical operators (AND, OR, NOT), and special operators like IN, BETWEEN,
LIKE, and IS NULL for advanced filtering.

Example:
SELECT *
FROM employees
WHERE salary > 50000;

 Output: Retrieves employees whose salary is greater than 50,000.

4. GROUP BY Clause

The GROUP BY clause in SQL is used to group rows that have the same values in specified
columns. It is often used with aggregate functions like COUNT(), SUM(), AVG(), MAX(), and
MIN() to summarize data within each group.

The GROUP BY clause must be used after the WHERE clause and before the ORDER BY
clause. It can be combined with the HAVING clause to filter grouped data based on conditions.
Only columns listed in the GROUP BY clause or used in aggregate functions can appear in the
SELECT statement.

Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;

Prof.Kallappa Huddar,VTU Belagavi Page 28


DATABASE MANAGEMENT SYSTEM (MMC103)

Example 1: Count Employees in Each Department


SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

 Output: Groups employees by department and counts the number of employees in each.

Example 2: Average Salary by Department


SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;

 Output: Groups rows by department and calculates the average salary for each.

5. HAVING Clause

The HAVING clause in SQL is used to filter grouped data after applying the GROUP BY
clause. Unlike the WHERE clause, which filters rows before grouping, the HAVING clause
filters groups after aggregation. It is often used with aggregate functions like COUNT(),
SUM(), and AVG() to apply conditions to grouped results.

Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;

Example 1: Departments with More Than 5 Employees


SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

 Output: Displays departments with more than 5 employees.

6. ORDER BY Clause

The ORDER BY clause in SQL is used to sort the result set in either ascending (ASC) or
descending (DESC) order. By default, the sorting is in ascending order. It can be applied to one or
more columns to arrange the data in a specific sequence.

Syntax
SELECT column1, column2
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];

Prof.Kallappa Huddar,VTU Belagavi Page 29


DATABASE MANAGEMENT SYSTEM (MMC103)

Example 1: Sorting by a Single Column


SELECT *
FROM employees
ORDER BY salary DESC;

 Output: Sorts employees by salary in descending order.

Example 2: Sorting by Multiple Columns


SELECT *
FROM employees
ORDER BY department ASC, salary DESC;

 Output: Sorts employees first by department in ascending order, then by salary in


descending order.

SET OPERATIONS

Set operations in SQL are used to combine the results of two or more SELECT queries. They allow
you to perform operations like union, intersection, and difference on result sets. The most common
set operations in SQL are:

1. UNION
2. UNION ALL
3. INTERSECT
4. EXCEPT (or MINUS in some databases)

Example Tables

Consider the following two tables:

Employees table Customers table

EmployeeID EmployeeName Department CustomerID CustomerName Country


1 Alice HR 1 Alice USA
2 Bob IT 2 John Canada
3 Charlie Marketing 3 Charlie UK
4 David IT 4 Helen Australia
5 Eve HR 5 Eve USA

Prof.Kallappa Huddar,VTU Belagavi Page 30


DATABASE MANAGEMENT SYSTEM (MMC103)

1. UNION

The UNION operator combines the results of two SELECT queries and removes duplicates. The
columns must have the same names and data types in both queries.

Example: Using UNION


We want to combine the names of employees and customers. If there are any duplicates (e.g.,
Alice and Charlie), they will be removed.

SELECT EmployeeName Name


FROM Employees Alice
UNION Bob
SELECT CustomerName Charlie
FROM Customers;
David
Eve
John
Helen

 Alice, Charlie, and Eve appear in both tables, but only one instance of each is included in
the result.

2. UNION ALL

The UNION ALL operator combines the result sets of two queries but does not remove duplicates.

Example: Using UNION ALL


This will return all names from both tables, including duplicates.

SELECT EmployeeName
FROM Employees Name
UNION ALL Alice
SELECT CustomerName Bob
FROM Customers; Charlie
David
Eve
Alice
John
Charlie
Helen
Eve

 Notice that Alice, Charlie, and Eve appear twice, as UNION ALL doesn't eliminate
duplicates.

Prof.Kallappa Huddar,VTU Belagavi Page 31


DATABASE MANAGEMENT SYSTEM (MMC103)

3. INTERSECT

The INTERSECT operator returns only the rows that are present in both result sets.

Example: Using INTERSECT

We want to find the common names between employees and customers.

SELECT EmployeeName Name


FROM Employees
INTERSECT Alice
SELECT CustomerName Charlie
FROM Customers; Eve

 Only Alice, Charlie, and Eve appear in both the Employees and Customers tables, so
they are returned.

4. EXCEPT (or MINUS in some databases)

The EXCEPT operator returns the rows from the first query that do not exist in the second query. It
removes any common rows.

Example: Using EXCEPT

We want to find employees who are not customers.

SELECT EmployeeName Name


FROM Employees Bob
EXCEPT
SELECT CustomerName David
FROM Customers;

Only Bob and David appear in the Employees table but not in the Customers table, so they
are returned.

Prof.Kallappa Huddar,VTU Belagavi Page 32


DATABASE MANAGEMENT SYSTEM (MMC103)

AGGREGATE FUNCTIONS

Aggregate functions in SQL are used to perform calculations on a set of values and return a single
value. These functions are commonly used with the GROUP BY clause to summarize or group
data, but they can also be used without grouping.

Common Aggregate Functions in SQL:

1. COUNT()
2. SUM()
3. AVG()
4. MIN()
5. MAX()

Let’s go through each function with examples.

1. COUNT(): The COUNT() function returns the number of rows that match a specified condition
or the total number of rows in a column.

Syntax:

COUNT(column_name)

Example:
SaleID Product Amount
1 A 100
2 B 150
3 A 200
4 C 120
5 A 180

To find out how many sales transactions occurred:


TotalSales
SELECT COUNT(*) AS TotalSales
FROM Sales; 5

 COUNT(*) counts all rows, including rows with NULL values.

If you want to count how many sales of product "A" there were:

SELECT COUNT(*) AS ProductACount ProductACount


FROM Sales
WHERE Product = 'A'; 3

 COUNT() ignores NULL values in columns.

Prof.Kallappa Huddar,VTU Belagavi Page 33


DATABASE MANAGEMENT SYSTEM (MMC103)

2. SUM(): The SUM() function returns the total sum of a numeric column.

Syntax:

SUM(column_name)

Example:
To find the total amount of sales in the Sales table:
TotalAmount
SELECT SUM(Amount) AS TotalAmount
FROM Sales;
750

 SUM() only works on numeric columns and ignores NULL values.

3. AVG(): The AVG() function returns the average value of a numeric column.

Syntax:
AVG(column_name)

Example:
To find the average sales amount:

SELECT AVG(Amount) AS AverageAmount AverageAmount


FROM Sales;
150

 AVG() calculates the average of non-NULL values.

4. MIN(): The MIN() function returns the smallest value in a column.

Syntax:
MIN(column_name)

Example:
To find the minimum sales amount:

SELECT MIN(Amount) AS MinAmount MinAmount


FROM Sales; 100

 MIN() works on numeric, date, or text columns and returns the smallest value.

Prof.Kallappa Huddar,VTU Belagavi Page 34


DATABASE MANAGEMENT SYSTEM (MMC103)

5. MAX(): The MAX() function returns the largest value in a column.

Syntax:
MAX(column_name)

Example:
To find the maximum sales amount:
MaxAmount
SELECT MAX(Amount) AS MaxAmount 200
FROM Sales;

 MAX() works similarly to MIN(), returning the largest value.

TRIGGERS

A trigger in SQL is a special kind of stored procedure that automatically executes (or fires) in
response to certain events on a table or view. Triggers can be set to run before or after an
INSERT, UPDATE, or DELETE operation is performed on a table.

Trigger Types:

1. AFTER INSERT activated after data is inserted into the table.

2. AFTER UPDATE: activated after data in the table is modified.

3. AFTER DELETE: activated after data is deleted/removed from the table.

4. BEFORE INSERT: activated before data is inserted into the table.

5. BEFORE UPDATE: activated before data in the table is modified.

6. BEFORE DELETE: activated before data is deleted/removed from the table.

Syntax for Creating a Trigger

CREATE TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- Trigger logic here
END;

Prof.Kallappa Huddar,VTU Belagavi Page 35


DATABASE MANAGEMENT SYSTEM (MMC103)

EXAMPLE

SELECT *FROM constituency;

Create a TRIGGER to UPDATE the count of “ Number_of_voters” of the respective


constituency

DELIMITER //
Create trigger T
after insert on voter
for each row
begin
update constituency set no_of_voters=no_of_voters+1 where
cons_id=new.cons_id;
end
//
insert into voter values(300,'suresh',25,'chikodi',111,121);
//
select *from constituency;
//

Prof.Kallappa Huddar,VTU Belagavi Page 36


DATABASE MANAGEMENT SYSTEM (MMC103)

STORED PROCEDURE

A stored procedure in SQL is a set of precompiled SQL statements that are stored together in a
database. Stored procedures are used to perform operations such as querying data, updating
records, or executing complex logic. They are stored within the database and can be executed
multiple times, providing efficiency, security, and code reusability.

Basic Syntax for Creating a Stored Procedure

CREATE PROCEDURE procedure_name


[parameter1 datatype, parameter2 datatype, ...]
AS
BEGIN
-- SQL statements
-- Example: SELECT, INSERT, UPDATE, DELETE
END;

Example: select *from voter;

Create a stored procedure to insert the tuple into the voter table by checking the voter age. If
voter‟s age is at least 18 years old, then insert the tuple into the voter else display the “Not an
eligible voter msg”.

DELIMITER //
CREATE PROCEDURE INSERT_VOTER1(IN vid int,IN vname
varchar(20),IN vage int,IN vaddrvarchar(20),IN cons_id
int,cid int)
BEGIN
DECLARE msg varchar(70);
IF vage>=18
THEN
INSERT INTO VOTER VALUES(vid,vname,vage,vaddr,cons_id,cid);
set msg="row inserted successfully";
ELSE
set msg="voter age is less than 18";
END IF
;
SELECT msg;
END;
//

Prof.Kallappa Huddar,VTU Belagavi Page 37


DATABASE MANAGEMENT SYSTEM (MMC103)

CALL insert_voter1(332,'ramesh',20,'nippani',111,121);

CALL insert_voter1(338,'ram',17,'nippani',111,121);
//

select *from voter;


//

Advantages of Stored Procedures

 Performance: Precompiled execution reduces overhead.


 Security: You can limit access to stored procedures instead of giving direct access to
tables.
 Maintainability: Encapsulates complex logic within the database, making it easier to
manage.

Prof.Kallappa Huddar,VTU Belagavi Page 38


DATABASE MANAGEMENT SYSTEM (MMC103)

VIEWS
A view in SQL is a virtual table that provides a way to simplify complex queries, encapsulate
logic, and re-use SQL code. It doesn't store data itself but displays data from one or more tables or
other views. Views are commonly used to simplify complex queries, aggregate data, or hide
specific data from the end user.

Basic Concepts of Views:

 Virtual Table: A view behaves like a table but doesn't physically store data. Instead, it
stores a query that retrieves data when accessed.
 Simplifying Queries: Views can simplify complex queries, so users don't need to write the
same SQL repeatedly.
 Security: Views can be used to restrict access to specific columns or rows of a table,
providing an abstraction layer.

Creating a View

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

Example 1: Simple View

Suppose we have the following Employees table:

EmployeeID Name Department Salary

1 Alice HR 50000

2 Bob IT 60000

3 Charlie Marketing 45000

4 David IT 65000

5 Eve HR 55000

Prof.Kallappa Huddar,VTU Belagavi Page 39


DATABASE MANAGEMENT SYSTEM (MMC103)

To create a view that only shows the names and salaries of employees:

CREATE VIEW EmployeeSalaries AS


SELECT Name, Salary
FROM Employees;

This creates a view EmployeeSalaries which can be queried like a table:

SELECT * FROM EmployeeSalaries;


Name Salary
Alice 50000
Bob 60000
Charlie 45000
David 65000
Eve 55000

Example 2: View with Filtering

You can create views that include filters. For example, let's create a view for employees with a
salary greater than 55,000.

CREATE VIEW HighEarners AS


SELECT Name, Salary
FROM Employees
WHERE Salary > 55000;

Now, querying the HighEarners view will only return employees with a salary above 55,000:

SELECT * FROM HighEarners; Name Salary


Bob 60000
David 65000
Dropping a View

If you no longer need a view, you can remove it using the DROP VIEW statement:

DROP VIEW EmployeeSalaries;

Limitations of Views

1. Read-Only Views: Some views are read-only if they involve certain operations (such as
joins or aggregations). You cannot update or insert data into these views directly.
2. Performance: Since views are virtual and executed at runtime, they may impact
performance when dealing with complex queries.
3. No Indexing: Views do not have indexes, although indexes on underlying tables can still
affect performance.
4. Not Persistent Data: Views do not store data themselves; they are always generated on the
fly when queried.

Prof.Kallappa Huddar,VTU Belagavi Page 40


DATABASE MANAGEMENT SYSTEM (MMC103)

NESTED SUB QUERIES

A nested subquery (or simply subquery) is a query within another query. The subquery is
typically used to return a value that is then used by the outer query to filter results or perform other
operations. Subqueries can be nested in various places, such as in the SELECT, WHERE, FROM,
and HAVING clauses of an SQL query.

Important Rule:
 A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause,
HAVING clause.
 You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
 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.
 Subqueries are on the right side of the comparison operator.
 A subquery is enclosed in parentheses.
 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
SELECT column_name
FROM table_name
WHERE column_name expression operator
( 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

Prof.Kallappa Huddar,VTU Belagavi Page 41


DATABASE MANAGEMENT SYSTEM (MMC103)

The subquery with a SELECT statement will be:

SELECT *
FROM EMPLOYEE
WHERE ID IN (SELECT ID
FROM EMPLOYEE
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

 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.
 In the subquery, the selected data can be modified with any of the character, date functions.

Syntax:

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


SELECT *
FROM table_name
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.

INSERT INTO EMPLOYEE_BKP


SELECT * FROM EMPLOYEE
WHERE ID IN (SELECT ID
FROM EMPLOYEE);

Prof.Kallappa Huddar,VTU Belagavi Page 42


DATABASE MANAGEMENT SYSTEM (MMC103)

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

UPDATE table
SET column_name = new_value
WHERE VALUE OPERATOR
(SELECT COLUMN_NAME
FROM TABLE_NAME
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.

UPDATE EMPLOYEE
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 29);

This would impact three rows, and finally, the EMPLOYEE table would 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 1625.00

5 Kathrin 34 Bangalore 2125.00

6 Harry 42 China 1125.00

7 Jackson 25 Mizoram 10000.00

Prof.Kallappa Huddar,VTU Belagavi Page 43


DATABASE MANAGEMENT SYSTEM (MMC103)

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

DELETE FROM TABLE_NAME


WHERE VALUE OPERATOR
(SELECT COLUMN_NAME
FROM TABLE_NAME
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

DELETE FROM EMPLOYEE


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

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00

Prof.Kallappa Huddar,VTU Belagavi Page 44

You might also like