0% found this document useful (0 votes)
37 views29 pages

Unit 4

Uploaded by

harsh1234mathur
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)
37 views29 pages

Unit 4

Uploaded by

harsh1234mathur
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/ 29

UNIT-4

Structured Query Language (SQL)


Structured Query Language is a standard Database language that is
used to create, maintain, and retrieve the relational database. In
this article, we will discuss this in detail about SQL. Following are
some interesting facts about SQL. Let’s focus on that.
SQL is case insensitive. But it is a recommended practice to use
keywords (like SELECT, UPDATE, CREATE, etc.) in capital letters and
use user-defined things (like table name, column name, etc.) in
small letters.
We can write comments in SQL using “–” (double hyphen) at the
beginning of any line. SQL is the programming language for
relational databases (explained below) like MySQL, Oracle, Sybase,
SQL Server, Postgre, etc. Other non-relational databases (also
called NoSQL) databases like MongoDB, DynamoDB, etc. do not use
SQL.
Although there is an ISO standard for SQL, most of the
implementations slightly vary in syntax. So we may encounter
queries that work in SQL Server but do not work in MySQL.
What is Relational Database?
A relational database means the data is stored as well as retrieved
in the form of relations (tables). Table 1 shows the relational
database with only one relation called STUDENT which
stores ROLL_NO, NAME, ADDRESS, PHONE, and AGE of students.
STUDENT Table
ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18


ROLL_NO NAME ADDRESS PHONE AGE

Important Terminologies
These are some important terminologies that are used in terms of
relation.
 Attribute:Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME etc.
 Tuple:Each row in the relation is known as tuple. The above
relation contains 4 tuples, one of which is shown as:
1 RAM DELHI 9455123451 18

 Degree:The number of attributes in the relation is known as


degree of the relation. The STUDENT relation defined above has
degree 5.
 Cardinality:The number of tuples in a relation is known as
cardinality. The STUDENTrelation defined above has cardinality
4.
 Column:Column represents the set of values for a particular
attribute. The column ROLL_NO is extracted from relation
STUDENT.
ROLL_NO

4
How Queries can be Categorized in Relational
Database?
The queries to deal with relational database can be categorized as:
 Data Definition Language:It is used to define the structure of
the database. e.g; CREATE TABLE, ADD COLUMN, DROP COLUMN
and so on.
 Data Manipulation Language:It is used to manipulate data in
the relations. e.g.; INSERT, DELETE, UPDATE and so on.
 Data Query Language:It is used to extract the data from the
relations. e.g.; SELECT So first we will consider the Data Query
Language. A generic query to retrieve data from a relational
database is:
1. SELECT [DISTINCT] Attribute_List FROM R1,R2….RM
2. [WHERE condition]
3. [GROUP BY (Attributes)[HAVING condition]]
4. [ORDER BY(Attributes)[DESC]];
Part of the query represented by statement 1 is compulsory if you
want to retrieve from a relational database. The statements written
inside [] are optional. We will look at the possible query combination
on relation shown in Table 1.
Different Query Combinations
Case 1: If we want to retrieve attributes ROLL_NO and NAMEof all
students, the query will be:
SELECT ROLL_NO, NAME FROM STUDENT;

ROLL_NO NAME

1 RAM

2 RAMESH

3 SUJIT

4 SURESH
Case 2: If we want to retrieve ROLL_NO and NAME of the students
whose ROLL_NO is greater than 2, the query will be:
SELECT ROLL_NO, NAME FROM STUDENT
WHERE ROLL_NO>2;

ROLL_NO NAME

3 SUJIT

4 SURESH

CASE 3: If we want to retrieve all attributes of students, we can


write * in place of writing all attributes as:
SELECT * FROM STUDENT
WHERE ROLL_NO>2;

ROLL_NO NAME ADDRESS PHONE AGE

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

CASE 4: If we want to represent the relation in ascending order


by AGE, we can use ORDER BY clause as:
SELECT * FROM STUDENT ORDER BY AGE;

ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

4 SURESH DELHI 9156768971 18


ROLL_NO NAME ADDRESS PHONE AGE

3 SUJIT ROHTAK 9156253131 20

Note:
ORDER BY AGEis equivalent to ORDER BY AGE ASC.
If we want to retrieve the results in descending order of AGE,
we can use ORDER BY AGE DESC.

