0% found this document useful (0 votes)
67 views42 pages

DBMS 2nd Unit Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views42 pages

DBMS 2nd Unit Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Unit 2

 Fundamentals of RDBMS:
 A Relational database management system (RDBMS) is a database
management system (DBMS) that is based on the relational model.
 In RDBMS data is stored in different tables, theses tables are interlinked
with each other with the help of common fields (columns) in between them.
 In such database the data and relations between them are organized into
tables.

 What is a table?
 Table is a collection of data which is organized in terms of rows and
columns.
 This table is basically a collection of related data entries and data is stored in
database objects.
 Example of a CUSTOMERS table which stores customer's ID, Name, Age,
Salary, City and Country

 What is a field?
 Every table is broken up into smaller segments called fields.
 A field in a table that is designed to maintain specific information about
every record in the table.
 For example, CUSTOMERS table consists of different fields like ID, Name,
Age, Salary, City and Country.

 What is a Record or a Row?


 A record is also called as a row of data where each individual set of entries
that exists in a table
 Rows are horizontal elements in a table.

 What is a NULL value?


 A NULL value in a table is a value in a field that appears to be blank, which
means a field with no value.
 It is very important to understand that a NULL value is different than a zero
value or a field that contains spaces.
 Advantages of RDBMS:

 Ease of Use: Data stored in a tabular format in rows and columns makes
accessing, retrieving, and manipulating the data in simple manner.
 Flexibility: Information can be retrieved easily by using tables and changes
can be done easily by using operations
 Security: Security management sets rules that allow access in the
database.This function also restricts on what specific data any user can see
or write
 Maintenance: It is simple to use. It allows database admins to easily
maintain, control, and update data in the database. Backing up data is easy
with RDMS.
 Data Structure: This feature stores data in a user-friendly table format.
Data are organized in a structured manner
 Dr Edgar F Codd’s Twelve Commandments

Rule 0: The Foundation Rule

 The database must be in relational form. So that the system can handle the
database through its relational capabilities.

Rule 1: Information Rule


 A database contains various information, and this information must be
stored in each cell of a table in the form of rows and columns.

 Everything in database must be stored in the tabular format


Rule 2: Guaranteed Access Rule

 Every single data (atomic value) may be accessed logically from a relational
database using the combination of primary key value, table name, and
column name.

Rule 3: Systematic Treatment of Null Values

 This rule defines the systematic treatment of Null values in database records.

 The null value has various meanings in the database, like missing the data,
no value in a cell

 It should allow a field to remain empty.

 But the primary key should not be null.

Rule 4: Active Online Catalog


 The structure description (Table attribute, name, size) of the entire database
must be stored in online catalog known as data dictionary, which can be
accessed by authorized users.
 Same query language is used to access catalog, which they are using for
database access.
Rule 5: Comprehensive Data Sub Language Rule

 Data sub language rule states that database needs to support minimum one
clearly defined language.

 This language should be capable of handling data manipulation and


transaction management operations.

 If the database allows access to the data without any language, it is


considered a violation of the database.

Rule 6: View Updating Rule

 All views table can be theoretically updated and must be practically updated
by the database systems.
Rule 7: Relational Level Operation (High-Level Insert, Update and delete)
Rule
 A database system should follow high-level relational operations such as
insert, update, and delete in each level or a single row.
 It also supports union, intersection and minus operation in the database
system.

Rule 8: Physical Data Independence Rule


 All stored data in a database or an application must be physically
independent to access the database.
 Each data should not depend on other data or an application.
 If data is updated or the physical structure of the database is changed, it will
not show any effect on conceptual level.

Rule 9: Logical Data Independence Rule


 It is similar to physical data independence. It means, if any changes occurred
