0% found this document useful (0 votes)
6 views

Khalid.

Uploaded by

imrn
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)
6 views

Khalid.

Uploaded by

imrn
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
You are on page 1/ 81

UNIT 2

Relational Model in DBMS

Relational model makes the query much easier than in hierarchical or network
database systems. In 1970, E.F Codd has been developed it. A relational
database is defined as a group of independent tables which are linked to each
other using some common fields of each related table. This model can be
represented as a table with columns and rows. Each row is known as a tuple.
Each table of the column has a name or attribute. It is well knows in database
technology because it is usually used to represent real-world objects and the
relationships between them. Some popular relational databases are used
nowadays like Oracle, Sybase, DB2, MySQL Server etc.

Relational Model Terminologies:

Following are the terminologies of Relational Model:

Relation Table

Tuple Row, Record

Attribute Column, Field

Domain It consists of set of legal values

Cardinality It consists of number of rows

Degree It contains number of columns

Let's explain each term one by one in detail with the help of example:

Example: STUDENT Relation

1
Stu_No S_Name PHONE_NO ADDRESS Gender

10112 Rama 9874567891 Islam ganj F

12839 Shyam 9026288936 Delhi M

33289 Laxman 8583287182 Gurugram M

27857 Mahesh 7086819134 Ghaziabad M

17282 Ganesh 9028939884 Delhi M

Relation: A relation is usually represented as a table, organized into rows and


columns. A relationship consists of multiple records. For example: student
relation which contains tuples and attributes.

Tuple: The rows of a relation that contain the values corresponding to the
attributes are called tuples. For example: in the Student relation there are 5
tuples.

The value of tuples contains (10112, Rama, 9874567891,islam ganj, F) etc.

Data Item: The smallest unit of data in the relation is the individual data item.
It is stored at the intersection of rows and columns are also known as cells. For
Example: 10112, "Rama" etc are data items in Student relation.

Domain: It contains a set of atomic values that an attribute can take. It could be
accomplish explicitly by listing all possible values or specifying conditions that
all values in that domain must be confirmed. For example: the domain of
gender attributes is a set of data values "M" for male and "F" for female. No

2
database software fully supports domains typically allowing the users to define
very simple data types such as numbers, dates, characters etc.

Attribute: The smallest unit of data in relational model is an attribute. It


contains the name of a column in a particular table. Each attribute Ai must
have a domain, dom(Ai). For example: Stu_No, S_Name, PHONE_NO,
ADDRESS, Gender are the attributes of a student relation. In relational
databases a column entry in any row is a single value that contains exactly one
item only.

Cardinality: The total number of rows at a time in a relation is called the


cardinality of that relation. For example: In a student relation, the total number
of tuples in this relation is3 so the cardinality of a relation is 3. The cardinality
of a relation changes with time as more and more tuples get added or deleted.

Degree: The degree of association is called the total number of attributes in a


relationship. The relation with one attribute is called unary relation, with two
attributes is known a binary relation and with three attributes is known as
ternary relation. For example: in the Student relation, the total number of
attributes is 5, so the degree of the relations is 5. The degree of a relation does
not change with time as tuples get added or deleted.

Relational instance: In the relational database system, the relational instance is


represented by a finite set of tuples. Relation instances do not have duplicate
tuples.

Relational schema: A relational schema contains the name of the relation and
name of all columns or attributes.

Relational key: In the relational key, each row has one or more attributes. It
can identify the row in the relation uniquely.

Properties of Relations

o Each attribute in a relation has only one data value corresponding to it


i.e. they do not contain two or more values.

3
o Name of the relation is distinct from all other relations.

o Each relation cell contains exactly one atomic (single) value

o Each attribute contains a distinct name

o Attribute domain has no significance

o tuple has no duplicate value

o Order of tuple can have a different sequence

o It also provides information about metadata.

Merits of Relational Model:

Following are the various merits of relational model:

o This provides an abstract view of the data. It abstracts the physical


structure from the logical structure of data.

o This model is very easy to design. Tables can use different attributes as
per requirements.

o The relational model supports data independence. In a relational


database the data is stored in tables so that we can modify the data
without changing the physical structure.

o Relational database helps the user to use a query language to query the
database.

o It offers more flexibility than other models.

o By moving sensitive attributes, we can also implement database security


control and authorization in a particular table into a separate relation
with its authorization controls.

4
o Relational database helps the user to use a query language to query the
database.

o A relational model consists of simple relationships. The characteristics of


a database that make it immune to certain maintenance problems have
been developed in the context of relational models.

o It is useful for representing most real world objects and the relationships
between them. It is very easy to implement a relationship through the
use of a composite key, so this model persistence method dominates the
market.

Demerits of Relational Model:

Most of the drawbacks of the relational database is not because of the


shortcoming but because of the way it is being implemented, we can avoid the
drawbacks of the relational model by using proper designing techniques and
proper database standards are enforced. Following are the various demerits of
relational model:

o The main disadvantage of relational models is that they do not support


binary data for example: images, documents, spreadsheets etc.

o The relational model can easily adapt to new hardware so incurs large
hardware overhead.

o Relational databases use a simple mapping of logical tables to physical


structures.

o This mostly limits performance and allows non-relational systems such as


object oriented management systems to perform better on specialised
applications such as CAD, CAM etc.

o Enforcing data integrity in relational models is difficult because no single


piece of hardware has control over the data.

o The relational model is suitable for small databases but not suitable for
complex databases because the user needs to know the complex
physical data storage details. So, while designing the databases they
don't come to light when they may cause problems. When a database

5
grows it will slow down the system and will result in performance
degradation and data corruption.

Operations on Relational Model:

List of the following basic operations that can be performed on a relational


model:

o Insertion Operation

o Deletion Operation

o Update Operation

o Retrieval Operation

Let's explain each operation one by one.

Insert operation: It is used to insert a new record in the table. Adding new
records to the table is much easier than other models. Data values will not be
found in a relation when the following condition occurs:

o If we try to insert a duplicate value for the field that is selected as a


primary key.

o If we insert a NULL value in the attribute that contains primary key.

o If we try to enter a data value in the foreign key attribute that does not
exist in corresponding primary key attribute.

o If an attribute is assigned a value that does not exist in the corresponding


domain.

DELETE operation: This operation is used to delete records from the table but
problems arise when the rows to be deleted have some attributes which are
foreign key attributes.

Update operation: It is used to modify or change the data value of a record in a


table. Updating an attribute that is neither a primary key nor a foreign key
requires only checking that the new value is of the correct data type and
domain. If we modify a data value of a primary key and foreign key attribute
then need to check:

6
o The modified value does not contain the value of the corresponding
foreign key value.

o The new values must not already exist in the table.

Retrieval operation: It is used to save a record from a relation. This operation is


very simple and homogeneous.

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

Types of Relational operation

1. Select Operation:

o The select operation selects tuples that satisfy a given predicate.

o It is denoted by sigma (σ).

1. Notation: σ p(r)

Where:

σ is used for selection prediction


r is used for relation

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

For example: LOAN Relation

BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

Input:

1. σ BRANCH_NAME="perryride" (LOAN)

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

2. Project Operation:

8
o This operation shows the list of those attributes that we wish to appear
in the result. Rest of the attributes are eliminated from the table.

o It is denoted by ∏.

1. Notation: ∏ A1, A2, An (r)

Where

A1, A2, A3 is used as an attribute name of relation r.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:

1. ∏ NAME, CITY (CUSTOMER)

Output:

NAME CITY

Jones Harrison

9
Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

3. Union Operation:

o Suppose there are two tuples R and S. The union operation contains all
the tuples that are either in R or S or both in R & S.

o It eliminates the duplicate tuples. It is denoted by ∪.

1. Notation: R ∪ S

A union operation must hold the following condition:

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

o Duplicate tuples are eliminated automatically.

Example:

DEPOSITOR RELATION

CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

10
Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

CUSTOMER_NAME LOAN_NO

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17

Input:

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

Output:

11
CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes

4. Set Intersection:

o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in both R & S.

o It is denoted by intersection ∩.

1. Notation: R ∩ S

Example: Using the above DEPOSITOR table and BORROW table

Input:

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

Output:

CUSTOMER_NAME

Smith

Jones

5. Set Difference:

o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in R but not in S.

o It is denoted by intersection minus (-).

1. Notation: R - S

Example: Using the above DEPOSITOR table and BORROW table

Input:

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

Output:

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

13
6. Cartesian product

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

o It is denoted by X.

1. Notation: E X D

Example:

EMPLOYEE

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B

DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal

Input:

1. EMPLOYEE X DEPARTMENT

Output:

14
EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

7. Rename Operation:

The rename operation is used to rename the output relation. It is denoted


by rho (ρ).

Example: We can use the rename operator to rename STUDENT relation to


STUDENT1.

1. ρ(STUDENT1, STUDENT)

Join Operations:

A Join operation combines related tuples from different relations, if and only if
a given join condition is satisfied. It is denoted by ⋈.

15
Example:

EMPLOYEE

EMP_CODE EMP_NAME

101 Stephan

102 Jack

103 Harry

SALARY

EMP_CODE SALARY

101 50000

102 30000

103 25000

1. Operation: (EMPLOYEE ⋈ SALARY)

Result:

EMP_CODE EMP_NAME SALARY

101 Stephan 50000

102 Jack 30000

103 Harry 25000

Types of Join operations:

16
1. Natural Join:

o A natural join is the set of tuples of all combinations in R and S that are
equal on their common attribute names.

o It is denoted by ⋈.

Example: Let's use the above EMPLOYEE table and SALARY table:

Input:

1. ∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)

Output:

EMP_NAME SALARY

17
Stephan 50000

Jack 30000

Harry 25000

2. Outer Join:

The outer join operation is an extension of the join operation. It is used to deal
with missing information.

Example:

EMPLOYEE

EMP_NAME STREET CITY

Ram Civil line Mumbai

Shyam Park street Kolkata

Ravi M.G. Street Delhi

Hari Nehru nagar Hyderabad

FACT_WORKERS

EMP_NAME BRANCH SALARY

Ram Infosys 10000

Shyam Wipro 20000

Kuber HCL 30000

18
Hari TCS 50000

Input:

1. (EMPLOYEE ⋈ FACT_WORKERS)

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru nagar Hyderabad TCS 50000

An outer join is basically of three types:

a. Left outer join

b. Right outer join

c. Full outer join

a. Left outer join:

o Left outer join contains the set of tuples of all combinations in R and S
that are equal on their common attribute names.

o In the left outer join, tuples in R have no matching tuples in S.

o It is denoted by ⟕.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟕ FACT_WORKERS

19
EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

b. Right outer join:

o Right outer join contains the set of tuples of all combinations in R and S
that are equal on their common attribute names.

o In right outer join, tuples in S have no matching tuples in R.

o It is denoted by ⟖.

Example: Using the above EMPLOYEE table and FACT_WORKERS Relation

Input:

1. EMPLOYEE ⟖ FACT_WORKERS

Output:

EMP_NAME BRANCH SALARY STREET CITY

Ram Infosys 10000 Civil line Mumbai

20
Shyam Wipro 20000 Park street Kolkata

Hari TCS 50000 Nehru street Hyderabad

Kuber HCL 30000 NULL NULL

c. Full outer join:

o Full outer join is like a left or right join except that it contains all rows
from both tables.

o In full outer join, tuples in R that have no matching tuples in S and tuples
in S that have no matching tuples in R in their common attribute name.

o It is denoted by ⟗.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟗ FACT_WORKERS

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

Kuber NULL NULL HCL 30000

3. Equi join:

21
It is also known as an inner join. It is the most common join. It is based on
matched data as per the equality condition. The equi join uses the comparison
operator(=).

Example:

CUSTOMER RELATION

CLASS_ID NAME

1 John

2 Harry

3 Jackson

PRODUCT

PRODUCT_ID CITY

1 Delhi

2 Mumbai

3 Noida

Input:

1. CUSTOMER ⋈ PRODUCT

Output:

CLASS_ID NAME PRODUCT_ID CITY

1 John 1 Delhi

22
2 Harry 2 Mumbai

3 Harry 3 Noida

Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality
of information.

o Integrity constraints ensure that the data insertion, updating, and other
processes have to be performed in such a way that data integrity is not
affected.

o Thus, integrity constraint is used to guard against accidental damage to


the database.

Types of Integrity Constraint

1. Domain constraints

23
o Domain constraints can be defined as the definition of a valid set of
values for an attribute.

o The data type of domain includes string, character, integer, time, date,
currency, etc. The value of the attribute must be available in the
corresponding domain.

Example:

2. Entity integrity constraints

o The entity integrity constraint states that primary key value can't be null.

o This is because the primary key value is used to identify individual rows
in relation and if the primary key has a null value, then we can't identify
those rows.

o A table can contain a null value other than the primary key field.

Example:

24
3. Referential Integrity Constraints

o A referential integrity constraint is specified between two tables.

o In the Referential integrity constraints, if a foreign key in Table 1 refers to


the Primary Key of Table 2, then every value of the Foreign Key in Table 1
must be null or be available in Table 2.

Example:

25
4. Key constraints

o Keys are the entity set that is used to identify an entity within its entity
set uniquely.

o An entity set can have multiple keys, but out of which one key will be the
primary key. A primary key can contain a unique and null value in the
relational table.

Example:

Relational Calculus
There is an alternate way of formulating queries known as Relational Calculus.
Relational calculus is a non-procedural query language. In the non-procedural
query language, the user is concerned with the details of how to obtain the
end results. The relational calculus tells what to do but never explains how to
do. Most commercial relational languages are based on aspects of relational
calculus including SQL-QBE and QUEL.

Why it is called Relational Calculus?

It is based on Predicate calculus, a name derived from branch of symbolic


language. A predicate is a truth-valued function with arguments. On
substituting values for the arguments, the function result in an expression
called a proposition. It can be either true or false. It is a tailored version of a
subset of the Predicate Calculus to communicate with the relational database.

Many of the calculus expressions involves the use of Quantifiers. There are
two types of quantifiers:

26
o Universal Quantifiers: The universal quantifier denoted by ∀ is read as
for all which means that in a given set of tuples exactly all tuples satisfy a
given condition.

o Existential Quantifiers: The existential quantifier denoted by ∃ is read as


for all which means that in a given set of tuples there is at least one
occurrences whose value satisfy a given condition.

Before using the concept of quantifiers in formulas, we need to know the


concept of Free and Bound Variables.

A tuple variable t is bound if it is quantified which means that if it appears in


any occurrences a variable that is not bound is said to be free.

Free and bound variables may be compared with global and local variable of
programming languages.

Types of Relational calculus:

1. Tuple Relational Calculus (TRC)

It is a non-procedural query language which is based on finding a number of


tuple variables also known as range variable for which predicate holds true. It
describes the desired information without giving a specific procedure for
obtaining that information. The tuple relational calculus is specified to select
the tuples in a relation. In TRC, filtering variable uses the tuples of a relation.
The result of the relation can have one or more tuples.

27
Notation:

A Query in the tuple relational calculus is expressed as following notation

1. {T | P (T)} or {T | Condition (T)}

Where

T is the resulting tuples

P(T) is the condition used to fetch T.

For example:

1. { T.name | Author(T) AND T.article = 'database' }

Output: This query selects the tuples from the AUTHOR relation. It returns a
tuple with 'name' from Author who has written an article on 'database'.

TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential
(∃) and Universal Quantifiers (∀).

For example:

1. { R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}

Output: This query will yield the same result as the previous one.

2. Domain Relational Calculus (DRC)

The second form of relation is known as Domain relational calculus. In domain