CASE 5: If we want to retrieve distinct values of an attribute or


group of attribute, DISTINCT is used as in:
SELECT DISTINCT ADDRESS FROM STUDENT;

ADDRESS

DELHI

GURGAON

ROHTAK

If DISTINCT is not used, DELHI will be repeated twice in result set.


Before understanding GROUP BY and HAVING, we need to
understand aggregations functions in SQL.
Aggregation Functions
Aggregation functions are used to perform mathematical operations
on data values of a relation. Some of the common aggregation
functions used in SQL are:
 COUNT: Count function is used to count the number of rows in a
relation. e.g;
SELECT COUNT (PHONE) FROM STUDENT;
COUNT(PHONE)

 SUM: SUM function is used to add the values of an attribute in a


relation. e.g;
SELECT SUM(AGE) FROM STUDENT;

SUM(AGE)

74

In the same way, MIN, MAX and AVG can be used. As we have seen
above, all aggregation functions return only 1 row. AVERAGE: It
gives the average values of the tupples. It is also defined as sum
divided by count values.
Syntax:
AVG(attributename)
OR
SUM(attributename)/COUNT(attributename)
The above mentioned syntax also retrieves the average value of
tupples.
 MAXIMUM:It extracts the maximum value among the set of
tupples.
Syntax:
MAX(attributename)
 MINIMUM:It extracts the minimum value amongst the set of all
the tupples.
Syntax:
MIN(attributename)
 GROUP BY:Group by is used to group the tuples of a relation
based on an attribute or group of attribute. It is always combined
with aggregation function which is computed on group. e.g.;
SELECT ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);
In this query, SUM(AGE) will be computed but not for entire table
but for each address. i.e.; sum of AGE for address DELHI(18+18=36)
and similarly for other address as well. The output is:
ADDRESS SUM(AGE)

DELHI 36

GURGAON 18

ROHTAK 20

If we try to execute the query given below, it will result in error


because although we have computed SUM(AGE) for each address,
there are more than 1 ROLL_NO for each address we have grouped.
So it can’t be displayed in result set. We need to use aggregate
functions on columns after SELECT statement to make sense of the
resulting set whenever we are using GROUP BY.
SELECT ROLL_NO, ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);

NOTE:
An attribute which is not a part of GROUP BY clause can’t be
used for selection.
Any attribute which is part of GROUP BY CLAUSE can be used for
selection but it is not mandatory.
But we could use attributes which are not a part of the GROUP BY
clause in an aggregate function.

Database Design in DBMS


Database Design can be defined as a set of procedures or collection
of tasks involving various steps taken to implement a database.
Following are some critical points to keep in mind to achieve a good
database design:
1. Data consistency and integrity must be maintained.
2. Low Redundancy
3. Faster searching through indices
4. Security measures should be taken by enforcing various integrity
constraints.
5. Data should be stored in fragmented bits of information in the
most atomic format possible.
However, depending on specific requirements above criteria might
change. But these are the most common things that ensure a good
database design.
What are the Following Steps that can be
taken by a Database Designer to Ensure
Good Database Design?
Step 1: Determine the goal of your database, and ensure clear
communication with the stakeholders (if any). Understanding the
purpose of a database will help in thinking of various use cases &
where the problem may arise & how we can prevent it.
Step 2: List down all the entities that will be present in the
database & what relationships exist among them.
Step 3: Organize the information into different tables such that no
or very little redundancy is there.
Step 4: Ensure uniqueness in every table. The uniqueness of
records present in any relation is a very crucial part of database
design that helps us avoid redundancy. Identify the key attributes to
uniquely identify every row from columns. You can use various key
constraints to ensure the uniqueness of your table, also keep in
mind the uniquely identifying records must consume as little space
as possible & shall not contain any NULL values.
Step 5: After all the tables are structured, and information is
organized apply Normalization Forms to identify anomalies that may
arise & redundancy that can cause inconsistency in the database.
Primary Terminologies Used in Database Design
Following are the terminologies that a person should be familiar with
before designing a database:
 Redundancy: Redundancy refers to the duplicity of the data.
There can be specific use cases when we need or don’t need
redundancy in our Database. For ex: If we have a banking system
application then we may need to strictly prevent redundancy in
our Database.
 Schema: Schema is a logical container that defines the structure