to the logical level (table structures), it should not affect the user's view
(application

Rule 10: Integrity Independence Rule

 A database must maintain integrity independence when inserting data into


table's cells using the SQL query language.

 All entered values should not be changed.

Rule 11: Distribution Independence Rule

 The distribution independence rule represents a database that must work


properly, even if it is stored in different locations and used by different end-
users.

 Suppose a user accesses the database through an application; in that case,


they should not be aware that another user uses particular data, and the data
they always get is only located on one site.

 The end users can access the database, and these access data should be
independent for every user to perform the SQL queries.
Rule 12: Non Subversion Rule

 There should not exist a way to modify or change for database structure
except database language
 Example: SQL

Types of Keys:

1. Super Key

2. Candidate Key

3. Primary Key

4. Alternate Key

5. Foreign key

6. Composite Key

1. Super Key: A super key is a combination of all possible attributes that


can uniquely identify the rows(or tuples)in the given relation.

 Super Key is a superset of a candidate key.

 A table can have many super keys.

 A super key may have additional attribute that are not needed for
unique identity.

Emp_ID Emp_name Emp_Adharno Emp_phno Dept_Id


01 Priya 1023456987 9874563212 41
02 Seeta 1026655489 8451320656 42
03 Seeta 6662323654 4565412121 43
04 Geeta 4546512245 4545548546 42

Super Keys:
1.{Emp_id} 2.{Emp_Adhar}

3.{Emp_id,Emp_name}

4.{Emp_id,Emp_Adharno}

5.{Emp_adharno,Emp_name}

6.{Emp_id,Emp_adharno,Emp_name}

7{Emp_adharno,Emp_name,Emp_phno}

2. Candidate Key: A candidate key is an attribute or set of an attribute which can


uniquely identify a tuple.

 A candidate key is a minimal set of super key, or super key with no


redundant attributes.

 It is called a minimal super key because we select a candidate key from a set
of super key.

 Candidate keys are defined as distinct set of attributes from which primary
key can be selected

 Candidate keys are not allowed to have NULL Values

Candidate Key

Emp_ID Emp_name Emp_Adharno Emp_phno Dept_Id


01 Priya 1023456987 9874563212 41
02 Seeta 1026655489 8451320656 42
03 Seeta 6662323654 4565412121 43
04 Geeta 4546512245 4545548546 42

Candidate Keys:

1. {Emp_id}

2. {Emp_adharno}
3. Primary Key: A primary key is one of the candidate key chosen by the
database designer to uniquely identify the tuple in the relation.

 The value of primary key can never be NULL

 The value of primary key must always be unique (not duplicate).

 The values of primary key can never be changed (no updation is


possible)

 The value of primary key must be assigned when inserting a record.

 A relation is allowed to have only one primary key.

Primary key

Emp_ID Emp_name Emp_Adharno Emp_phno Dept_Id


01 Priya 1023456987 9874563212 41
02 Seeta 1026655489 8451320656 42
03 Seeta 6662323654 4565412121 43
04 Geeta 4546512245 4545548546 42

Primary Key: 1. {Emp_id}

4. Alternate Keys: Out of all candidate keys, only one gets selected as
primary key, remaining keys are known as alternate keys.

In the Employee table

 Emp_id is suited for primary key

 Rest of the attributes of candidate are alternate key like Emp_adharno

Primary Key Alternate Key

Emp_ID Emp_name Emp_Adharno Emp_phno Dept_Id


01 Priya 1023456987 9874563212 41
02 Seeta 1026655489 8451320656 42
03 Seeta 6662323654 4565412121 43
04 Geeta 4546512245 4545548546 42

Alternate Key: 1. {Emp_adharno}

5. Foreign Key: A foreign key is used to link two tables together.

 An attribute (or set of attributes) in one table that refers to the primary
key in another table.

 The purpose of the foreign key is to ensure referential integrity of the


data

Employee Table (Referencing Relation) (ForeignKeyof


Department Table)

Emp_ID Emp_name Emp_Adharno Emp_phno Dept_Id


01 Priya 1023456987 9874563212 41
02 Seeta 1026655489 8451320656 42
03 Seeta 6662323654 4565412121 43
04 Geeta 4546512245 4545548546 42
(Primary Key of Department Table)

Department Table (Referenced Relation)

Dept_Id Dept_Name
41 Sales
42 Marketing
43 HR

Foreign Key: Dept_Id

Foreign Key:
 Foreign Key references the primary key of the table.
 Foreign key can take only those values which are present in the primary key
of the referenced relation.
 Referenced relation may also be called as the master table or primary table.
 Referencing relation may also be called as the foreign table.
6. Composite Key: A Key that has more than one attribute is known as
composite key.
Normalization:
 Normalization is the process of organizing the data in the database.
 The normal form is used to reduce redundancy from the database table.
 Data redundancy in dbms means having the same data at multiple places.
 Normalization is used to minimize the redundancy from a relation or set of
relations. It is also used to eliminate Insertion, Update, and Deletion
Anomalies.
 A database anomaly is a error in the database that occurs because of data
redundancy
 Normalization divides the larger table into smaller and links them using
relationships.

Name Rollno Section


Sai 21 A
Sai 21 A
Shiva 22 B
Ramesh 23 C

1. Insert Anomalies: This occurs when we are not able to insert data
into a database because some columns may be missing at the time of
insertion.
EX: Insert into student(“Raj”,24,”B”,19);
2. Updation Anomalies: This occurs when the same data items are
repeated with same values.
Ex: two similar values
Name Rollno Section
Sai 21 A
Sai 21 A

3. Deletion Anomalies: This occurs when deleting one part of data


deletes the other necessary information from the database.
Ex: Automatically deletes
Name Rollno Section
Sai 21 A
Sai 21 A
Shiva 22 B
Ramesh 23 C

Types of Normal Forms:

 Normalization works through a series of stages called Normal forms.


 The normal forms apply to individual relations. The relation is said to be in
particular normal form if it satisfies constraints.

First Normal Form (1NF)


Normal Description
Form

1NF A relation is in 1NF if it contains an atomic value and no multi value attribute.

2NF A relation will be in 2NF if it is in 1NF and all non-key attributes are full
functional dependent on the primary key.

3NF A relation will be in 3NF if it is in 2NF and no transition dependency exists.

Advantages of Normalization

o Normalization helps to minimize data redundancy.


o Greater overall database organization.
o Data consistency within the database.
o Much more flexible database design.

First Normal Form (1NF)


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

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


EMP_PHONE.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385, UP
9064738238

20 Harry 8574783832 Bihar

12 Sam 7390372389, Punjab


8589830302

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

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385 UP

14 John 9064738238 UP

20 Harry 8574783832 Bihar

12 Sam 7390372389 Punjab

12 Sam 8589830302 Punjab

Second Normal Form (2NF)


o In the 2NF, relational must be in 1NF.
o In the second normal form, all non-key attributes are fully functional
dependent on the primary key
Stud_id Proj_Id Stud_name Proj_name
1 P1 Ram Banking
2 P2 Sham Library
3 P3 Seeta College
4 P4 Geeta Library

 Here stud_name is dependant on stud_id


 Proj_name is dependant on proj_id and stud id, which violates 2NF.

Stud_id Stud_name
1 Ram
2 Sham
3 Seeta
4 Geeta

Proj_Id Proj_name
P1 Banking
P2 Library
P3 college
P4 Library

Third Normal Form (3NF)


o A relation will be in 3NF if it is in 2NF and not contain any transitive partial
dependency
o Partial Dependency (Non prime attribute depends on non prime attribute).
o If there is no transitive dependency for non-prime attributes, then the
relation must be in third normal form.
Example:

EMPLOYEE_DETAIL table:

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY

222 Harry 201010 UP Noida

333 Stephan 02228 US Boston

444 Lan 60007 US Chicago

555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Non-prime attributes: In the given table, all attributes except EMP_ID are
non-prime.

Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and EMP_ZIP


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

That's why we need to move the EMP_CITY and EMP_STATE to the new
<EMPLOYEE_ZIP> table, with EMP_ZIP as a Primary key.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228

444 Lan 60007

555 Katharine 06389

666 John 462007


EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY

201010 UP Noida

02228 US Boston

60007 US Chicago

06389 UK Norwich

462007 MP Bhopal

SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.

Datatype of SQL:

Data Type Properties

These are used to store numeric values. Examples include INT,


Numeric data types
BIGINT, DECIMAL, and FLOAT.

Character data These are used to store character strings. Examples include CHAR,
types VARCHAR, and TEXT.

These are used to store date and time values. Examples include
Date and time data
DATE, TIME, and TIMESTAMP
types
.

These are used to store binary data. Examples include Binary,


Binary data types
BYTEA.

This data type is used to store logical values. The only possible
Boolean data type
values are TRUE and FALSE.
SQL Commands
o SQL commands are instructions.
o It is used to communicate with the database. It is also used to perform
specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop
the table, modify the table, set permission for users.

Types of SQL Commands

There are four types of SQL commands: DDL, DML, DCL and DQL.

1. Data Definition Language (DDL)


o DDL changes the structure of the table like creating a table, deleting a table,
altering a table, etc.
o It is used to define and modify the data and structure of table.
o All the command of DDL are auto-committed that means it permanently
save all the changes in the database.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP
o TRUNCATE

a. CREATE It is used to create a new table in the databaseJava Try Catch

Syntax: CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), D