relational calculus, filtering variable uses the domain of attributes. Domain
relational calculus uses the same operators as tuple calculus. It uses logical
connectives ∧ (and), ∨ (or) and ┓ (not). It uses Existential (∃) and Universal
Quantifiers (∀) to bind the variable. The QBE or Query by example is a query
language related to domain relational calculus.

Notation:

1. { a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}

Where

28
a1, a2 are attributes
P stands for formula built by inner attributes

For example:

1. {< article, page, subject > | ∈ javatpoint ∧ subject = 'database'}

Output: This query will yield the article, page, and subject from the relational
javatpoint, where the subject is a database.

What is SQL?
SQL is a short-form of the structured query language, and it is pronounced as S-
Q-L or sometimes as See-Quell.

This database language is mainly designed for maintaining the data in relational
database management systems. It is a special tool used by data professionals
for handling structured data (data which is stored in the form of tables). It is
also designed for stream processing in RDSMS.

You can easily create and manipulate the database, access and modify the
table rows and columns, etc. This query language became the standard of ANSI
in the year of 1986 and ISO in the year of 1987.

If you want to get a job in the field of data science, then it is the most
important query language to learn. Big enterprises like Facebook, Instagram,
and LinkedIn, use SQL for storing the data in the back-end.

Why SQL?

Nowadays, SQL is widely used in data science and analytics. Following are the
reasons which explain why it is widely used:

o The basic use of SQL for data professionals and SQL users is to insert,
update, and delete the data from the relational database.

o SQL allows the data professionals and users to retrieve the data from the
relational database management systems.

o It also helps them to describe the structured data.

29
o It allows SQL users to create, drop, and manipulate the database and its
tables.

o It also helps in creating the view, stored procedure, and functions in the
relational database.

o It allows you to define the data and modify that stored data in the
relational database.

o It also allows SQL users to set the permissions or constraints on table


columns, views, and stored procedures.

History of SQL

"A Relational Model of Data for Large Shared Data Banks" was a paper which
was published by the great computer scientist "E.F. Codd" in 1970.

The IBM researchers Raymond Boyce and Donald Chamberlin originally


developed the SEQUEL (Structured English Query Language) after learning from
the paper given by E.F. Codd. They both developed the SQL at the San Jose
Research laboratory of IBM Corporation in 1970.

At the end of the 1970s, relational software Inc. developed their own first SQL
using the concepts of E.F. Codd, Raymond Boyce, and Donald Chamberlin. This
SQL was totally based on RDBMS. Relational Software Inc., which is now known
as Oracle Corporation, introduced the Oracle V2 in June 1979, which is the first
implementation of SQL language. This Oracle V2 version operates on VAX
computers.

Process of SQL

When we are executing the command of SQL on any Relational database


management system, then the system automatically finds the best routine to
carry out our request, and the SQL engine determines how to interpret that
particular command.

Structured Query Language contains the following four components in its


process:

o Query Dispatcher

30
o Optimization Engines

o Classic Query Engine

o SQL Query Engine, etc.

A classic query engine allows data professionals and users to maintain non-SQL
queries. The architecture of SQL is shown in the following diagram:

Some SQL Commands

The SQL commands help in creating and managing the database. The most
common SQL commands which are highly used are mentioned below:

1. CREATE command

2. UPDATE command

3. DELETE command

4. SELECT command

5. DROP command

6. INSERT command

31
CREATE Command

This command helps in creating the new database, new table, table view, and
other objects of the database.

UPDATE Command

This command helps in updating or changing the stored data in the database.

DELETE Command

This command helps in removing or erasing the saved records from the
database tables. It erases single or multiple tuples from the tables of the
database.

SELECT Command

This command helps in accessing the single or multiple rows from one or
multiple tables of the database. We can also use this command with the
WHERE clause.

DROP Command

This command helps in deleting the entire table, table view, and other objects
from the database.

INSERT Command

This command helps in inserting the data or records into the database tables.
We can easily insert the records in single as well as multiple rows of the table.

SQL vs No-SQL

32
The following table describes the differences between the SQL and NoSQL,
which are necessary to understand:

SQL No-SQL

1. While No-SQL is a non-relational or


1. SQL is a relational database
distributed database management
management system.
system.

2. The query language used in this 2. The query language used in the No-SQL
database system is a structured query database systems is a non-declarative
language. query language.

3. The schema of SQL databases is 3. The schema of No-SQL databases is a


predefined, fixed, and static. dynamic schema for unstructured data.

4. These databases are horizontally


4. These databases are vertically scalable.
scalable.

5. The database type of SQL is in the form 5. The database type of No-SQL is in the
of tables, i.e., in the form of rows and form of documents, key-value, and
columns. graphs.

6. It follows the ACID model. 6. It follows the BASE model.

7. Complex queries are easily managed in 7. NoSQL databases cannot handle


the SQL database. complex queries.

8. This database is not the best choice for 8. While No-SQL database is a perfect
storing hierarchical data. option for storing hierarchical data.

9. All SQL databases require object- 9. Many No-SQL databases do not require
relational mapping. object-relational mapping.

33
10. Gauges, CircleCI, Hootsuite, etc., are 10. Airbnb, Uber, and Kickstarter are the
the top enterprises that are using this top enterprises that are using this query
query language. language.

11. SQLite, Ms-SQL, Oracle, PostgreSQL, 11. Redis, MongoDB, Hbase, BigTable,
and MySQL are examples of SQL database CouchDB, and Cassandra are examples of
systems. NoSQL database systems.

Advantages of SQL

SQL provides various advantages which make it more popular in the field of
data science. It is a perfect query language which allows data professionals and
users to communicate with the database. Following are the best advantages or
benefits of Structured Query Language:

1. No programming needed

SQL does not require a large number of coding lines for managing the database
systems. We can easily access and maintain the database by using simple SQL
syntactical rules. These simple rules make the SQL user-friendly.

2. High-Speed Query Processing

A large amount of data is accessed quickly and efficiently from the database by
using SQL queries. Insertion, deletion, and updation operations on data are
also performed in less time.

3. Standardized Language

SQL follows the long-established standards of ISO and ANSI, which offer a
uniform platform across the globe to all its users.

4. Portability

The structured query language can be easily used in desktop computers,


laptops, tablets, and even smartphones. It can also be used with other
applications according to the user's requirements.

5. Interactive language

34
We can easily learn and understand the SQL language. We can also use this
language for communicating with the database because it is a simple query
language. This language is also used for receiving the answers to complex
queries in a few seconds.

6. More than one Data View

The SQL language also helps in making the multiple views of the database
structure for the different database users.

Disadvantages of SQL

With the advantages of SQL, it also has some disadvantages, which are as
follows:

1. Cost

The operation cost of some SQL versions is high. That's why some programmers
cannot use the Structured Query Language.

2. Interface is Complex

Another big disadvantage is that the interface of Structured query language is


difficult, which makes it difficult for SQL users to use and manage it.

3. Partial Database control

The business rules are hidden. So, the data professionals and users who are
using this query language cannot have full database control.

SQL Data Types

Data types are used to represent the nature of the data that can be stored in
the database table. For example, in a particular column of a table, if we want to
store a string type of data then we will have to declare a string data type of this
column.

Data types mainly classified into three categories for every database.

o String Data types

o Numeric Data types

35
o Date and time Data types

Data Types in MySQL, SQL Server and Oracle Databases

MySQL Data Types

A list of data types used in MySQL database. This is based on MySQL 8.0.

MySQL String Data Types

It is used to specify a fixed length string


that can contain numbers, letters, and
CHAR(Size)
special characters. Its size can be 0 to 255
characters. Default is 1.

It is used to specify a variable length string


that can contain numbers, letters, and
VARCHAR(Size)
special characters. Its size can be from 0
to 65535 characters.

It is equal to CHAR() but stores binary byte


BINARY(Size) strings. Its size parameter specifies the
column length in the bytes. Default is 1.

It is equal to VARCHAR() but stores binary


VARBINARY(Size) byte strings. Its size parameter specifies
the maximum column length in bytes.

It holds a string that can contain a