& manages the organization of the data stored in it. It consists of
rows and columns having data types for each column.
 Records/Tuples: A Record or a tuple is the same thing, basically
its where our data is stored inside a table
 Indexing: Indexing is a data structure technique to promote
efficient retrieval of the data stored in our database.
 Data Integrity & Consistency: Data integrity refers to the
quality of the information stored in our database and consistency
refers to the correctness of the data stored.
 Data Models: Data models provide us with visual modeling
techniques to visualize the data & the relationship that exists
among those data. Ex: model, Network Model, Object Oriented
Model, Hierarchical model, etc.
 Functional Dependency: Functional Dependency is a
relationship between two attributes of the table that represents
that the value of one attribute can be determined by another. Ex:
{A -> B}, A & B are two attributes and attribute A can uniquely
determine the value of B.
 Transaction: Transaction is a single logical unit of work. It
signifies that some changes are made in the database. A
transaction must satisfy the ACID or BASE properties (depending
on the type of Database).
 Schedule: Schedule defines the sequence of transactions in
which they’re executed by one or multiple users.
 Concurrency: Concurrency refers to allowing multiple
transactions to operate simultaneously without interfering with
one another.
Database Design Lifecycle
The database design lifecycle goes something like this:

Lifecycle of Database Design


1. Requirement Analysis
It’s very crucial to understand the requirements of our application so
that you can think in productive terms. And imply appropriate
integrity constraints to maintain the data integrity & consistency.
2. Logical & Physical Design
This is the actual design phase that involves various steps that are
to be taken while designing a database. This phase is further divided
into two stages:
 Logical Data Model Design: This phase consists of coming up
with a high-level design of our database based on initially
gathered requirements to structure & organize our data
accordingly. A high-level overview on paper is made of the
database without considering the physical level design, this
phase proceeds by identifying the kind of data to be stored and
what relationship will exist among those data.
Entity, Key attributes identification & what constraints are to be
implemented is the core functionality of this phase. It involves
techniques such as Data Modeling to visualize data, normalization
to prevent redundancy, etc.
 Physical Design of Data Model: This phase involves the
implementation of the logical design made in the previous stage.
All the relationships among data and integrity constraints are
implemented to maintain consistency & generate the actual
database.
3. Data Insertion and testing for various integrity
Constraints
Finally, after implementing the physical design of the database,
we’re ready to input the data & test our integrity. This phase
involves testing our database for its integrity to see if something got
left out or, if anything new to add & then integrating it with the
desired application.
Logical Data Model Design
The logical data model design defines the structure of data and
what relationship exists among those data. The following are the
major components of the logical design:
1. Data Models: Data modeling is a visual modeling technique
used to get a high-level overview of our database. Data models help
us understand the needs and requirements of our database by
defining the design of our database through diagrammatic
representation. Ex: model, Network model, Relational Model, object-
oriented data model.

Data Models

2. Entity: Entities are objects in the real world, which can have
certain properties & these properties are referred to as attributes of
that particular entity. There are 2 types of entities: Strong and weak
entity, weak entity do not have a key attribute to identify them,
their existence solely depends on one 1-specific strong entity & also
have full participation in a relationship whereas strong entity does
have a key attribute to uniquely identify them.
Weak entity example: Loan -> Loan will be given to a customer
(which is optional) & the load will be identified by the customer_id to
whom the lone is granted.
3. Relationships: How data is logically related to each other
defines the relationship of that data with other entities. In simple
words, the association of one entity with another is defined here.
A relationship can be further categorized into – unary, binary, and
ternary relationships.
 Unary: In this, the associating entity & the associated entity both
are the same. Ex: Employee Manages themselves, and students
are also given the post of monitor hence here the student
themselves is a monitor.
 Binary: This is a very common relationship that you will come
across while designing a database.
Ex: Student is enrolled in courses, Employee is managed by
different managers, One student can be taught by many
professors.
 Ternary: In this, we have 3 entities involved in a single
