Notes DBMS
Notes DBMS
SQL operators are reserved keywords used in the WHERE clause of a SQL
statement to perform arithmetic, logical and comparison operations.
Operators act as conjunctions in SQL statements to fulfill multiple conditions
in a statement.
Since, there are different types of operators in SQL, let us understand the
same in the next section of this article on SQL operators.
Arithmetic Operators
Operato
Operation Description
r
+ Addition Add values on either side of the operator
Used to subtract the right hand side value from the
– Subtraction
left hand side value
Multiplicatio Multiples the values present on each side of the
*
n operator
Divides the left hand side value by the right hand
/ Division
side value
Divides the left hand side value by the right hand
% Modulus
side value; and returns the remainder
Example:
1SELECT 40 + 20;
2
3SELECT 40 - 20;
4
5SELECT 40 * 20;
6
7SELECT 40 / 20;
1
DBMS
8
9SELECT 40 % 20;
60
20
800
Logical Operators
The logical operators are used to perform operations such as ALL, ANY, NOT,
BETWEEN etc.
Operato
Description
r
BETWEE
Searches for values within the range mentioned.
N
SOME Similar to the ANY operator, and is used compares a specific value
2
DBMS
Example:
Example[ANY]
2WHERE Age > ANY (SELECT Age FROM Students WHERE Age > 21);
Output:
1 Atul Mishra 23
5 Vaibhav Gupta 25
Output:
1 Atul Mishra 23
Example[IN]
Output:
1 Atul Mishra 23
4 Akanksha Jain 20
3
DBMS
SQL Date Functions are built-in tools used to handle, modify, and analyze
date/time values in a database. They help perform tasks like retrieving
current dates, calculating differences, and formatting results effectively.
Let's use the sales table as the base for demonstrating each of the SQL Date
Functions mentioned. Here’s the structure of the sales table:
sales Table
1. NOW()
The NOW() function retrieves the server’s current date and time, making it
useful for capturing exact event moments such as transaction timestamps,
as well as for logging and comparing time-based records.
Query:
Output:
4
DBMS
2. CURDATE()
Query:
Output:
3. CURTIME()
The CURTIME() function returns the current time in HH:MM:SS format and is
useful for time-based operations, such as scheduling or performing precise
time comparisons.
Query:
Output:
4. DATE()
The DATE() function extracts only the date from a date or datetime value,
making it useful for situations where the time component should be ignored,
such as date-only comparisons or aggregations.
Query:
5
DBMS
Output
5. EXTRACT()
The EXTRACT() function retrieves a specific part of a date such as the year,
month, or day, making it useful for grouping, filtering, or performing time-
based analysis including year-over-year reports.
Query:
Output:
6. DATE_ADD()
6
DBMS
The DATE_ADD() function adds a chosen time interval such as days, months,
or years to a date, making it useful for calculating future dates and
simplifying planning or scheduling tasks.
Query:
Output:
7. DATE_SUB()
Query:
Output:
7
DBMS
8. DATEDIFF()
The DATEDIFF() function returns the number of days between two dates,
making it useful for calculating durations such as deadlines or overdue
periods. In this case, it shows how many days remain from each sale date
until August 15, 2024.
Query:
Output:
9. DATE_FORMAT()
8
DBMS
Query:
Output:
10. ADDDATE()
Query:
Output:
9
DBMS
11. ADDTIME()
Query:
Output:
SQL string functions help manipulate and format text data efficiently. They
are widely used for cleaning, comparing, and extracting meaningful
information from textual fields.
String functions are used to perform an operation on input string and return
an output string. Below are some of the most commonly used SQL string
functions:
10
DBMS
1. CONCAT()
Query:
Output:
John Doe
2. CHAR_LENGTH() / CHARACTER_LENGTH()
Query:
Output:
Query:
Output:
HELLO
hello
4. LENGTH()
LENGTH() returns the length of a string in bytes. This can be useful for
working with multi-byte character sets.
Query:
11
DBMS
Output:
5. REPLACE()
Query:
Output:
Hello SQL
6. SUBSTRING() / SUBSTR()
Query:
Output:
Hello
The LEFT() and RIGHT() functions allow you to extract a specified number of
characters from the left or right side of a string, respectively. It is used for
truncating strings for display.
Query:
Output:
Hello
World
12
DBMS
8. INSTR()
The INSTR() function is used to find the position of the first occurrence of a
substring within a string. It returns the position (1-based index) of the
substring. If the substring is not found, it returns 0. This function is
particularly useful for locating specific characters or substrings in text data.
Query:
Output:
9. TRIM()
The TRIM() function removes leading and trailing spaces (or other specified
characters) from a string. By default, it trims spaces but can also remove
specific characters using TRIM(character FROM string). This is helpful for
cleaning text data, such as user inputs or database records.
Query:
Output:
Hello World
10. REVERSE()
Query:
Output:
olleH
In SQL, beyond the basic string functions, there are several advanced string
functions that can help you manipulate and process string data more
effectively. These are the some additional SQL Functions.
13
DBMS
11. ASCII()
The ASCII() function returns the ASCII value of a single character. This is
helpful when we need to find the numeric code corresponding to a character,
often used in encoding and decoding text.
Query:
SELECT ascii('t');
Output:
116
12. CONCAT_WS()
Query:
Output:
geeks_for_geeks
13. FIND_IN_SET()
Query:
Output:
14. FORMAT()
14
DBMS
Query:
Output:
‘98.10%’
15. LCASE()
Query:
Output:
geeksforgeeks to learn
16. LOCATE()
LOCATE() allows you to find the nth occurrence of a substring in a string. This
is especially useful when you need to locate a specific substring based on its
position.
Query:
Output:
17. LPAD()
Query:
Output:
000geeks
18. MID()
15
DBMS
MID() extracts a substring starting from a given position in a string and for a
specified length. It is useful when you want to extract a specific portion of a
string.
Query:
Output:
fo
19. POSITION()
Query:
Output:
20. REPEAT()
Query:
Output:
geeksgeeks
21. RPAD()
RPAD() pads the right side of a string with specified characters to a fixed
length. This is often used to format text or numbers to a desired size.
Query:
RPAD('geeks', 8, '0');
Output:
‘geeks000’
16
DBMS
22. RTRIM()
Query:
RTRIM('geeksxyxzyyy', 'xyz');
Output:
‘geeks’
23. SPACE()
Query:
SELECT SPACE(7);
Output:
‘ ‘
24. STRCMP()
STRCMP() compares two strings and returns an integer value based on their
lexicographical comparison. This is useful for sorting or checking equality
between two strings. STRCMP(string1, string2) returns:
Query:
Output:
17
DBMS
1. Selection(σ)
The Selection Operation is basically used to filter out rows from a given table
based on certain given condition. It basically allows us to retrieve only those
rows that match the condition as per condition passed during SQL Query.
A B C
1 2 4
18
DBMS
A B C
2 2 3
3 2 3
4 3 4
Output:
A B C
1 2 4
4 3 4
Explanation: The selection operation only filters rows but does not display
or change their order. The projection operator is used for displaying specific
columns.
2. Projection(π)
Output:
19
DBMS
B C
2 4
2 3
3 4
3. Union(U)
The Union Operator is basically used to combine the results of two queries
into a single result. The only condition is that both queries must return same
number of columns with same data types. Union operation in relational
algebra is the same as union operation in set theory.
FRENCH
Student_Nam Roll_Numbe
e r
Ram 01
Mohan 02
Vivek 13
Geeta 17
GERMAN
20
DBMS
Student_Nam Roll_Numbe
e r
Vivek 13
Geeta 17
Shyam 21
Rohan 25
π(Student_Name)(FRENCH) U π(Student_Name)(GERMAN)
Output:
Student_Na
me
Ram
Mohan
Vivek
Geeta
Shyam
Rohan
21
DBMS
Student_Na
me
Explanation: The only constraint in the union of two relations is that both
relations must have the same set of Attributes.
4. Set Difference(-)
Set difference basically provides the rows that are present in one table, but
not in another tables. Set Difference in relational algebra is the same set
difference operation as in set theory.
π(Student_Name)(FRENCH) - π(Student_Name)(GERMAN)
Student_Na
me
Ram
Mohan
5. Rename(ρ)
22
DBMS
A B C
1 2 4
2 2 3
3 2 3
4 3 4
Output Table:
A D C
1 2 4
2 2 3
3 2 3
4 3 4
6. Cartesian Product(X)
The Cartesian product combines every row of one table with every row of
another table, producing all the possible combination. It's mostly used as a
precursor to more complex operation like joins. Let’s say A and B, so the
cross product between A X B will result in all the attributes of A followed by
each attribute of B. Each record of A will pair with every record of B.
Relation A:
23
DBMS
Ram 14 M
Sona 15 F
Kim 20 M
Relation B:
ID Course
1 DS
2 DBMS
Output: If relation A has 3 rows and relation B has 2 rows, the Cartesian
product A × B will result in 6 rows.
Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
Kim 20 M 1 DS
24
DBMS
Kim 20 M 2 DBMS
Explanation: If A has 'n' tuples and B has 'm' tuples then A X B will have
'n*m' tuples.
Derived operators are built using basic operators and include operations like
join, intersection, and division. These operators help perform more complex
queries by combining basic operations to meet specific data retrieval needs.
1. Join Operators
Join operations in relational algebra combine data from two or more relations
based on a related attribute, allowing for more complex queries and data
retrieval. Different types of joins include:
a. Conditional Join:
b. Equi Join:
c. Natural Join:
25
DBMS
An outer join returns all rows from one relation, and the matching rows from
the other relation. If there is no match, the result will still include all rows
from the outer relation with NULL values in the columns from the unmatched
relation.
A left outer join returns all rows from the left relation and the matching
rows from the right relation.
If there is no match, the result will include NULL values for the right
relation’s attributes.
A right outer join returns all rows from the right relation and the
matching rows from the left relation.
If no match exists, the left relation's columns will contain NULL values.
A full outer join returns all rows when there is a match in either the left
or right relation.
26
DBMS
Example: Joining Customers and Orders using a full outer join will
return all customers and orders, even if there’s no corresponding order
for a customer or no customer for an order.
2. Set Intersection(∩)
Set Intersection basically allows to fetches only those rows of data that are
common between two sets of relational tables. Set Intersection in relational
algebra is the same set intersection operation in set theory.
Relation FRENCH
Student_Nam Roll_Numbe
e r
Ram 01
Mohan 02
Vivek 13
Geeta 17
Relation GERMAN
Student_Nam Roll_Numbe
e r
Vivek 13
Geeta 17
Shyam 21
27
DBMS
Student_Nam Roll_Numbe
e r
Rohan 25
From the above table of FRENCH and GERMAN, the Set Intersection is used
as follows:
π(Student_Name)(FRENCH ∩ π(Student_Name)(GERMAN)
Output:
Student_Na
me
Vivek
Geeta
3. Division (÷)
The Division Operator is used to find tuples in one relation that are related to
all tuples in another relation. It’s typically used for "for all" queries.
Student_ Course_
ID ID
101 C1
101 C2
28
DBMS
Student_ Course_
ID ID
102 C1
103 C1
103 C2
Course_
ID
C1
C2
Example: Query is to find students who are enrolled in all courses listed in
the Course table. In this case, students must be enrolled in both C1 and C2.
Output:
Student_
ID
101
103
29
DBMS
elational Calculus
{ t | P(t) }
∧: AND
∨: OR
¬: NOT
30
DBMS
Quantifiers:
For example, let's say we have a table called "Employees" with the
following attributes:
Employee ID
Name
Salary
Department
ID
To retrieve the names of all employees who earn more than $50,000 per
year, we can use the following TRC query:
Explanation:
The result is a set of tuples where each employee earns more than
$50,000.
31
DBMS
{t| P(t)}
P(t) may have various conditions logically combined with OR (∨), AND (∧),
NOT(¬).
{<a1,a2,a3,.....an> | P(a1,a2,a3,.....an)}
where a1,a2,...an are the attributes of the relation and P is the condition.
Table Customer
Customer Stre
name et City
Saurabh A7 Patiala
Jalandh
Mehak B6
ar
Ludhian
Sumiti D9
a
32
DBMS
Customer Stre
name et City
Ria A5 Patiala
Table Branch
Branch Branch
name City
ABC Patiala
DEF Ludhiana
GHI Jalandhar
Table Account
Table Loan
33
DBMS
Table Borrower
Customer Loan
name number
Saurabh L33
Mehak L49
Ria L98
Table Depositor
Customer Account
name number
Saurabh 1111
Mehak 1113
34
DBMS
Customer Account
name number
Suniti 1114
Example 1: Find the loan number, branch, and amount of loans greater than
or equal to 10000 amount.
Resulting relation:
Example 2: Find the loan number for each loan of an amount greater or
equal to 10000.
Loan
number
L33
35
DBMS
Loan
number
L35
L98
Example 3: Find the names of all customers who have a loan and an
account at the bank.
Customer
name
Saurabh
Mehak
Example 4: Find the names of all customers having a loan at the "ABC"
branch.
{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name]
∧ ∃ u ∈ loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-
number]))}
Resulting relation:
Customer
name
Saurabh
Key Concepts:
36
DBMS
TRC does not specify execution steps, only the condition of result.
Relationa
Feature TRC l Algebra
How to
What to retrieve
Focus retrieve
Set-based
Logical expressions
Expression Style operators
Directly
Abstract, not directly
convertible
executable
Execution to query
Basis for
Theoretical foundation query
Use in DBMS execution
37
DBMS
{ t | P(t) }
∧: AND
∨: OR
¬: NOT
Quantifiers:
For example, let's say we have a table called "Employees" with the
following attributes:
Employee ID
Name
Salary
Department
ID
38
DBMS
To retrieve the names of all employees who earn more than $50,000 per
year, we can use the following TRC query:
Explanation:
The result is a set of tuples where each employee earns more than
$50,000.
{t| P(t)}
P(t) may have various conditions logically combined with OR (∨), AND (∧),
NOT(¬).
{<a1,a2,a3,.....an> | P(a1,a2,a3,.....an)}
where a1,a2,...an are the attributes of the relation and P is the condition.
39
DBMS
Table Customer
Customer Stre
name et City
Saurabh A7 Patiala
Jalandh
Mehak B6
ar
Ludhian
Sumiti D9
a
Ria A5 Patiala
Table Branch
Branch Branch
name City
ABC Patiala
DEF Ludhiana
GHI Jalandhar
Table Account
40
DBMS
Table Loan
Table Borrower
Customer Loan
name number
Saurabh L33
41
DBMS
Customer Loan
name number
Mehak L49
Ria L98
Table Depositor
Customer Account
name number
Saurabh 1111
Mehak 1113
Suniti 1114
Example 1: Find the loan number, branch, and amount of loans greater than
or equal to 10000 amount.
Resulting relation:
42
DBMS
Example 2: Find the loan number for each loan of an amount greater or
equal to 10000.
Loan
number
L33
L35
L98
Example 3: Find the names of all customers who have a loan and an
account at the bank.
Customer
name
Saurabh
Mehak
Example 4: Find the names of all customers having a loan at the "ABC"
branch.
43
DBMS
{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name]
∧ ∃ u ∈ loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-
number]))}
Resulting relation:
Customer
name
Saurabh
Key Concepts:
TRC does not specify execution steps, only the condition of result.
Relation
al
Feature TRC Algebra
Procedur
Non-procedural
Type al
How to
What to retrieve
Focus retrieve
Set-
Logical expressions based
Expression Style operators
44
DBMS
Relation
al
Feature TRC Algebra
Directly
Abstract, not directly convertib
executable le to
Execution query
Basis for
query
Theoretical foundation
executio
Use in DBMS n
45