TEXT(Size)
maximum length of 255 characters.

It holds a string with a maximum length of


TINYTEXT
255 characters.

36
It holds a string with a maximum length of
MEDIUMTEXT
16,777,215.

It holds a string with a maximum length of


LONGTEXT
4,294,967,295 characters.

It is used when a string object having only


one value, chosen from a list of possible
ENUM(val1, val2, val3,...) values. It contains 65535 values in an
ENUM list. If you insert a value that is not
in the list, a blank value will be inserted.

It is used to specify a string that can have


0 or more values, chosen from a list of
SET( val1,val2,val3,....)
possible values. You can list up to 64
values at one time in a SET list.

It is used for BLOBs (Binary Large Objects).


BLOB(size)
It can hold up to 65,535 bytes.

MySQL Numeric Data Types

It is used for a bit-value type. The


number of bits per value is specified in
BIT(Size)
size. Its size can be 1 to 64. The default
value is 1.

It is used for the integer value. Its signed


range varies from -2147483648 to
2147483647 and unsigned range varies
INT(size)
from 0 to 4294967295. The size
parameter specifies the max display
width that is 255.

37
INTEGER(size) It is equal to INT(size).

It is used to specify a floating point


number. Its size parameter specifies the
FLOAT(size, d) total number of digits. The number of
digits after the decimal point is specified
by d parameter.

It is used to specify a floating point


number. MySQL used p parameter to
determine whether to use FLOAT or
FLOAT(p)
DOUBLE. If p is between 0 to24, the data
type becomes FLOAT (). If p is from 25 to
53, the data type becomes DOUBLE().

It is a normal size floating point number.


Its size parameter specifies the total
DOUBLE(size, d) number of digits. The number of digits
after the decimal is specified by d
parameter.

It is used to specify a fixed point number.


Its size parameter specifies the total
number of digits. The number of digits
after the decimal parameter is specified
DECIMAL(size, d)
by d parameter. The maximum value for
the size is 65, and the default value is 10.
The maximum value for d is 30, and the
default value is 0.

DEC(size, d) It is equal to DECIMAL(size, d).

38
It is used to specify Boolean values true
BOOL and false. Zero is considered as false, and
nonzero values are considered as true.

MySQL Date and Time Data Types

It is used to specify date format YYYY-


DATE MM-DD. Its supported range is from
'1000-01-01' to '9999-12-31'.

It is used to specify date and time


combination. Its format is YYYY-MM-DD
DATETIME(fsp) hh:mm:ss. Its supported range is from
'1000-01-01 00:00:00' to 9999-12-31
23:59:59'.

It is used to specify the timestamp. Its