OB DATE);

b. ALTER: It is used to alter the structure of the database. This change could be
either to modify the characteristics of an existing attribute or probably to add a new
attribute.

Syntax: To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-datatype;

To modify existing column in the table:

2. ALTER TABLE table_name MODIFY(column_datatype....);

To delete existing column in the table:

3. ALTER TABLE table_name DROP COLUMN column_name;

EXAMPLE:

1. Alter table stu_details add address varchar2(50);


2. Alter table stu_details modify name varchar2(20);
3. Alter table stu_details drop email;
b. DROP: It is used to delete both the structure and table from database
permanently.

It removes an existing table along with its structure from the database.

1. Syntax: DROP TABLE table_name;

Example: DROP TABLE EMPLOYEE;

2. Syntax: DROP DATABASE database_name;

Example: DROP DATABASE COMPANY;

D. Truncate: It is used to delete all the records from the table,delete all the rows
from the table but structure of table remains same.

Syntax: TRUNCATE TABLE table_name;

Example: TRUNCATE TABLE EMPLOYEE;

E. Rename: The RENAME syntax helps in changing the name of the table.

1. Syntax: RENAME old_table _name To new_table_name ;

Example: Rename stud to students

2. Syntax: ALTER TABLE old_table_name RENAME TO new_table_name;

