UNIT III dbms notes
UNIT III dbms notes
Basic SQL querying (select and project) using where clause, arithmetic & logical operations, SQL
functions(Date and Time, Numeric, String conversion).Creating tables with relationship,
implementation of key and integrity constraints, nested queries, sub queries, grouping, aggregation,
ordering, implementation of different types of joins, view(updatable and non-updatable), relational set
operations.
• In SQL, the WHERE clause is equivalent to the SELECT (σ) operation in relational algebra.
• 𝜎 𝑎𝑔𝑒>20 (Students)
• In SQL:
• πfirst_name,last_name(Students)
• In SQL:
• If we need to apply both selection and projection, we use SELECT column_names along
with WHERE.
• πfirst_name,last_name(σage>20(Students))
• In SQL:
• This filters students where age is greater than 20 (SELECT σ) and retrieves only the
first_name and last_name (PROJECT π).
SQL Where Clause:
• Where clauses are not mandatory clauses of SQL DML statements but it can be used to limit
the number of rows affected by a SQL DML statement or returned by query.
• Actually, it follows the records.it returns only those queries which the specific conditions.
• = • Equal to
SQL operators: SQL statements generally contain some reserved words or characters that are used to
perform operations such as arithmetic and logical operations etc. Their reserved words are known as
operators.
LOGICAL OPERATORS:
• Logical operators in SQL are used to combine multiple conditions in a query to control the
flow of execution. They evaluate whether these conditions are TRUE, FALSE, or NULL,
assisting in refining query results effectively. By using these operators, developers can
retrieve highly specific data based on given conditions.
• We will use the following employee table throughout the examples. This table represents
employee details, including their unique ID, name, city, and country.
1. AND Operator: The AND operator is used to combine two or more conditions in an SQL query.
It returns records only when all conditions specified in the query are true. This operator is commonly
used when filtering data that must satisfy multiple criteria simultaneously.
• Example
• Retrieve the records of employees from the employees table who are located
in 'Allahabad' and belong to 'India', ensuring that both conditions are met.
• Query:
2. IN Operator: The IN operator simplifies the process of checking if a value matches any value in a
list, making it more efficient and readable compared to using multiple OR conditions. This operator is
especially helpful when we need to filter results based on multiple possible values for a given column,
reducing the complexity of the query.
• Example
• Retrieve the records of employees from the employee table who are located in
either 'Allahabad' or 'Patna'.
• Query:
• Example
• Retrieve the records of employees from the employee table whose city names do not start
with the letter 'A'.
• Query:
• Example
• Retrieve the records of employees from the employee table who are either from 'Varanasi' or
have 'India' as their country.
• Query
• %: Represents zero or more characters. It allows matching any sequence of characters in the
string.
• _: Represents exactly one character. It is used when you want to match a specific number of
characters at a given position.
• Example
• Retrieve the records of employees from the employee table whose city names start with the
letter 'P'.
• Query:
6. BETWEEN Operator: The BETWEEN operator in SQL allows us to test if a value or expression
lies within a specified range. The BETWEEN condition is inclusive, meaning it includes both
the lower and in the results. This operator is particularly useful when we need to filter records based
on a range of values, such as numerical ranges, dates, or even text values.
• Example
• Retrieve the records of employees from the employee table whose emp_id values fall within
the range of 101 to 104 (inclusive).
• Query:
• Example
• Retrieve the records of employees whose emp_id is equal to all emp_id values in
the employees table where the emp_city is 'Varanasi'.
• Query:
8. ANY Operator: The ANY operator in SQL is used to compare a value with the results of
a subquery. It returns TRUE if the value satisfies the condition with any of the values returned by the
subquery. This operator allows for greater flexibility when you want to check if a value matches at
least one of the results in a set of values.
• Example
• Retrieve the records of employees whose emp_id matches any of the emp_id values in
the employees table where the emp_city is 'Varanasi'.
• Query:
• Example
• Retrieve the names of employees from the employee table if there are any employees in
the employee table who are located in 'Patna'.
• Query
10. SOME Operator: The SOME operator in SQL is used in conjunction with comparison operators
such as <, >, =, <=, etc., to compare a value with the results of a subquery. It returns TRUE if the
condition is met with any value returned by the subquery. The SOME operator allows us to perform
comparisons with any of the values returned by a subquery, and it is particularly useful when we
want to match a value against a set of values rather than a single value.
• Example
• Retrieve the records of employees from the employee table where the emp_id is less
than any of the emp_id values from employees located in 'Patna'.
• Query:
• SELECT * FROM employee WHERE emp_id < SOME
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');
Arithmetic Operations: The SQL Arithmetic operators are used to perform basic mathematical
operations on numeric data types in a database. The most common arithmetic operators used in SQL
are:
Output:
SQL Addition (+) Operator
The addition operator in SQL is used to add two or more numeric values. It is similar to the "plus"
symbol in basic mathematics.
Example
In the following example, we are trying to perform the addition operation to give all employees a
bonus of 5000 to their existing salary.
Output:
Example
In here, we are using the - operator to find the salary difference between the highest-paid and lowest-
paid employees.
Output:
The multiplication operator in SQL is used to perform mathematical multiplication on numeric values.
It allows us to multiply two or more columns or numeric expressions together, resulting in a new
value representing the product of the operands.
Example
Now, we are performing * operation to give all employees a 10% bonus on their salary.
Output:
The division operator (/) in SQL is used to perform mathematical division on numeric values. It
allows us to divide one numeric operand by another, resulting in a new value representing the quotient
of the division.
Example
Here, we are using the / operator to calculate the average salary of all employees.
Output:
The modulus operator (%) in SQL is used to find the remainder after dividing one numeric value by
another. It returns the integer remainder of the division operation.
Example
In the following example, we are using the % operator to find out the employees having an even
employee ID.
SQL provides built-in functions to perform operations on Date and Time values, Numeric values,
and String conversions.
These functions help in manipulating and extracting information from date and time values.
1.1 SYSDATE
Output:
SYSDATE
-------------------
2025-03-19 14:30:45
1.2 CURRENT_DATE
Output:
CURRENT_DATE
-------------------
2025-03-19 14:30:45
1.3 ADD_MONTHS()
Output:
NEW_DATE
-------------------
2025-09-19
1.4 MONTHS_BETWEEN()
Output:
MONTH_DIFF
----------
9
1.5 NEXT_DAY()
Returns the next occurrence of the specified day after a given date.
Example:
SELECT NEXT_DAY('2025-03-19', 'Friday') AS NEXT_FRIDAY FROM DUAL;
Output:
NEXT_FRIDAY
-------------------
2025-03-21
1.6 LAST_DAY()
LAST_DAY_OF_MONTH
-------------------
2025-03-31
1.7 EXTRACT()
Output:
YEAR
----
2025
2. Numeric Functions
2.1 ROUND()
Output:
ROUNDED
-------
123.46
2.2 TRUNC()
Output:
TRUNCATED
---------
123.45
2.3 MOD()
Output:
REMAINDER
---------
1
2.4 POWER()
Output:
RESULT
------
8
2.5 CEIL()
Returns the smallest integer greater than or equal to the given number.
Example:
SELECT CEIL(12.3) AS CEIL_VALUE FROM DUAL;
Output:
CEIL_VALUE
----------
13
2.6 FLOOR()
Returns the largest integer less than or equal to the given number.
Example:
SELECT FLOOR(12.9) AS FLOOR_VALUE FROM DUAL;
Output:
FLOOR_VALUE
-----------
12
2.7 ABS()
Output:
ABSOLUTE
--------
15
3. String Conversion Functions
These functions convert data between different formats (number to string, string to number, date to
string, etc.).
3.1 TO_CHAR()
Output:
DATE_STR
----------------------
19-MAR-2025 02:30:45 PM
Output:
NUM_STR
-------
12345
3.2 TO_NUMBER()
Output:
SUM_RESULT
----------
12355
3.3 TO_DATE()
Output:
DATE_VALUE
-------------------
2025-03-19
3.4 CAST()
Output:
CAST_DATE
-------------------
2025-03-19
It is important to understand and design relationships among tables in a relational database like
SQL Server. In a relational database, each table is connected to another table using the Primary-
Foreign Key constraints.
1. One-to-One
2. One-to-Many
3. Many-to-Many
One-to-One Relation
In One-to-One relationship, one record of the first table will be linked to zero or one record of
another table. For example, each employee in the Employee table will have a corresponding row
in EmployeeDetails table that stores the current passport details for that particular employee. So,
each employee will have zero or one record in the EmployeeDetails table. This is called zero or
one-to-one relationship.
Below, EmployeeID column is the primary key as well as foreign key column in the
EmloyeeDetails table that linked to EmployeeID of the Employee table. This forms zero or one-
to-one relation.
The following query will display data from both the tables.
SELECT * FROM Employee
SELECT * FROM EmployeeDetails
The following is the result of the above queries that demonstrate how each employee has none or
just one corresponding record in EmployeeDetails table.
One-to-Many Relation
One-to-Many is the most commonly used relationship among tables. A single record from one
table can be linked to zero or more rows in another table.
Let's take an example of the Employee and Address table in the HR database. The Employee
table stores employee records where EmployeeID id the primary key. The Address table holds
the addresses of employees where AddressID is a primary key and EmployeeID is a foreign key.
Each employee will have one record in the Employee table. Each employee can have many
addresses such as Home address, Office Address, Permanent address, etc.
The Employee and Address tables are linked by the key column EmployeeID. It is a foreign key in
the Address table linking to the primary key EmployeeID in the Employee table. Thus, one record of
the Employee table can point to multiple records in the Address table. This is a One-to-Many
relationship.
The following query will display data from both the tables.
In the above data, each record in the Employee table associated with zero or more records in
the Address table, e.g. James Bond has zero address, John King has three addresses.
Many-to-Many Relation
Many-to-Many relationship lets you relate each row in one table to many rows in another table
and vice versa. As an example, an employee in the Employee table can have many skills from
the EmployeeSkill table and also, one skill can be associated with one or more employees.
Every employee in the Employee table can have one or many skills. Similarly, a skill in
the SkillDescription table can be linked to many employees. This makes a many-to-many
relationship
In the example above, the EmployeeSkill is the junction table that contains EmployeeID and
SkillID foreign key columns to form many-to-many relation between the Employee and
SkillDescription table. Individually, the Employee and EmployeeSkill have a one-to-many
relation and the SkillDescription and the EmployeeSkill tables have one-to-many relation. But,
they form many-to-many relation by using a junction table EmployeeSkill.
The following query will display data from all the tables.
The following is the result of the above queries that demonstrate how the data is related in
many-to-many relationship.
When creating tables in SQL, keys and integrity constraints ensure data consistency,
uniqueness, and relationships between tables. Below are different types of constraints with
their implementations.
KEY CONSTRAINTS
There are 3 most important Key constraints one should consider mainly they are
1. PRIMARY KEY
2. FOREIGN KEY
3. UNIQUE
FIRSTNAME VARCHAR2(50),
LASTNAME VARCHAR2(50),
PHONE VARCHAR2(15),
HIREDATE DATE
);
Here, EMPLOYEEID is the Primary Key, and EMAIL has a Unique Constraint.
It Ensures a relationship between two tables by linking a column in one table to the
Primary Key in another.
FIRSTNAME VARCHAR2(50),
LASTNAME VARCHAR2(50),
DEPARTMENTID NUMBER,
UNIQUE CONSTRAINT:
);
INTEGRITY CONSTRAINTS
There are the integrity constraints one should consider mainly they are
1. NOT NULL
2. CHECK
3. DEFAULT
);
CHECK CONSTRAINT
DEFAULT CONSTRAINT:
);
PHONE VARCHAR2(15),
DEPARTMENTID NUMBER,
);
NESTED QUERIES:
• A nested query is a query that has another query embedded within it; the embedded
query is called a subquery.
• The embedded query can of course be a nested query itself; thus queries that have very
deeply nested structures are possible.
• A nested query in SQL contains a query inside another query. The outer query will use
the result of the inner query. For instance, a nested query can have
two SELECT statements, one on the inner query and the other on the outer query.
[WHERE]
);
INDEPENDENT NESTED QUERIES: In independent nested queries, the execution order is from
the innermost query to the outer query. An outer query won't be executed until its inner query
completes its execution. The outer query uses the result of the inner query. Operators such
as IN, NOT IN, ALL, and ANY are used to write independent nested queries.
• The IN operator checks if a column value in the outer query's result is present in the inner
query's result. The final result will have rows that satisfy the IN condition.
• The NOT IN operator checks if a column value in the outer query's result is not present in
the inner query's result. The final result will have rows that satisfy the NOT IN condition.
• The ALL operator compares a value of the outer query's result with all the values of the
inner query's result and returns the row if it matches all the values.
• The ANY operator compares a value of the outer query's result with all the inner query's
result values and returns the row if there is a match with any value.
Example 1: IN
Example 2: NOT IN
• Example 3: ALL
• Select all Developers who earn more than all the Managers
);
• Example 4: ANY
);
CO-RELATED NESTED QUERIES: In co-related nested queries, the inner query uses the values
from the outer query to execute the inner query for every row processed by the outer query. The co-
related nested queries run slowly because the inner query is executed for every row of the outer
query's result.
• Select all employees whose salary is above the average salary of employees in their role.
SELECT AVG(salary)
);
SUB QUERIES: A subquery is a SQL query nested inside another query (called the main or outer
query). It helps in breaking down complex queries into smaller parts and retrieving results
dynamically. The subquery executes first, and its result is used by the main query.
• Single-row subquery → Returns one value (use =, >, <, <=, >=, <>).
• Multi-row subquery → Returns multiple values (use IN, ANY, ALL).
• Multi-column subquery → Returns multiple columns (use with IN).
FROM student
GROUP BY dept;
FROM employee;
Aggregation: Aggregate functions in DBMS perform calculations on multiple rows of a column and
return a single value. These are commonly used with the GROUP BY clause.
Output: 5
Output: 246000
Output: 79.6
Output: 68
Output: 92
Grouping:
1. GROUP BY Clause
• The GROUP BY clause is used to group rows that have the same values in specified columns.
• It is typically used with aggregate functions like COUNT(), SUM(), AVG(), MIN(), and
MAX().
• Syntax:
Output:
Department Student_count
CSE 2
ECE 2
ME 1
2. HAVING Clause:
• The HAVING clause is used to filter groups based on aggregate function results. It is similar
to WHERE, but WHERE cannot be used with aggregate functions.
• Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
• Using HAVING to Filter Aggregates (Departments with Average Marks > 75)
• SELECT Department, AVG(Marks) AS Avg_Marks
FROM Student
GROUP BY Department
HAVING AVG(Marks) > 75;
Output:
Department Avg_Marks
Alice 85
Charlie 92
Ordering:
3. ORDER BY Clause
• The ORDER BY clause is used to sort the result set in ascending (ASC) or descending
(DESC) order.
• Syntax:
SELECT column_name
FROM table_name
ORDER BY column_name [ASC|DESC];
• Retrieve student names and marks, sorted by marks in descending order.
SELECT Name, Marks
FROM Student
ORDER BY Marks DESC;
Output:
Name Marks
Charlie 92
Alice 85
Bob 78
Eva 75
David 68
SQL joins are the foundation of database management systems, enabling the combination of data
from multiple tables based on relationships between columns. Joins allow efficient data retrieval,
which is essential for generating meaningful observations and solving complex business queries.
SQL JOIN:
• SQL JOIN clause is used to query and access data from multiple tables by
establishing logical relationships between them. It can access data from multiple tables
simultaneously using common key values shared across different tables. We can use SQL
JOIN with multiple tables. It can also be paired with other clauses, the most popular use will
be using JOIN with WHERE clause to filter data retrieval.
• A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
• Consider the two tables, Student and StudentCourse, which share a common
column ROLL_NO. Using SQL JOINS, we can combine data from these tables based on
their relationship, allowing us to retrieve meaningful information like student details along
with their enrolled courses.
• Both these tables are connected by one common key (column) i.e ROLL_NO. We can
perform a JOIN operation using the given SQL query:
• There are many types of Joins in SQL. Depending on the use case, we can use different type
of SQL JOIN clause. Below, we explain the most commonly used join types with syntax and
examples:
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• Natural Join
1. SQL 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;
• Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.
• Example: This query will show the names and age of students enrolled in different courses.
• Query:
2. SQL LEFT JOIN: LEFT 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_colum
• Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.n =
table2.matching_column;
• In this example, the LEFT JOIN retrieves all rows from the Student table and the matching
rows from the StudentCourse table based on the ROLL_NO column.
• Query:
• SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
3. SQL RIGHT JOIN: RIGHT 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. It is very similar to LEFT 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.
• In this example, the RIGHT JOIN retrieves all rows from the StudentCourse table and the
matching rows from the Student table based on the ROLL_NO column.
• Query:
• SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
4. SQL 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;
• This example demonstrates the use of a FULL JOIN, which combines the results of
both LEFT JOIN and RIGHT JOIN. The query retrieves all rows from
the Student and StudentCourse tables. If a record in one table does not have a matching
record in the other table, the result set will include that record with NULL values for the
missing fields
• Query:
• SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
• Output
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
5. SQL 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 table must have at least one common column with same column name and same data
type.
• 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.
• SELECT *
FROM table1
• SELECT *
FROM Employee
• Output:
VIEWS:
• In SQL, views contain rows and columns similar to a table, however, views don't hold the
actual data.
• You can think of a view as a virtual table environment that's created from one or more tables
so that it's easier to work with data.
Creation and Dropping of Views
• A view is a virtual table in SQL that is based on the result of a SELECT query. It does not
store data physically but provides a way to simplify complex queries.
1. Creating a View
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Creating a View for CSE Students
If you no longer need a view, you can remove it using DROP VIEW.
Syntax:
DROP VIEW view_name;
Types of Views:
• Updatable Views
• Non-Updatable Views
Updatable Views: An updatable view allows users to perform INSERT, UPDATE, and DELETE
operations, which reflect changes in the underlying table(s).
FROM Customers;
• Since this view is based on a single table without any complex operations, we can update
records using:
• UPDATE customer_view
Non-Updatable Views: A non-updatable view is a read-only view, meaning we can SELECT data
but cannot perform INSERT, UPDATE, or DELETE operations.
• When is a View Non-Updatable?
FROM Customers
• Since this view is based on multiple tables using a JOIN, we cannot update it directly.
• Example:
BEGIN
END;
• This ensures that updates on the view are redirected to the appropriate base table.
Relational Set Operations: Relational Set Operations refer to a group of operations in Relational
Algebra that manipulate relations (tables) based on set theory principles. These operations allow
the combination, comparison, and transformation of relations to retrieve meaningful results. To
perform these operations, the relations must often be union-compatible, meaning they have the
same number of attributes with matching data types. These operations provide fundamental ways
to manipulate relational data and are crucial for query processing in relational databases.
3. Set-Difference ( − ): Retrieves tuples that are in the first relation but not in the second.
4. Cartesian Product ( × ): Pairs every tuple from the first relation with every tuple from the second
relation.