relationship. Ex: an employee works on a project for a client. Note
that, here we have 3 entities: Employee, Project & Client.
4. Attributes: Attributes are nothing but properties of a specific
entity that define its behavior. For example, an employee can have
unique_id, name, age, date of birth (DOB), salary, department,
Manager, project id, etc.
5. Normalization: After all the entities are put in place and the
relationship among data is defined, we need to look for loopholes or
possible ambiguities that may arise as a result of CRUD operations.
To prevent various Anomalies such as INSERTION, UPDATION, and
DELETION Anomalies.
Data Normalization is a basic procedure defined for databases to
eliminate such anomalies & prevent redundancy.
An Example of Logical Design

Logical Design Example

Physical Design
The main purpose of the physical design is to actually implement
the logical design that is, show the structure of the database along
with all the columns & their data types, rows, relations, relationships
among data & clearly define how relations are related to each other.
Following are the steps taken in physical design
Step 1: Entities are converted into tables or relations that consist of
their properties (attributes)
Step 2: Apply integrity constraints: establish foreign key, unique
key, and composite key relationships among the data. And apply
various constraints.
Step 3: Entity names are converted into table names, property
names are translated into attribute names, and so on.
Step 4: Apply normalization & modify as per the requirements.
Step 5: Final Schemes are defined based on the entities &
attributes derived in logical design.

Physical Design

What is a relational database?


A relational database is a type of database that organizes data points with defined
relationships for easy access. In the relational database model, the data structures --
data tables, indexes and views -- remain separate from the physical storage structures,
letting database administrators edit the physical data storage without affecting the
logical data structure.

In the enterprise, relational databases are used to organize data and identify
relationships between key data points. They make it easy to sort and find information,
which helps organizations make business decisions more efficiently and minimize
costs. They work well with structured data.

How does a relational database work?


Relational databases organize data into tables. The data tables used store information
about related objects in a tabular structure. This structure is what makes it easy to find
relationships between data points.

What is the structure of a relational database model?


E. F. Codd, then a programmer at IBM, invented the relational database in
1970. In his paper "A Relational Model of Data for Large Shared Data Banks,"
Codd proposed shifting from storing data in hierarchical or navigational
structures to organizing data in a tabular structure of tables containing rows
and columns.

Each table, sometimes called a relation, in a relational database contains one


or more data categories in columns, or attributes. Each row, also called
a record or tuple, contains a unique instance of data, or key, for the categories
defined by the columns. Each table has a unique primary key that identifies
the information in a table. The relationship between tables can be set via the
use of foreign keys -- a field in a table that links to the primary key of another
table.

What are the advantages of relational databases?


The key advantages of relational databases include the following:

 Categorizing data. Database administrators can easily categorize and store data
in a relational database that can then be queried and filtered to extract
information for reports. Relational databases are also easy to extend and aren't
reliant on physical organization. After the original database creation, a new data
category can be added without having to modify the existing applications.

 Accuracy. Data is stored just once, eliminating data deduplication in storage


procedures.

 Ease of use. Complex queries are easy for users to carry out with SQL, the main
query language used with relational databases.

 Collaboration. Multiple users can access the same database.

 Security. Direct access to data in tables within an RDBMS can be limited to


specific users.

 ACID. Relational databases support ACID -- atomicity, consistency, isolation, and


durability.

 Stored procedures. Relational databases also support stored procedures, which


helps ensure that specific data functions are implemented in a detailed way.

 Redundancy. Normalization and stored procedures help reduce instances of


redundancy. Likewise, primary keys also ensure there are no duplicate rows.

What are the disadvantages of relational databases?


The disadvantages of relational databases include the following:

 Structure. Relational databases require a lot of structure and a certain level of


planning because columns must be defined and data needs to fit correctly into
somewhat rigid categories. The structure is good in some situations, but it creates
issues related to the other drawbacks, such as maintenance and lack of flexibility
and scalability.
 Maintenance issues. Developers and other personnel responsible for the
database must spend time managing and optimizing the database as data gets
added to it.

 Inflexibility. Relational databases are not ideal for handling large quantities
of unstructured data. Data that is largely qualitative, not easily defined or
dynamic is not optimal for relational databases. As the data changes or evolves,
the schema must evolve with it, which takes time.

 Lack of scalability. Relational databases do not horizontally scale well across


physical storage structures with multiple servers. It is difficult to handle relational
databases across multiple servers because as a data set gets larger and more
distributed, the structure is disrupted, and the use of multiple servers has effects
on performance -- such as application response times -- and availability.

 Performance over time. Complex relational databases contain many different