value is stored as the number of seconds
since the Unix epoch('1970-01-01
TIMESTAMP(fsp) 00:00:00' UTC). Its format is YYYY-MM-DD
hh:mm:ss. Its supported range is from
'1970-01-01 00:00:01' UTC to '2038-01-09
03:14:07' UTC.

It is used to specify the time format. Its


TIME(fsp) format is hh:mm:ss. Its supported range
is from '-838:59:59' to '838:59:59'

It is used to specify a year in four-digit


YEAR format. Values allowed in four digit
format from 1901 to 2155, and 0000.

SQL Server Data Types

SQL Server String Data Type

39
It is a fixed width character string dat
char(n)
can be up to 8000 characters.

It is a variable width character string


varchar(n)
size can be up to 8000 characters.

It is a variable width character string


varchar(max)
size can be up to 1,073,741,824 chara

It is a variable width character string


text
size can be up to 2GB of text data.

It is a fixed width Unicode string data


nchar
can be up to 4000 characters.

It is a variable width Unicode string d


nvarchar
can be up to 4000 characters.

It is a variable width Unicode string d


ntext
can be up to 2GB of text data.

It is a fixed width Binary string data ty


binary(n)
be up to 8000 bytes.

It is a variable width Binary string dat


varbinary
can be up to 8000 bytes.

It is also a variable width Binary string


image
size can be up to 2GB.

SQL Server Numeric Data Types

bit It is an integer that can be 0, 1 or null.

40
tinyint It allows whole numbers from 0 to 255.

It allows whole numbers between -


Smallint
32,768 and 32,767.

It allows whole numbers between -


Int
2,147,483,648 and 2,147,483,647.

It allows whole numbers between -


bigint 9,223,372,036,854,775,808 and
9,223,372,036,854,775,807.

It is used to specify floating precision


number data from -1.79E+308 to
float(n) 1.79E+308. The n parameter indicates
whether the field should hold the 4 or 8
bytes. Default value of n is 53.

It is a floating precision number data


real
from -3.40E+38 to 3.40E+38.

It is used to specify monetary data from -


money 922,337,233,685,477.5808 to
922,337,203,685,477.5807.

SQL Server Date and Time Data Type

It is used to specify date and time


combination. It supports range from
datetime
January 1, 1753, to December 31, 9999
with an accuracy of 3.33 milliseconds.

41
It is used to specify date and time
combination. It supports range from
datetime2
January 1, 0001 to December 31, 9999
with an accuracy of 100 nanoseconds

It is used to store date only. It supports


date range from January 1, 0001 to December
31, 9999

It stores time only to an accuracy of 100


time
nanoseconds

It stores a unique number when a new


row gets created or modified. The time
stamp value is based upon an internal
timestamp
clock and does not correspond to real
time. Each table may contain only one-
time stamp variable.

SQL Server Other Data Types

It is used for various data types except for


Sql_variant text, timestamp, and ntext. It stores up to
8000 bytes of data.

It stores XML formatted data. Maximum


XML
2GB.

It stores a reference to a cursor used for


cursor
database operations.

table It stores result set for later processing.

42
uniqueidentifier It stores GUID (Globally unique identifier).

Oracle Data Types

Oracle String data types

It is used to store character data within


CHAR(size) the predefined length. It can be stored
up to 2000 bytes.

It is used to store national character data


NCHAR(size) within the predefined length. It can be
stored up to 2000 bytes.

It is used to store variable string data


VARCHAR2(size) within the predefined length. It can be
stored up to 4000 byte.

It is the same as VARCHAR2(size). You


VARCHAR(SIZE) can also use VARCHAR(size), but it is
suggested to use VARCHAR2(size)

It is used to store Unicode string data


within the predefined length. We have to
NVARCHAR2(size) must specify the size of NVARCHAR2
data type. It can be stored up to 4000
bytes.

Oracle Numeric Data Types

It contains precision p and scale s. The


NUMBER(p, s) precision p can range from 1 to 38, and
the scale s can range from -84 to 127.

43
It is a subtype of the NUMBER data type.
FLOAT(p)
The precision p can range from 1 to 126.

It is used for binary precision( 32-bit). It


BINARY_FLOAT
requires 5 bytes, including length byte.

It is used for double binary precision (64-


BINARY_DOUBLE bit). It requires 9 bytes, including length
byte.

Oracle Date and Time Data Types

It is used to store a valid date-time


format with a fixed length. Its range
DATE
varies from January 1, 4712 BC to
December 31, 9999 AD.

It is used to store the valid date in YYYY-


TIMESTAMP
MM-DD with time hh:mm:ss format.

Oracle Large Object Data Types (LOB Types)

It is used to specify unstructured binary


BLOB data. Its range goes up to 232-1 bytes or 4
GB.

It is used to store binary data in an


BFILE external file. Its range goes up to 232-1
bytes or 4 GB.

It is used for single-byte character data.


CLOB
Its range goes up to 232-1 bytes or 4 GB.

44
It is used to specify single byte or fixed
length multibyte national character set
NCLOB
(NCHAR) data. Its range is up to 232-1
bytes or 4 GB.

It is used to specify variable length raw


binary data. Its range is up to 2000 bytes
RAW(size)
per row. Its maximum size must be
specified.

It is used to specify variable length raw


LONG RAW binary data. Its range up to 231-1 bytes or
2 GB, per row.

SQL Operators

Every database administrator and user uses SQL queries for manipulating and
accessing the data of database tables and views.

The manipulation and retrieving of the data are performed with the help of
reserved words and characters, which are used to perform arithmetic
operations, logical operations, comparison operations, compound operations,
etc.

What is SQL Operator?

The SQL reserved words and characters are called operators, which are used
with a WHERE clause in a SQL query. In SQL, an operator can either be a unary
or binary operator. The unary operator uses only one operand for performing
the unary operation, whereas the binary operator uses two operands for
performing the binary operation.

Syntax of Unary SQL Operator

1. Operator SQL_Operand

Syntax of Unary SQL Operator


45
1. Operand1 SQL_Operator Operand2

Note: SQL operators are used for filtering the table's data by a specific
condition in the SQL statement.

What is the Precedence of SQL Operator?

The precedence of SQL operators is the sequence in which the SQL evaluates
the different operators in the same expression. Structured Query Language
evaluates those operators first, which have high precedence.

In the following table, the operators at the top have high precedence, and the
operators that appear at the bottom have low precedence.

SQL Operator Symbols Operators

** Exponentiation operator

+, - Identity operator, Negation operator

*, / Multiplication operator, Division operator

Addition (plus) operator, subtraction


+, -, || (minus) operator, String Concatenation
operator

=, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN,


Comparison Operators
IN

NOT Logical negation operator

&& or AND Conjunction operator

OR Inclusion operator

For Example,

46
1. UPDATE employee

2. SET salary = 20 - 3 * 5 WHERE Emp_Id = 5;

In the above SQL example, salary is assigned 5, not 85, because the *
(Multiplication)

Operator has higher precedence than the - (subtraction) operator, so it first


gets multiplied with 3*5 and then subtracts from 20.

Types of Operator

SQL operators are categorized in the following categories:

1. SQL Arithmetic Operators

2. SQL Comparison Operators

3. SQL Logical Operators

4. SQL Set Operators

5. SQL Bit-wise Operators

6. SQL Unary Operators

Let's discuss each operator with their types.

SQL Arithmetic Operators

The Arithmetic Operators perform the mathematical operation on the


numerical data of the SQL tables. These operators perform addition,
subtraction, multiplication, and division operations on the numerical operands.

Following are the various arithmetic operators performed on the SQL data:

1. SQL Addition Operator (+)

2. SQL Subtraction Operator (-)

3. SQL Multiplication Operator (+)

4. SQL Division Operator (-)

5. SQL Modulus Operator (+)

47
SQL Addition Operator (+)

The Addition Operator in SQL performs the addition on the numerical data of
the database table. In SQL, we can easily add the numerical values of two
columns of the same table by specifying both the column names as the first
and second operand. We can also add the numbers to the existing numbers of
the specific column.

Syntax of SQL Addition Operator:

1. SELECT operand1 + operand2;

Let's understand the below example which explains how to execute Addition
Operator in SQL query:

This example consists of an Employee_details table, which has four


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_Monthlybonus.

Emp Id Emp Name Emp Salary Emp


Monthlybonus

101 Tushar 25000 4000

102 Anuj 30000 200

o Suppose, we want to add 20,000 to the salary of each employee


specified in the table. Then, we have to write the following query in the
SQL:

1. SELECT Emp_Salary + 20000 as Emp_New_Salary FROM Employee_detail


s;

In this query, we have performed the SQL addition operation on the single
column of the given table.

o Suppose, we want to add the Salary and monthly bonus columns of the
above table, then we have to write the following query in SQL:

48
1. SELECT Emp_Salary + Emp_Monthlybonus as Emp_Total_Salary FROM E
mployee_details;

In this query, we have added two columns with each other of the above table.

SQL Subtraction Operator (-)

The Subtraction Operator in SQL performs the subtraction on the numerical


data of the database table. In SQL, we can easily subtract the numerical values
of two columns of the same table by specifying both the column names as the
first and second operand. We can also subtract the number from the existing
number of the specific table column.

Syntax of SQL Subtraction Operator:

1. SELECT operand1 - operand2;

Let's understand the below example which explains how to execute


Subtraction Operator in SQL query:

This example consists of an Employee_details table, which has four


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_Monthlybonus.

Emp Id Emp Name Emp Salary Penalty

201 Abhay 25000 200

202 Sumit 30000 500

o Suppose we want to subtract 5,000 from the salary of each employee


given in the Employee_details table. Then, we have to write the
following query in the SQL:

1. SELECT Emp_Salary -
5000 as Emp_New_Salary FROM Employee_details;

In this query, we have performed the SQL subtraction operation on the single
column of the given table.

49
o If we want to subtract the penalty from the salary of each employee,
then we have to write the following query in SQL:

1. SELECT Emp_Salary -
Penalty as Emp_Total_Salary FROM Employee_details;

SQL Multiplication Operator (*)

The Multiplication Operator in SQL performs the Multiplication on the


numerical data of the database table. In SQL, we can easily multiply the
numerical values of two columns of the same table by specifying both the
column names as the first and second operand.

Syntax of SQL Multiplication Operator:

1. SELECT operand1 * operand2;

Let's understand the below example which explains how to execute


Multiplication Operator in SQL query:

This example consists of an Employee_details table, which has four


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_Monthlybonus.

Emp Id Emp Name Emp Salary Penalty

201 Abhay 25000 200

202 Sumit 30000 500

o Suppose, we want to double the salary of each employee given in


the Employee_details table. Then, we have to write the following query
in the SQL:

1. SELECT Emp_Salary * 2 as Emp_New_Salary FROM Employee_details;

In this query, we have performed the SQL multiplication operation on the single
column of the given table.

50
o If we want to multiply the Emp_Id column to Emp_Salary column of that
employee whose Emp_Id is 202, then we have to write the following
query in SQL:

1. SELECT Emp_Id * Emp_Salary as Emp_Id * Emp_Salary FROM Employee_


details WHERE Emp_Id = 202;

In this query, we have multiplied the values of two columns by using the
WHERE clause.

SQL Division Operator (/)

The Division Operator in SQL divides the operand on the left side by the
operand on the right side.

Syntax of SQL Division Operator:

1. SELECT operand1 / operand2;

In SQL, we can also divide the numerical values of one column by another
column of the same table by specifying both column names as the first and
second operand.

We can also perform the division operation on the stored numbers in the
column of the SQL table.

Let's understand the below example which explains how to execute Division
Operator in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, and Emp_Salary.

Emp Id Emp Name Emp Salary

201 Abhay 25000

202 Sumit 30000

51
o Suppose, we want to half the salary of each employee given in the
Employee_details table. For this operation, we have to write the
following query in the SQL:

1. SELECT Emp_Salary / 2 as Emp_New_Salary FROM Employee_details;

In this query, we have performed the SQL division operation on the single
column of the given table.

SQL Modulus Operator (%)

The Modulus Operator in SQL provides the remainder when the operand on
the left side is divided by the operand on the right side.

Syntax of SQL Modulus Operator:

1. SELECT operand1 % operand2;

Let's understand the below example which explains how to execute Modulus
Operator in SQL query:

This example consists of a Division table, which has three columns Number,
First_operand, and Second_operand.

Number First operand Second operand

1 56 4

2 32 8

3 89 9

4 18 10

5 10 5

52
o If we want to get the remainder by dividing the numbers of
First_operand column by the numbers of Second_operand column, then
we have to write the following query in SQL:

1. SELECT First_operand % Second_operand as Remainder FROM Employee


_details;

SQL Comparison Operators

The Comparison Operators in SQL compare two different data of SQL table and
check whether they are the same, greater, and lesser. The SQL comparison
operators are used with the WHERE clause in the SQL queries

Following are the various comparison operators which are performed on the
data stored in the SQL database tables:

1. SQL Equal Operator (=)

2. SQL Not Equal Operator (!=)

3. SQL Greater Than Operator (>)

4. SQL Greater Than Equals to Operator (>=)

5. SQL Less Than Operator (<)\

6. SQL Less Than Equals to Operator (<=)

SQL Equal Operator (=)

This operator is highly used in SQL queries. The Equal Operator in SQL shows
only data that matches the specified value in the query.

This operator returns TRUE records from the database table if the value of both
operands specified in the query is matched.

Let's understand the below example which explains how to execute Equal
Operator in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, and Emp_Salary.

53
Emp Id Emp Name Emp Salary

201 Abhay 30000

202 Ankit 40000

203 Bheem 30000

204 Ram 29000

205 Sumit 30000

o Suppose, we want to access all the records of those employees from


the Employee_details table whose salary is 30000. Then, we have to
write the following query in the SQL database:

1. SELECT * FROM Employee_details WHERE Emp_Salary = 30000;

In this example, we used the SQL equal operator with WHERE clause for getting
the records of those employees whose salary is 30000.

SQL Equal Not Operator (!=)

The Equal Not Operator in SQL shows only those data that do not match the
query's specified value.

This operator returns those records or rows from the database views and
tables if the value of both operands specified in the query is not matched with
each other.

Let's understand the below example which explains how to execute Equal
Not Operator in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, and Emp_Salary.

Emp Id Emp Name Emp Salary

54
201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

205 Sumit 29000

o Suppose, we want to access all the records of those employees from


the Employee_details table whose salary is not 45000. Then, we have to
write the following query in the SQL database:

1. SELECT * FROM Employee_details WHERE Emp_Salary != 45000;

In this example, we used the SQL equal not operator with WHERE clause for
getting the records of those employees whose salary is not 45000.

SQL Greater Than Operator (>)

The Greater Than Operator in SQL shows only those data which are greater
than the value of the right-hand operand.

Let's understand the below example which explains how to execute Greater
ThanOperator (>) in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, and Emp_Salary.

Emp Id Emp Name Emp Salary

201 Abhay 45000

202 Ankit 45000

55
203 Bheem 30000

204 Ram 29000

205 Sumit 29000

o Suppose, we want to access all the records of those employees from


the Employee_details table whose employee id is greater than 202.
Then, we have to write the following query in the SQL database:

1. SELECT * FROM Employee_details WHERE Emp_Id > 202;

Here, SQL greater than operator displays the records of those employees from
the above table whose Employee Id is greater than 202.

SQL Greater Than Equals to Operator (>=)

The Greater Than Equals to Operator in SQL shows those data from the table
which are greater than and equal to the value of the right-hand operand.

Let's understand the below example which explains how to execute greater
than equals to the operator (>=) in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, and Emp_Salary.

Emp Id Emp Name Emp Salary

201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

56
205 Sumit 29000

o Suppose, we want to access all the records of those employees from


the Employee_details table whose employee id is greater than and
equals to 202. For this, we have to write the following query in the SQL
database:

1. SELECT * FROM Employee_details WHERE Emp_Id >= 202;

Here,'SQL greater than equals to operator' with WHERE clause displays the
rows of those employees from the table whose Employee Id is greater than and
equals to 202.

SQL Less Than Operator (<)

The Less Than Operator in SQL shows only those data from the database tables
which are less than the value of the right-side operand.

This comparison operator checks that the left side operand is lesser than the
right side operand. If the condition becomes true, then this operator in SQL
displays the data which is less than the value of the right-side operand.

Let's understand the below example which explains how to execute less than
operator (<) in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, and Emp_Salary.

Emp Id Emp Name Emp Salary

201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

57
205 Sumit 29000

o Suppose, we want to access all the records of those employees from


the Employee_details table whose employee id is less than 204. For this,
we have to write the following query in the SQL database:

1. SELECT * FROM Employee_details WHERE Emp_Id < 204;

Here,SQL less than operator with WHERE clause displays the records of those
employees from the above table whose Employee Id is less than 204.

SQL Less Than Equals to Operator (<=)

The Less Than Equals to Operator in SQL shows those data from the table
which are lesser and equal to the value of the right-side operand.

This comparison operator checks that the left side operand is lesser and equal
to the right side operand.

Let's understand the below example which explains how to execute less than
equals to the operator (<=) in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, and Emp_Salary.

Emp Id Emp Name Emp Salary

201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

205 Sumit 29000

58
o Suppose, we want to access all the records of those employees from
the Employee_details table whose employee id is less and
equals 203. For this, we have to write the following query in the SQL
database:

1. SELECT * FROM Employee_details WHERE Emp_Id <= 203;

Here, SQL less than equals to the operator with WHERE clause displays the
rows of those employees from the table whose Employee Id is less than and
equals 202.

SQL Logical Operators

The Logical Operators in SQL perform the Boolean operations, which give two
results True and False. These operators provide True value if both operands
match the logical condition.

Following are the various logical operators which are performed on the data
stored in the SQL database tables:

1. SQL ALL operator

2. SQL AND operator

3. SQL OR operator

4. SQL BETWEEN operator

5. SQL IN operator

6. SQL NOT operator

7. SQL ANY operator

8. SQL LIKE operator

SQL ALL Operator

The ALL operator in SQL compares the specified value to all the values of a
column from the sub-query in the SQL database.

This operator is always used with the following statement:

59
1. SELECT,

2. HAVING, and

3. WHERE.

Syntax of ALL operator:

1. SELECT column_Name1, ...., column_NameN FROM table_Name WHERE


column Comparison_operator ALL (SELECT column FROM tablename2)

Let's understand the below example which explains how to execute ALL
logical operators in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Gurgaon

202 Ankit 45000 Delhi

203 Bheem 30000 Jaipur

204 Ram 29000 Mumbai

205 Sumit 40000 Kolkata

o If we want to access the employee id and employee names of those


employees from the table whose salaries are greater than the salary of
employees who lives in Jaipur city, then we have to type the following
query in SQL.

1. SELECT Emp_Id, Emp_Name FROM Employee_details WHERE Emp_Salar


y > ALL ( SELECT Emp_Salary FROM Employee_details WHERE Emp_City
= Jaipur)

60
Here, we used the SQL ALL operator with greater than the operator.

SQL AND Operator

The AND operator in SQL would show the record from the database table if all
the conditions separated by the AND operator evaluated to True. It is also
known as the conjunctive operator and is used with the WHERE clause.

Syntax of AND operator:

1. SELECT column1, ...., columnN FROM table_Name WHERE condition1 AN


D condition2 AND condition3 AND ....... AND conditionN;

Let's understand the below example which explains how to execute AND
logical operator in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi

202 Ankit 45000 Chandigarh

203 Bheem 30000 Delhi

204 Ram 25000 Delhi

205 Sumit 40000 Kolkata

o Suppose, we want to access all the records of those employees from


the Employee_details table whose salary is 25000 and the city is Delhi.
For this, we have to write the following query in SQL:

o SELECT * FROM Employee_details WHERE Emp_Salary = 25000 OR


Emp_City = 'Delhi';

61
Here,SQL AND operator with WHERE clause shows the record of employees
whose salary is 25000 and the city is Delhi.

SQL OR Operator

The OR operator in SQL shows the record from the table if any of the
conditions separated by the OR operator evaluates to True. It is also known as
the conjunctive operator and is used with the WHERE clause.

Syntax of OR operator:

1. SELECT column1, ...., columnN FROM table_Name WHERE condition1 OR


condition2 OR condition3 OR ....... OR conditionN;

Let's understand the below example which explains how to execute OR


logical operator in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi

202 Ankit 45000 Chandigarh

203 Bheem 30000 Delhi

204 Ram 25000 Delhi

205 Sumit 40000 Kolkata

o If we want to access all the records of those employees from


the Employee_details table whose salary is 25000 or the city is Delhi. For
this, we have to write the following query in SQL:

1. SELECT * FROM Employee_details WHERE Emp_Salary = 25000 OR Emp_


City = 'Delhi';

62
Here, SQL OR operator with WHERE clause shows the record of employees
whose salary is 25000 or the city is Delhi.

SQL BETWEEN Operator

The BETWEEN operator in SQL shows the record within the range mentioned in
the SQL query. This operator operates on the numbers, characters, and
date/time operands.

If there is no value in the given range, then this operator shows NULL value.

Syntax of BETWEEN operator:

1. SELECT column_Name1, column_Name2 ...., column_NameN FROM tabl


e_Name WHERE column_nameBETWEEN value1 and value2;

Let's understand the below example which explains how to execute


BETWEEN logical operator in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi

202 Ankit 45000 Chandigarh

203 Bheem 30000 Delhi

204 Ram 25000 Delhi

205 Sumit 40000 Kolkata

o Suppose, we want to access all the information of those employees from


the Employee_details table who is having salaries between 20000 and
40000. For this, we have to write the following query in SQL:

63
1. SELECT * FROM Employee_details WHERE Emp_Salary BETWEEN 30000
AND 45000;

Here, we used the SQL BETWEEN operator with the Emp_Salary field.

SQL IN Operator

The IN operator in SQL allows database users to specify two or more values in a
WHERE clause. This logical operator minimizes the requirement of multiple OR
conditions.

This operator makes the query easier to learn and understand. This operator
returns those rows whose values match with any value of the given list.

Syntax of IN operator:

1. SELECT column_Name1, column_Name2 ...., column_NameN FROM tabl


e_Name WHERE column_name IN (list_of_values);

Let's understand the below example which explains how to execute IN logical
operator in SQL query:

This example consists of an Employee_details table, which has three


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi

202 Ankit 45000 Chandigarh

203 Bheem 30000 Delhi

204 Ram 25000 Delhi

205 Sumit 40000 Kolkata

64
o Suppose, we want to show all the information of those employees from
the Employee_details table whose Employee Id is 202, 204, and 205. For
this, we have to write the following query in SQL:

1. SELECT * FROM Employee_details WHERE Emp_Id IN (202, 204, 205);

Here, we used the SQL IN operator with the Emp_Id column.

o Suppose, we want to show all the information of those employees from


the Employee_details table whose Employee Id is not equal to 202 and
205. For this, we have to write the following query in SQL:

1. SELECT * FROM Employee_details WHERE Emp_Id NOT IN (202,205);

2.

Here, we used the SQL NOT IN operator with the Emp_Id column.

SQL NOT Operator

The NOT operator in SQL shows the record from the table if the condition
evaluates to false. It is always used with the WHERE clause.

Syntax of NOT operator:

1. SELECT column1, column2 ...., columnN FROM table_Name WHERE NOT


condition;

Let's understand the below example which explains how to execute NOT
logical operator in SQL query:

This example consists of an Employee_details table, which has four


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi

202 Ankit 45000 Chandigarh

65
203 Bheem 30000 Delhi

204 Ram 25000 Delhi

205 Sumit 40000 Kolkata

o Suppose, we want to show all the information of those employees from


the Employee_details table whose Cityis not Delhi. For this, we have to
write the following query in SQL:

1. SELECT * FROM Employee_details WHERE NOT Emp_City = 'Delhi' ;

In this example, we used the SQL NOT operator with the Emp_City column.

o Suppose, we want to show all the information of those employees from


the Employee_details table whose Cityis not Delhi and Chandigarh. For
this, we have to write the following query in SQL:

1. SELECT * FROM Employee_details WHERE NOT Emp_City = 'Delhi' AND N


OT Emp_City = 'Chandigarh';

In this example, we used the SQL NOT operator with the Emp_City column.

SQL ANY Operator

The ANY operator in SQL shows the records when any of the values returned
by the sub-query meet the condition.

The ANY logical operator must match at least one record in the inner query and
must be preceded by any SQL comparison operator.

Syntax of ANY operator:

1. SELECT column1, column2 ...., columnN FROM table_Name WHERE colu


mn_name comparison_operator ANY ( SELECT column_name FROM tabl
e_name WHERE condition(s)) ;

SQL LIKE Operator

The LIKE operator in SQL shows those records from the table which match with
the given pattern specified in the sub-query.
66
The percentage (%) sign is a wildcard which is used in conjunction with this
logical operator.

This operator is used in the WHERE clause with the following three statements:

1. SELECT statement

2. UPDATE statement

3. DELETE statement

Syntax of LIKE operator:

1. SELECT column_Name1, column_Name2 ...., column_NameN FROM tabl


e_Name WHERE column_name LIKE pattern;

Let's understand the below example which explains how to execute LIKE
logical operator in SQL query:

This example consists of an Employee_details table, which has four


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Chandigarh

203 Saket 30000 Delhi

204 Abhay 25000 Delhi

205 Sumit 40000 Kolkata

o If we want to show all the information of those employees from


the Employee_details whose name starts with ''s''. For this, we have to
write the following query in SQL:

1. SELECT * FROM Employee_details WHERE Emp_Name LIKE 's%' ;

67
In this example, we used the SQL LIKE operator with Emp_Name column
because we want to access the record of those employees whose name starts
with s.

o If we want to show all the information of those employees from


the Employee_detailswhose name ends with ''y''. For this, we have to
write the following query in SQL:

1. SELECT * FROM Employee_details WHERE Emp_Name LIKE '%y' ;

o If we want to show all the information of those employees from


the Employee_detailswhose name starts with ''S'' and ends with ''y''. For
this, we have to write the following query in SQL:

1. SELECT * FROM Employee_details WHERE Emp_Name LIKE 'S%y' ;

SQL Set Operators

The Set Operators in SQL combine a similar type of data from two or more SQL
database tables. It mixes the result, which is extracted from two or more SQL
queries, into a single result.

Set operators combine more than one select statement in a single query and
return a specific result set.

Following are the various set operators which are performed on the similar
data stored in the two SQL database tables:

1. SQL Union Operator

2. SQL Union ALL Operator

3. SQL Intersect Operator

4. SQL Minus Operator

SQL Union Operator

The SQL Union Operator combines the result of two or more SELECT
statements and provides the single output.

68
The data type and the number of columns must be the same for each SELECT
statement used with the UNION operator. This operator does not show the
duplicate records in the output table.

Syntax of UNION Set operator:

1. SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE co


nditions]