Example: ALTER TABLE Emp RENAME TO Employee_Details ;

F. DESC: It is used to display structure of table

Syntax: Desc tablename;

Example: Desc students;

2. Data Manipulation Language


o DML commands are used to modify the database. It is responsible for all
form of changes in the database.
o The command of DML is not auto-committed that means it can't
permanently save all the changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into
the row of a table.

1. Syntax: INSERT INTO TABLE_NAME


(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);
Or

1. INSERT INTO TABLE_NAME


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

For example: INSERT INTO javatpoint (Author, Subject) VALUES ("Singh", "DBMS");

2. Syntax: INSERT INTO TABLE_NAME


Values(value1, value2, value3, .... valueN) ,
(value1, value2, value3, .... valueN);

Example: INSERT INTO employee_details


VALUES ('E40004','SANTHOSH','E102',25),
('E40005','THAMAN','E103',26);

b. UPDATE: This command is used to update or modify the value of a column in


the table.

Syntax:UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHE


RE CONDITION]

For example:
1. UPDATE students
SET User_Name = 'Siya'
WHERE Student_Id = '3'
c. DELETE: It is used to remove one or more row from a table.

Syntax: DELETE FROM table_name [WHERE condition];

For example: DELETE FROM javatpoint


WHERE Author="Singh";

3. Data Control Language

These are the types of DCL commands that are used to assign permission to the
users to perform a different task.

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

Syntax: GRANT privilege_name(s)


ON object
TO user_account_name;

Example: GRANT SELECT


ON Student
to director;
GRANT SELECT
ON Student
TO Director

Parameters Used:
 privileges_name: These are the access rights or privileges granted to the user.
 object: In the case of granting privileges on a table, this would be the table
name.
 user:It is the name of the user to whom the privileges would be granted.

Privileges: The privileges that can be granted to the users are listed below along
with_description:

b. Revoke: It is used to take back permissions from the user.

1. REVOKE privilege_name(s)
ON object
FROM user_account_name;

Example: Revoke insert, select


on accounts
from Ram
Sno Rollback Commit Savepoint
.

1. Rollback means the database DML commands saves Savepoint helps to save
is restored to the last modification and it the transaction
committed state permanently saves the temporarily.
transaction.

2. Syntax- ROLLBACK [To Syntax- COMMIT; Syntax- SAVEPOINT


SAVEPOINT_NAME]; [savepoint_name;]