tables. Over time, with an increase of data, performance might start to decrease,
and response times queries might start to slow.

Create, Alter and Drop schema in MS SQL


Server
Schema management in MS SQL Server involves creating,
altering, and dropping database schema elements such as
tables, views, stored procedures, and indexes. It ensures that the
database structure is optimized for data storage and retrieval.
In this article, we will be discussing schema and how to create,
alter, and drop the schema.
What is Schema?
A schema is usually a collection of objects. The objects can be
tables, triggers, views, procedures, etc. A database may have one or
more schemas. SQL Server provides a feature of pre-defined
schemas. The names of pre-defined schemas are very similar to
those of built-in schemas. A user can create a schema using the
syntax mentioned below.
CREATE SCHEMA [schema_name] [AUTHORIZATION owner_name]
[DEFAULT CHARACTER SET char_set_name]
[PATH schema_name[, ...]]
[ ANSI CREATE statements [...] ]
[ ANSI GRANT statements [...] ];
Create Schema in MS SQL Server
To create a schema in MS SQL Server, use the CREATE SCHEMA
statement. This statement allows you to create a new schema in
the current database and define its elements, such as tables, views,
and permissions.
Syntax
CREATE schema schema_name
[AUTHORIZATION owner_name];
 schema_name: The name of the new schema.
 AUTHORIZATION owner_name: Assigns ownership of the
schema to the specified user. The owner has control over the
resources and can provide security for the schema.
For better understanding, an example is mentioned below –
Example: Create a schema in MS SQL Server
Query:
CREATE SCHEMA student
GO
Output:
The GO command executes the statement and a new schema is
created.
Alter Schema in MS SQL Server
To alter a schema in MS SQL Server, use the ALTER
SCHEMA statement with the TRANSFER clause.
Alter is generally used to change the contents related to a table in
SQL. In case of SQL Server, alter_schema is used to transfer the
securables/contents from one schema to another within a same
database.
Syntax
ALTER SCHEMA target_schemaname
TRANSFER [ <entity_type> ::] securable name;
 target_schemaname is the name of the schema in which the
object/contents should be transferred.
 TRANSFER is a keyword that transfers the contents from one
schema to the other.
 entity_type is the contents or kind of objects that are to be
transferred.
 securable_name is the name of the schema in which the object
is present.
When a user moves the contents of the schema to another schema,
SQL server will not change the name of the schema. In case, a user
wants to change the name, drop_schema has to be used and the
objects needs to be re-created for the new schema. When the object
is moved, the SQL server will not update automatically, it must be
manually modified by user.
Example: Alter schema in MS SQL Server
A table named university has two schemas:
'student' and 'lecturer'
If suppose, the marks of the students has to be transferred to the
lecturer schema, the query is as follows.
Query:
ALTER SCHEMA lecturer
TRANSFER student.marks;
This way, the marks are transferred to the lecturer schema.
Drop Schema in MS SQL Server
To drop a schema in MS SQL Server, use the DROP SCHEMA statement.
It completely deletes the schema and its related objects including its
definition. Drop schema is used when the schema and its related
objects has to be completely banished from the database including
its definition.
Syntax
DROP SCHEMA [IF EXISTS] schema_name
 IF EXISTS (optional): If a user wants to check whether a schema
actually exists in database or not.
 schema_name: The name of the schema in the database.
Example: Drop schema in MS SQL Server
To drop the student schema from the database, use the following
query.
Query:
DROP SCHEMA [IF EXISTS] student
 Student is a schema that is actually present in the university
database.
 The schema is dropped from the database along with its
definition.
This removes the student schema from the database along with its
definition.
What are the 5 types of SQL commands?
These SQL commands are mainly categorized into five categories:
 DDL – Data Definition Language.
 DQL – Data Query Language.
 DML – Data Manipulation Language.
 DCL – Data Control Language.
 TCL – Transaction Control Language.