2. UNION

3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE co


nditions];

Let's understand the below example which explains how to execute Union
operator in Structured Query Language:

In this example, we used two tables. Both tables have four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Delhi

203 Saket 30000 Aligarh

Table: Employee_details1

Emp Id Emp Name Emp Salary Emp City

203 Saket 30000 Aligarh

204 Saurabh 40000 Delhi

69
205 Ram 30000 Kerala

201 Sanjay 25000 Delhi

Table: Employee_details2

o Suppose, we want to see the employee name and employee id of each


employee from both tables in a single output. For this, we have to write
the following query in SQL:

1. SELECT Emp_ID, Emp_Name FROM Employee_details1

2. UNION

3. SELECT Emp_ID, Emp_Name FROM Employee_details2 ;

SQL Union ALL Operator

The SQL Union Operator is the same as the UNION operator, but the only
difference is that it also shows the same record.

Syntax of UNION ALL Set operator:

1. SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE co


nditions]

2. UNION ALL

3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE co


nditions];

Let's understand the below example which explains how to execute Union
ALL operator in Structured Query Language:

In this example, we used two tables. Both tables have four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

70
201 Sanjay 25000 Delhi

202 Ajay 45000 Delhi

203 Saket 30000 Aligarh

Table: Employee_details1

Emp Id Emp Name Emp Salary Emp City