3. Example- ROLLBACK Example- SQL> Example- SAVEPOINT


Update5; COMMIT; table_create;

 These operations are automatically committed in the database that's why


they cannot be used while creating tables or dropping them.

 Here are some commands that come under TCL:

o COMMIT
o ROLLBACK
o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

 Whenever DDL commands such as INSERT, UPDATE and DELETE are


used, the changes made by these commands are permanent

 Syntax: COMMIT;

Example: DELETE FROM CUSTOMERS

WHERE AGE = 25;

COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already
been saved to the database.
Syntax: ROLLBACK;

Example:

1. DELETE FROM CUSTOMERS


WHERE AGE = 25;
ROLLBACK;

c. SAVEPOINT: It is used to save the transaction temporarily.

Syntax: SAVEPOINT SAVEPOINT_NAME;

Example: Savepoint deletion

5. Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

o SELECT

a. SELECT: This is the same as the projection operation of relational algebra. It is


used to select the attribute based on the condition described by WHERE clause.

Syntax:

1. SELECT column_name
FROM TABLES
WHERE conditions;

For example:

1. SELECT emp_name
FROM employee
WHERE age > 20;
Type of Data constraints

 Input/Output constraints: This constraints determines the speed of which


data are inserted or extracted from database table. For example Primary key,
Foreign key constraints.
 Business Rule constraints: These rules are applied to data prior(first) the data
being inserted into the table columns. For example Unique, Not NULL,
check constraints.

I/O Constraints:
a) Primary Key: The PRIMARY KEY constraint uniquely identifies each
record in a table.
 Primary keys must contain UNIQUE values, and cannot contain NULL
values. A table can have only ONE primary key; in the table.

Example: CREATE TABLE students (


S_Id int NOT NULL PRIMARY KEY,
FirstName varchar (255),
Address varchar (255));

b) Foreign Key: In the relational databases, a foreign key is a field or a column


that is used to establish a link between two tables.

 In simple words you can say that, a foreign key in one table used to point
primary key in another table.

 Here are two tables first one is students table and second is orders table.
 Here orders are given by students.
 First table:

S_Id LastName FirstName CITY

1 MAURYA AJEET ALLAHABAD

2 JAISWAL RATAN GHAZIABAD


3 ARORA SAUMYA MODINAGAR

 Second table:

O_Id OrderNo S_Id

1 99586465 2

2 78466588 2

3 22354846 3

4 57698656 1

Here you see that "S_Id" column in the "Orders" table points to the "S_Id" column
in"Students" table.

 The "S_Id" column in the "Students" table is the PRIMARY KEY in the "Students" table.
 The "S_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

Example: CREATE TABLE students(


S_Id int NOT NULL PRIMARY KEY,
FirstName varchar (255),
Address varchar (255));

CREATE TABLE Orders (


O_Id int,
Order_name Varchar(20),
S_Id int REFERENCES students(S_Id));
c). Unique Key Constraint: A unique constraint is the rule that the values of a key
are valid only if they are unique. A key that is constrained to have unique values is
called a unique key.

Roll number attribute is already assigned with the primary key and Citizen_ID
can have unique constraints where each entry in a Citizen_ID column should be
unique because each citizen of a country must have his or her Unique
identification number like an Aadhaar Number. But if the student is migrated to
another country in that case, he or she would not have any Citizen_ID and the
entry could have a NULL value as only one NULL is allowed in the unique
constraint.

Example: CREATE TABLE students (


S_Id int NOT NULL,
FirstName varchar (255),
Address varchar (255)
Unique(S_Id));

Extra Notes: Differences between Primary Key and Unique Key

Parameters PRIMARY KEY UNIQUE KEY

Used to serve as a unique Uniquely determines a


Basic identifier for each row in a row that isn’t the primary
table. key.

NULL value Cannot accept NULL


Can accept NULL values.
acceptance values.

Number of keys that


More than one unique
can be defined in Only one primary key
key
the table

We cannot change or
We can change unique
Modification delete values stored in
key values.
primary keys.

Syntax CREATE TABLE Student CREATE TABLE House


Parameters PRIMARY KEY UNIQUE KEY

(
(
House_Number INT
Student_Id INT
UNIQUE,
PRIMARY KEY,
House_Name
Student_name
VARCHAR(150),
VARCHAR(150),
House_Address
roll_number INT(10)
VARCHAR(250)
)
)