SQL Operators
SQL Operators perform arithmetic, comparison, and logical
operations to manipulate and retrieve data from databases.
In this article, we will discuss Operators in SQL with examples, and
understand how they work in SQL.
Operators in SQL
Operators in SQL are symbols that help us to perform specific
mathematical and logical computations on operands. An operator
can either be unary or binary.
The unary operator operates on one operand, and the binary
operator operates on two operands.
Types of Operators in SQL
Different types of operators in SQL are:
 Arithmetic operator
 Comparison operator
 Logical operator
 Bitwise Operators
 Compound Operators
SQL Arithmetic Operators
Arithmetic operators in SQL are used to perform mathematical
operations on numeric values in queries. Some common arithmetic
operators are:
Operator Description

+ The addition is used to perform an addition operation on the data values.


Operator Description

– This operator is used for the subtraction of the data values.

/ This operator works with the ‘ALL’ keyword and it calculates division
operations.

* This operator is used for multiplying data values.

% Modulus is used to get the remainder when data is divided by another.

SQL Arithmetic Operators Example


In this example, we will retrieve all records from the “employee”
table where the “emp_city” column does not start with the letter ‘A’.
Query:
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';
Output:

SQL Comparison Operators


Comparison Operators in SQL are used to compare one
expression’s value to other expressions. SQL supports different
types of comparison operator, which are described below:
Operator Description

= Equal to.

> Greater than.


Operator Description

< Less than.

>= Greater than equal to.

<= Less than equal to.

<> Not equal to.

SQL Comparison Operators Example


In this example, we will retrieve all records from the “MATHS” table
where the value in the “MARKS” column is equal to 50.
Query:
SELECT * FROM MATHS WHERE MARKS=50;
Output:

SQL Logical Operators


Logical Operators in SQL are used to combine or manipulate
conditions in SQL queries to retrieve or manipulate data based on
specified criteria..
Operator Description

AND Logical AND compares two Booleans as expressions and returns true when
both expressions are true.

OR Logical OR compares two Booleans as expressions and returns true when one
of the expressions is true.

NOT Not takes a single Boolean as an argument and change its value from false to
true or from true to false.

SQL Logical Operators Example


In this example, retrieve all records from the “employee” table
where the “emp_city” column is equal to ‘Allahabad’ and the
“emp_country” column is equal to ‘India’.
SELECT * FROM employee WHERE emp_city =
'Allahabad' AND emp_country = 'India';
Output:

SQL Bitwise Operators


Bitwise operators in SQL are used to perform bitwise operations
on binary values in SQL queries, manipulating individual bits to
perform logical operations at the bit level. Some SQL Bitwise
Operators are:
Operator Description

& Bitwise AND operator


Operator Description

| Bitwise OR operator

^ Bitwise XOR (exclusive OR) operator

~ Bitwise NOT (complement) operator

<< Left shift operator

>> Right shift operator

SQL Compound Operators


Compound operator in SQL are used to perform an operation and
assign the result to the original value in a single line. Some
Compound operators are:
Operator Description

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulo and assign

&= Bitwise AND and assign

^= Bitwise XOR and assign

|= Bitwise OR and assign

SQL Special Operators


Special operators are used in SQL queries to perform specific
operations like comparing values, checking for existence, and
filtering data based on certain conditions.
Operators Description

ALL is used to select all records of a SELECT STATEMENT. It


ALL compares a value to every value in a list of results from a query. The
ALL must be preceded by the comparison operators and evaluated
to TRUE if the query returns no rows.

ANY compares a value to each value in a list of results from a query


ANY and evaluates to true if the result of an inner query contains at least
one row.

The SQL BETWEEN operator tests an expression against a range.


BETWEEN The range consists of a beginning, followed by an AND keyword
and an end expression.

IN The IN operator checks a value within a set of values separated by


commas and retrieves the rows from the table that match.

The EXISTS checks the existence of a result of a subquery. The


EXISTS EXISTS subquery tests whether a subquery fetches at least one row.
When no data is returned then this operator returns ‘FALSE’.

SOME operator evaluates the condition between the outer and


SOME inner tables and evaluates to true if the final result returns any one
row. If not, then it evaluates to false.

The UNIQUE operator searches every unique row of a specified


UNIQUE
table.

SQL Special Operator Example


In this example, we will retrieve all records from the “employee”
table where the “emp_id” column has a value that falls within the
range of 101 to 104 (inclusive).
SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;
Output:
SQL | Subquery
Last Updated : 30 Jul, 2024