203 Saket 30000 Aligarh

204 Saurabh 40000 Delhi

205 Ram 30000 Kerala

201 Sanjay 25000 Delhi

Table: Employee_details2

o If we want to see the employee name of each employee of both tables in


a single output. For this, we have to write the following query in SQL:

1. SELECT Emp_Name FROM Employee_details1

2. UNION ALL

3. SELECT Emp_Name FROM Employee_details2 ;

SQL Intersect Operator

71
The SQL Intersect Operator shows the common record from two or more
SELECT statements. The data type and the number of columns must be the
same for each SELECT statement used with the INTERSECT operator.

Syntax of INTERSECT Set operator:

1. SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE co


nditions]

2. INTERSECT

3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE co


nditions];

Let's understand the below example which explains how to execute


INTERSECT operator in Structured Query Language:

In this example, we used two tables. Both tables have four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Delhi

203 Saket 30000 Aligarh

Table: Employee_details1

Emp Id Emp Name Emp Salary Emp City

72
203 Saket 30000 Aligarh

204 Saurabh 40000 Delhi

205 Ram 30000 Kerala

201 Sanjay 25000 Delhi

Table: Employee_details2

Suppose, we want to see a common record of the employee from both the
tables in a single output. For this, we have to write the following query in SQL:

1. SELECT Emp_Name FROM Employee_details1