Business Rule Constraints:


a) Null: In SQL there may be some records in a table that do not have values or
data for every field and those fields are termed as a NULL value.
NULL values could be possible because at the time of data entry information is not
available.
 It is important to understand that a NULL value differs from a zero value.
Example: INSERT INTO Employee (Fname, Lname, SSN, Phoneno, Salary)
VALUES ('Shubham', 'Thakur', '123-45-6789', '9876543210', 50000.00),
('Aman', 'Chopra', '234-56-7890', NULL, 45000.00));

b) Not Null: The NOT NULL constraint is used to ensure that a given column
of a table is never assigned the null value.
Once a NOT NULL constraint has been defined for a particular column, any insert
or update operation that attempts to place a null value in that column will fail.
Example: CREATE TABLE students (
S_Id int NOT NULL,
FirstName varchar (255),
Address varchar (255));
c) Check Constraint in SQL
o Check constraint is validation or a rule which is applied on the column of a
table.
o When we apply check constraint to any column, it checks for specific values
while inserting any record.
o Check constraint can be created on a table level as well as column level.
o Check constraints can be applied only to a single column,
o Example: CREATE TABLE student(

StudentID INT NOT NULL,


Name VARCHAR(30) NOT NULL,
Age INT NOT NULL,
check(Age >= 17));

Arithmetic Operators

Arithmetic operators can perform arithmetical operations on numeric operands


involved. Arithmetic operators are addition(+), subtraction(-), multiplication(*)
and division(/). The + and - operators can also be used in date arithmetic.

Operator Meaning Operates on

+ (Add) Addition Numeric


value

- (Subtract) Subtraction Numeric


value

* Multiplication Numeric
(Multiply) value
/ (Divide) Division Numeric
value

% Returns the integer remainder of a division. For example, 17 % 5 Numeric


(Modulo) = 2 because the remainder of 17 divided by 5 is 2. value

Example: Update emp


Set esal=esal+3000
Where eid = 50;

2. Logical Operator:
Types of Logical Operators in SQL
Given below is the list of logical operators available in SQL.
Operator Meaning

AND TRUE if both Boolean expressions are TRUE.

IN TRUE if the operand is equal to one of a list of expressions.

NOT Reverses the value of any other Boolean operator.

OR TRUE if either Boolean expression is TRUE.

LIKE TRUE if the operand matches a pattern.

ALL TRUE if all of a set of comparisons are TRUE.

ANY TRUE if any one of a set of comparisons is TRUE.


Operator Meaning

EXISTS TRUE if a subquery contains any rows.

SOME TRUE if some of a set of comparisons are TRUE.

a. AND Operator
The AND operator is used to combines two or more conditions but if it is true
when all the conditions are satisfied.
Query
SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country
= 'India';

Output

b. IN Operator
It is used to remove the multiple OR conditions in SELECT, INSERT, UPDATE,
or DELETE. and We can also use NOT IN to minimize the rows in your list and
any kind of duplicate entry will be retained.
Query
SELECT * FROM employee WHERE emp_city IN ('Allahabad', 'Patna');
Output

c. NOT Operator
Query
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';
Output

d. OR Operator
The OR operator is used to combines two or more conditions but if it is true when
one of the conditions are satisfied.
Query
SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country =
'India';
Output

e. LIKE Operator
In SQL, the LIKE operator is used in the WHERE clause to search for a specified
pattern in a column.
 % – It is used for zero or more than one character.
 _ – It is used for only one character means fixed length.
Query
SELECT * FROM employee WHERE emp_city LIKE 'P%';
Output

f. BETWEEN Operator
The SQL BETWEEN condition allows you to easily test if an expression is
within a range of values (inclusive).
Query
SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;
Output