In SQL a Subquery can be simply defined as a query within another query. In


other words we can say that a Subquery is a query that is embedded in
WHERE clause of another SQL query. Important rules for Subqueries:
 You can place the Subquery in a number of SQL
clauses: WHERE clause, HAVING clause, FROM clause. Subqueries can
be used with SELECT, UPDATE, INSERT, DELETE statements along
with expression operator. It could be equality operator or comparison
operator such as =, >, =, <= and Like operator.
 A subquery is a query within another query. The outer query is called
as main query and inner query is called as subquery.
 The subquery generally executes first when the subquery doesn’t have
any co-relation with the main query, when there is a co-relation the
parser takes the decision on the fly on which query to execute
on precedence and uses the output of the subquery accordingly.
 Subquery must be enclosed in parentheses.
 Subqueries are on the right side of the comparison operator.
 Use single-row operators with single row Subqueries. Use multiple-row
operators with multiple-row Subqueries.
Syntax: There is not any general syntax for Subqueries. However,
Subqueries are seen to be used most frequently with SELECT statement as
shown below:
SELECT column_name
FROM table_name
WHERE column_name expression operator
(SELECT column_name FROM table_name WHERE ...);
Sample Table:
DATABASE
NAME ROLL_NO LOCATION PHONE_NUMBER

Ram 101 Chennai 9988775566

Raj 102 Coimbatore 8877665544

Sasi 103 Madurai 7766553344

Ravi 104 Salem 8989898989

Sumathi 105 Kanchipuram 8989856868

STUDENT
NAME ROLL_NO SECTION

Ravi 104 A

Sumathi 105 B

Raj 102 A

Sample Queries:
 To display NAME, LOCATION, PHONE_NUMBER of the students from
DATABASE table whose section is A
SELECT NAME, LOCATION, PHONE_NUMBER
FROM DATABASE
WHERE ROLL_NO IN (SELECT ROLL_NO
FROM STUDENT
WHERE SECTION='A');
 Explanation : First subquery executes “ SELECT ROLL_NO from
STUDENT where SECTION=’A’ ” returns ROLL_NO from STUDENT table
whose SECTION is ‘A’.Then outer-query executes it and return the
NAME, LOCATION, PHONE_NUMBER from the DATABASE table of the
student whose ROLL_NO is returned from inner subquery. Output:
NAME ROLL_NO LOCATION PHONE_NUMBER

Ravi 104 Salem 8989898989

Raj 102 Coimbatore 8877665544

 Insert Query Example:


Table1: Student1
NAME ROLL_NO LOCATION PHONE_NUMBER

Ram 101 chennai 9988773344

Raju 102 coimbatore 9090909090

Ravi 103 salem 8989898989

Table2: Student2
NAME ROLL_NO LOCATION PHONE_NUMBER

Raj 111 chennai 8787878787

Sai 112 mumbai 6565656565

Sri 113 coimbatore 7878787878

 To insert Student2 into Student1 table:


INSERT INTO Student1
SELECT * FROM Student2;
 Output:
NAME ROLL_NO LOCATION PHONE_NUMBER

Ram 101 chennai 9988773344

Raju 102 coimbatore 9090909090

Ravi 103 salem 8989898989

Raj 111 chennai 8787878787

Sai 112 mumbai 6565656565

Sri 113 coimbatore 7878787878

 To delete students from Student2 table whose rollno is same as that in


Student1 table and having location as chennai
DELETE FROM Student2
WHERE ROLL_NO IN (SELECT ROLL_NO
FROM Student1
WHERE LOCATION = 'chennai');
 Output:
1 row delete successfully.
 Display Student2 table:
NAME ROLL_NO LOCATION PHONE_NUMBER

Sai 112 mumbai 6565656565

Sri 113 coimbatore 7878787878

 To update name of the students to geeks in Student2 table whose


location is same as Raju,Ravi in Student1 table
UPDATE Student2
SET NAME='geeks'
WHERE LOCATION IN (SELECT LOCATION
FROM Student1
WHERE NAME IN ('Raju', 'Ravi'));
 Output:
1 row updated successfully.
 Display Student2 table:
NAME ROLL_NO LOCATION PHONE_NUMBER

Sai 112 mumbai 6565656565

geeks 113 coimbatore 7878787878

You might also like