2. INTERSECT

3. SELECT Emp_Name FROM Employee_details2 ;

SQL Minus Operator

The SQL Minus Operator combines the result of two or more SELECT
statements and shows only the results from the first data set.

Syntax of MINUS operator:

1. SELECT column1, column2 ...., columnN FROM First_tablename [WHERE


conditions]

2. MINUS

3. SELECT column1, column2 ...., columnN FROM Second_tablename [WHE


RE conditions];

Let's understand the below example which explains how to execute


INTERSECT operator in Structured Query Language:

In this example, we used two tables. Both tables have four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.

73
Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Delhi

203 Saket 30000 Aligarh

Table: Employee_details1

Emp Id Emp Name Emp Salary Emp City

203 Saket 30000 Aligarh

204 Saurabh 40000 Delhi

205 Ram 30000 Kerala

201 Sanjay 25000 Delhi

Table: Employee_details2

Suppose, we want to see the name of employees from the first result set after
the combination of both tables. For this, we have to write the following query
in SQL:

1. SELECT Emp_Name FROM Employee_details1

2. MINUS

3. SELECT Emp_Name FROM Employee_details2 ;

SQL Unary Operators

The Unary Operators in SQL perform the unary operations on the single data of
the SQL table, i.e., these operators operate only on one operand.

74
These types of operators can be easily operated on the numeric data value of
the SQL table.

Following are the various unary operators which are performed on the
numeric data stored in the SQL table:

1. SQL Unary Positive Operator

2. SQL Unary Negative Operator

3. SQL Unary Bitwise NOT Operator

SQL Unary Positive Operator

The SQL Positive (+) operator makes the numeric value of the SQL table
positive.

Syntax of Unary Positive Operator

1. SELECT +(column1), +(column2) ...., +(columnN) FROM table_Name [WH


ERE conditions] ;

Let's understand the below example which explains how to execute a Positive
unary operator on the data of SQL table:

This example consists of anEmployee_details table, which has four


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Chandigarh

203 Saket 30000 Delhi

204 Abhay 25000 Delhi

75
205 Sumit 40000 Kolkata

o Suppose, we want to see the salary of each employee as positive from


the Employee_details table. For this, we have to write the following
query in SQL:

1. SELECT +Emp_Salary Employee_details ;

SQL Unary Negative Operator

The SQL Negative (-) operator makes the numeric value of the SQL table
negative.

Syntax of Unary Negative Operator

1. SELECT -(column_Name1), -(column_Name2) ...., -


(column_NameN) FROM table_Name [WHERE conditions] ;

Let's understand the below example which explains how to execute Negative
unary operator on the data of SQL table:

This example consists of an Employee_details table, which has four


columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Chandigarh

203 Saket 30000 Delhi

204 Abhay 25000 Delhi

205 Sumit 40000 Kolkata

76
o Suppose, we want to see the salary of each employee as negative from
the Employee_details table. For this, we have to write the following
query in SQL:

1. SELECT -Emp_Salary Employee_details ;

o Suppose, we want to see the salary of those employees as negative


whose city is Kolkatain the Employee_details table. For this, we have to
write the following query in SQL:

1. SELECT -Emp_Salary Employee_details WHERE Emp_City = 'Kolkata';

SQL Bitwise NOT Operator

The SQL Bitwise NOT operator provides the one's complement of the single
numeric operand. This operator turns each bit of numeric value. If the bit of
any numerical value is 001100, then this operator turns these bits into 110011.

Syntax of Bitwise NOT Operator

1. SELECT ~(column1), ~(column2) ...., ~(columnN) FROM table_Name [WH


ERE conditions] ;

Let's understand the below example which explains how to execute the
Bitwise NOT operator on the data of SQL table:

This example consists of aStudent_details table, which has four


columns Roll_No, Stu_Name, Stu_Marks, and Stu_City.

Emp Id Stu Name Stu Marks Stu City

101 Sanjay 85 Delhi

102 Ajay 97 Chandigarh

103 Saket 45 Delhi

104 Abhay 68 Delhi

77
105 Sumit 60 Kolkata

If we want to perform the Bitwise Not operator on the marks column


of Student_details, we have to write the following query in SQL:

1. SELECT ~Stu_Marks Employee_details ;

SQL Bitwise Operators

The Bitwise Operators in SQL perform the bit operations on the Integer values.
To understand the performance of Bitwise operators, you just knew the basics
of Boolean algebra.

Following are the two important logical operators which are performed on
the data stored in the SQL database tables:

1. Bitwise AND (&)

2. Bitwise OR(|)

Bitwise AND (&)

The Bitwise AND operator performs the logical AND operation on the given
Integer values. This operator checks each bit of a value with the corresponding
bit of another value.

Syntax of Bitwise AND Operator

1. SELECT column1 & column2 & .... & columnN FROM table_Name [WHER
E conditions] ;

Let's understand the below example which explains how to execute Bitwise
AND operator on the data of SQL table:

This example consists of the following table, which has two columns. Each
column holds numerical values.

When we use the Bitwise AND operator in SQL, then SQL converts the values of
both columns in binary format, and the AND operation is performed on the
converted bits.

78
After that, SQL converts the resultant bits into user understandable format, i.e.,
decimal format.

Column1 Column2

1 1

2 5

3 4

4 2

5 3

o Suppose, we want to perform the Bitwise AND operator between both


the columns of the above table. For this, we have to write the following
query in SQL:

1. SELECT Column1 & Column2 From TABLE_AND ;

Bitwise OR (|)

The Bitwise OR operator performs the logical OR operation on the given Integer
values. This operator checks each bit of a value with the corresponding bit of
another value.

Syntax of Bitwise OR Operator

1. SELECT column1 | column2 | .... | columnN FROM table_Name [WHERE


conditions] ;

Let's understand the below example which explains how to execute Bitwise
OR operator on the data of SQL table:

This example consists of a table that has two columns. Each column holds
numerical values.

79
When we used the Bitwise OR operator in SQL, then SQL converts the values of
both columns in binary format, and the OR operation is performed on the
binary bits. After that, SQL converts the resultant binary bits into user
understandable format, i.e., decimal format.

Column1 Column2

1 1

2 5

3 4

4 2

5 3

o Suppose, we want to perform the Bitwise OR operator between both the


columns of the above table. For this, we have to write the following
query in SQL:

1. SELECT Column1 | Column2 From TABLE_OR ;

Characteristics of SQL

o SQL is easy to learn.

o SQL is used to access data from relational database management


systems.

o SQL can execute queries against the database.

o SQL is used to describe the data.

o SQL is used to define the data in the database and manipulate it when
needed.

o SQL is used to create and drop the database and table.

80
o SQL is used to create a view, stored procedure, function in a database.

o SQL allows users to set permissions on tables, procedures, and views.

Advantages of SQL
There are the following advantages of SQL:

High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of records
from a database.

No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.

Well defined standards


Long established are used by the SQL databases that are being used by ISO and ANSI.

Portability
SQL can be used in laptop, PCs, server and even some mobile phones.

Interactive language
SQL is a domain language used to communicate with the database. It is also used to receive
answers to the complex questions in seconds.

Multiple data view


Using the SQL language, the users can make different views of the database structure.

81

You might also like