g. ALL Operator
The ALL operator returns TRUE if all of the subqueries values matches the
condition.
All operator is used with SELECT, WHERE, HAVING statement.
Query
SELECT * FROM employee WHERE emp_id = ALL
(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');
Output

h. ANY Operator
The ANY operator:
 It returns a boolean value as a result
 It returns TRUE if ANY of the subquery values match the condition
Query
SELECT * FROM employee WHERE emp_id = ANY
(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');
Output

i. EXISTS Operator
In SQL,Exists operator is used to check whether the result of a correlated nested
query is empty or not.
Exists operator is used with SELECT, UPDATE, INSERT or DELETE
statement.
Query
SELECT emp_name FROM employee WHERE EXISTS
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');
Output

j. SOME Operator
In SQL, SOME operators are issued with comparison operators (<,>,=,<=, etc) to
compare the value with the result of a subquery.
Query
SELECT * FROM employee WHERE emp_id < SOME
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');
Output

SET Operators in SQL


SET operators are special type of operators which are used to combine the
result of two queries.

Operators covered under SET operators are:

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

There are certain rules which must be followed to perform operations using SET
operators in SQL. Rules are as follows:

1. The number and order of columns must be the same.


2. Data types must be compatible.

Let us see each of the SET operators in more detail with the help of
examples.

All the examples will be written using the MySQL database.

Consider we have the following tables with the given data.

Table 1: t_employees
ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

Table 2: t2_employees

ID Name Department Salary Year_of_Experience

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4

6 Bhushan Wagh R&D 75000 2

7 Anand Singh Marketing 28000 1

Table 3: t_students

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History


4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

Table 4: t2_students

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Ishwari Dixit Delhi 86 Hindi

3 Anuja Rajput Jaipur 78 History

4 Pakhi Arora Surat 70 Sanskrit

5 Renuka Deshmukh Panipat 90 Biology

6 Jayshree Patel Pune 91 Maths

7 Prachi Jaiswal Gurugram 96 Hindi

1. UNION:
o UNION will be used to combine the result of two select statements.
o Duplicate rows will be eliminated from the results obtained after
performing the UNION operation.

Example 1:

Write a query to perform union between the table t_employees and the table
t2_employees.

1. Query:
mysql> SELECT *FROM t_employees UNION SELECT *FROM t2_employees
;
2. Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and
perform a UNION operation with the records fetched by the second
SELECT query from the t2_employees table.
3. You will get the following output:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

3 Gautam Jain Development 56000 4

5 Rahul Thakur Production 76000 4

7 Anand Singh Marketing 28000 1

2. UNION ALL
o This operator combines all the records from both the queries.
o Duplicate rows will be not be eliminated from the results obtained after
performing the UNION ALL operation.

Example 1:

Write a query to perform union all operation between the table t_employees
and the table t2_employees.
1. Query:
mysql> SELECT *FROM t_employees UNION ALL SELECT *FROM t2_emplo
yees;
2. Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and
perform UNION ALL operation with the records fetched by the second
SELECT query from the t2_employees table.

You will get the following output:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4

6 Bhushan Wagh R&D 75000 2

7 Anand Singh Marketing 28000 1

Since we have performed union all operation between both the tables, so all
the records from the first and second table are displayed, including the
duplicate records.
3. INTERSECT:
o It is used to combine two SELECT statements, but it only returns the
records which are common from both SELECT statements.

Example 1:

Write a query to perform intersect operation between the table t_employees


and the table t2_employees.

1. Query:
mysql> SELECT *FROM t_employees INTERSECT SELECT *FROM t2_empl
oyees;
2. Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and
perform INTERSECT operation with the records fetched by the second
SELECT query from the t2_employees table.
3. You will get the following output:

ID Name Hometown Percentage Favourite_Subject

2 Abhishek Pawar Production 45000 1

4 Shubham Mahale Accounts 57000 2

6 Bhushan Wagh R&D 75000 2

4. Since we have performed intersect operation between both the tables,


so only the common records from both the tables are displayed.

4. MINUS

o It displays the rows which are present in the first query but absent in
the second query with no duplicates.

Example 1:

Write a query to perform a minus operation between the table t_employees


and the table t2_employees.

Query:
1. mysql> SELECT *FROM t_employees MINUS SELECT *FROM t2_employees;

Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
MINUS operation with the records fetched by the second SELECT query from
the t2_employees table.

You will get the following output:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

3 Pranav Deshmukh HR 59900 3

5 Sunil Kulkarni Development 87000 3

7 Paras Jaiswal Marketing 32000 1

Since we have performed Minus operation between both the tables, so only
the unmatched records from both the tables are displayed.

You might also like