SlideShare a Scribd company logo
SQL
SubQuery
1
ICT Level V
COT - Jaffna
S.Sakthybaalan
2
What Is a Subquery?
 A subquery is a SELECT statement embedded in a
clause of another SQL statement (SELECT, INSERT,
UPDATE, DELETE).
SELECT . . .
FROM . . .
WHERE . . .
(SELECT . . .
FROM . . .
WHERE . . .)
Main
Query
Subquery
SQL subquery is usually added in the WHERE Clause
of the SQL statement.
3
The basic concept is to pass a single value
4
3
2
1
When reading or writing SQL subqueries, you should start from
the bottom upwards, working out which data is to be passed to
the next query up.
4
SQL Subquery
 Subquery or Inner query or Nested query.
 An alternate way of returning data from multiple tables.
 Subqueries can be used with the following SQL statements
along with the comparision operators like =, <, >, >=, <= etc.
 Subqueries can also be used inside the WHERE or HAVING
clause.
5
Sub-query Syntax
• The subquery (inner query) executes once
before the main query.
• The result of the subquery is used by the main
query (outer query).
6
Using a Subquery to Solve a
Problem  To solve this problem, you need
two queries: one to find what
Abel earns, and a second query
to find who earns more than that
amount.
 You can solve this problem by
combining the two queries,
placing one query inside the
other query.
 The inner query or the subquery
returns a value that is used by the
outer query or the main query.
 Using a subquery is equivalent to
performing two sequential
queries and using the result of the
first query as the search value in
the second query.
7
Example :
 In the slide, the inner query determines the salary of employee Abel.
 The outer query takes the result of the inner query and uses this result to display
all the employees who earn more than this amount.
 Execute the subquery (inner query) on its own first to show the value that
the subquery returns.
 Then execute the outer query using the result returned by the inner query.
Finally, execute the entire query (containing the subquery), and show
that the result is the same.
8
Types of SubQueries
SubQueries
Single-row subqueries Multiple-row subqueries
9
Types of Subqueries
 Single-row subqueries:
Queries that return only one
row from the inner SELECT
statement
 Multiple-row subqueries:
Queries that return more than
one row from the inner SELECT
statement
10
Single-Row Subqueries
 Return only one row
 Use single-row comparison operators
11
Executing Single-Row Subqueries
 A SELECT statement can be considered as a query block.
 The example on the slide displays employees whose job ID is the same as that of
employee 141 and whose salary is greater than that of employee 143.
 The example consists of three query blocks: the outer query and two inner queries.
 The inner query blocks are executed first, producing the query results ST_CLERK and
2600, respectively.
 The outer query block is then processed and uses the values returned by the inner
queries to complete its search conditions.
12
Problems with Subqueries
 A common problem with subqueries is no rows being returned by the inner query.
 There is no employee named Haas. So the subquery returns no rows.
13
Multiple-Row Subqueries
 Subqueries that return more
than one row are called
multiple-row subqueries.
 You use a multiple-row
operator, instead of a single-
row operator, with a
multiple-row subquery.
 The multiple-row operator
expects one or more values.
14
Example :
The NOT operator can be used with IN, ANY, and
ALL operators.
15
Exercise 1 :
Track
cID Num Title Time aID
1 1 Violent 239 1
1 2 Every Girl 410 1
1 3 Breather 217 1
1 4 Part of Me 279 1
2 1 Star 362 1
2 2 Teaboy 417 2
CD
cID Title Price
1 Mix 9.99
2 Compilation 12.99
Artist
aID Name
1 Stellar
2 Cloudboy
• Find a list of all the CD titles.
• Find a list of the titles of tracks that are more than 300 seconds long.
• Find a list of the names of those artists who have a track on the CD
with the title “Compilation”.
16
LOCATION
Location_ID Regional_Group
122 NEW YORK
123 DALLAS
124 CHICAGO
167 BOSTON
DEPARTMENT
Department_ID Name Location_ID
10 ACCOUNTING 122
20 RESEARCH 124
30 SALES 123
40 OPERATIONS 167
JOB
Job_ID Function
667 CLERK
668 STAFF
669 ANALYST
670 SALESPERSON
671 MANAGER
672 PRESIDENT
EMPLOYEE
EMPLOYEE
_ID
LAST_NAME FIRST_NAME
MIDDLE_
NAME
JOB_ID
MANAGER
_ID
HIREDATE SALARY COMM
DEPARTME
NT_ID
7369 SMITH JOHN Q 667 7902 17-DEC-84 800 NULL 20
7499 ALLEN KEVIN J 670 7698 20-FEB-85 1600 300 30
7505 DOYLE JEAN K 671 7839 04-APR-85 2850 NULL 30
7506 DENNIS LYNN S 671 7839 15-MAY-85 2750 NULL 30
7507 BAKER LESLIE D 671 7839 10-JUN-85 2200 NULL 40
7521 WARK CYNTHIA D 670 7698 22-FEB-85 1250 500 30
Exercise 2 :
17
1. Display the employee who got the maximum salary.
SELECT *
FROM employee
WHERE salary =(SELECT MAX(salary) FROM employee)
2. Find out no.of employees working in “Sales” department.
SELECT *
FROM employee
WHERE department_id =(SELECT department_id
FROM department
WHERE name=’SALES’
GROUP BY department_id)
Sub-Queries
18
3. Delete the employees who are working in accounting
department.
DELETE FROM employee
WHERE department_id =(SELECT department_id
FROM department
WHERE name=’ACCOUNTING’)
4. Display the second highest salary drawing employee details.
SELECT *
FROM employee
WHERE salary =( SELECT MAX(salary)
FROM employee
WHERE salary <(SELECT MAX(salary)
FROM employee))
19
Any Questions ?
20
Ad

More Related Content

What's hot (20)

Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testers
tlvd
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sql
Charan Reddy
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
Rayhan Chowdhury
 
AGGREGATE FUNCTION.pptx
AGGREGATE FUNCTION.pptxAGGREGATE FUNCTION.pptx
AGGREGATE FUNCTION.pptx
Anusha sivakumar
 
Aggregate Function - Database
Aggregate Function - DatabaseAggregate Function - Database
Aggregate Function - Database
Shahadat153031
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan Pasricha
MananPasricha
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
Ritwik Das
 
Creating Views - oracle database
Creating Views - oracle databaseCreating Views - oracle database
Creating Views - oracle database
Salman Memon
 
Sql Constraints
Sql ConstraintsSql Constraints
Sql Constraints
I L0V3 CODING DR
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
Vikas Gupta
 
SQL Data Manipulation
SQL Data ManipulationSQL Data Manipulation
SQL Data Manipulation
khalid alkhafagi
 
Sql joins
Sql joinsSql joins
Sql joins
Gaurav Dhanwant
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query Optimization
Brian Gallagher
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
programmings guru
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL
EDB
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
Aliya Saldanha
 
SQL commands
SQL commandsSQL commands
SQL commands
GirdharRatne
 
Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testers
tlvd
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sql
Charan Reddy
 
Aggregate Function - Database
Aggregate Function - DatabaseAggregate Function - Database
Aggregate Function - Database
Shahadat153031
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan Pasricha
MananPasricha
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai
 
Creating Views - oracle database
Creating Views - oracle databaseCreating Views - oracle database
Creating Views - oracle database
Salman Memon
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
Vikas Gupta
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query Optimization
Brian Gallagher
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
programmings guru
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL
EDB
 

Viewers also liked (20)

Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
Salman Memon
 
Sql subquery
Sql subquerySql subquery
Sql subquery
Vivek Singh
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueries
ecomputernotes
 
Technical stream presentation
Technical stream presentationTechnical stream presentation
Technical stream presentation
Dynistics
 
Subqueries
SubqueriesSubqueries
Subqueries
Yaswanth Babu Gummadivelli
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
Antonios Chatzipavlis
 
Microsoft SQL Server PowerPivot
Microsoft SQL Server PowerPivotMicrosoft SQL Server PowerPivot
Microsoft SQL Server PowerPivot
Mark Ginnebaugh
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
rehaniltifat
 
T-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, IntersectT-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, Intersect
Bill Lin
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
Bharat Kalia
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
SQL Views
SQL ViewsSQL Views
SQL Views
baabtra.com - No. 1 supplier of quality freshers
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
Nick Buytaert
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
mohdoracle
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
Felipe Costa
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
Sql joins
Sql joinsSql joins
Sql joins
Berkeley
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
DataminingTools Inc
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
pitchaiah yechuri
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
Salman Memon
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueries
ecomputernotes
 
Technical stream presentation
Technical stream presentationTechnical stream presentation
Technical stream presentation
Dynistics
 
Microsoft SQL Server PowerPivot
Microsoft SQL Server PowerPivotMicrosoft SQL Server PowerPivot
Microsoft SQL Server PowerPivot
Mark Ginnebaugh
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
rehaniltifat
 
T-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, IntersectT-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, Intersect
Bill Lin
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
Bharat Kalia
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
Nick Buytaert
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
mohdoracle
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
Felipe Costa
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
Ad

Similar to Sub query_SQL (20)

Dbms question
Dbms questionDbms question
Dbms question
Ricky Dky
 
7. Using Sub Queries
7. Using Sub Queries7. Using Sub Queries
7. Using Sub Queries
Evelyn Oluchukwu
 
SUBQUERIES.pptx
SUBQUERIES.pptxSUBQUERIES.pptx
SUBQUERIES.pptx
RenugadeviR5
 
Ch 6 Sub Query.pptx
Ch 6 Sub Query.pptxCh 6 Sub Query.pptx
Ch 6 Sub Query.pptx
RamishaRauf
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
Balqees Al.Mubarak
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
IMsKanchanaI
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
Dhananjay Goel
 
How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?
loginworks software
 
Database object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab AssignmentDatabase object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab Assignment
Arun Sial
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Abhishek590097
 
Week6_Theory.pptx
Week6_Theory.pptxWeek6_Theory.pptx
Week6_Theory.pptx
MDTOUKERAHMED
 
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdf
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdfOracle Database Administration I (1Z0-082) Exam Dumps 2024.pdf
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdf
SkillCertProExams
 
Data base management system full details
Data base management system full detailsData base management system full details
Data base management system full details
NitinYadav690862
 
SQL command for daily use ddl dml dcl dql
SQL command for daily use ddl dml dcl dqlSQL command for daily use ddl dml dcl dql
SQL command for daily use ddl dml dcl dql
kashyapdaksh29
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
ami111
 
Les06
Les06Les06
Les06
Vijay Kumar
 
Les06
Les06Les06
Les06
Sudharsan S
 
Optimizing MySQL Queries
Optimizing MySQL QueriesOptimizing MySQL Queries
Optimizing MySQL Queries
Achievers Tech
 
Chapter15
Chapter15Chapter15
Chapter15
gourab87
 
Ch-2-Query-Process.pptx advanced database
Ch-2-Query-Process.pptx advanced databaseCh-2-Query-Process.pptx advanced database
Ch-2-Query-Process.pptx advanced database
tasheebedane
 
Dbms question
Dbms questionDbms question
Dbms question
Ricky Dky
 
Ch 6 Sub Query.pptx
Ch 6 Sub Query.pptxCh 6 Sub Query.pptx
Ch 6 Sub Query.pptx
RamishaRauf
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
IMsKanchanaI
 
How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?
loginworks software
 
Database object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab AssignmentDatabase object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab Assignment
Arun Sial
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Abhishek590097
 
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdf
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdfOracle Database Administration I (1Z0-082) Exam Dumps 2024.pdf
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdf
SkillCertProExams
 
Data base management system full details
Data base management system full detailsData base management system full details
Data base management system full details
NitinYadav690862
 
SQL command for daily use ddl dml dcl dql
SQL command for daily use ddl dml dcl dqlSQL command for daily use ddl dml dcl dql
SQL command for daily use ddl dml dcl dql
kashyapdaksh29
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
ami111
 
Optimizing MySQL Queries
Optimizing MySQL QueriesOptimizing MySQL Queries
Optimizing MySQL Queries
Achievers Tech
 
Ch-2-Query-Process.pptx advanced database
Ch-2-Query-Process.pptx advanced databaseCh-2-Query-Process.pptx advanced database
Ch-2-Query-Process.pptx advanced database
tasheebedane
 
Ad

Recently uploaded (20)

Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 

Sub query_SQL

  • 1. SQL SubQuery 1 ICT Level V COT - Jaffna S.Sakthybaalan
  • 2. 2 What Is a Subquery?  A subquery is a SELECT statement embedded in a clause of another SQL statement (SELECT, INSERT, UPDATE, DELETE). SELECT . . . FROM . . . WHERE . . . (SELECT . . . FROM . . . WHERE . . .) Main Query Subquery SQL subquery is usually added in the WHERE Clause of the SQL statement.
  • 3. 3 The basic concept is to pass a single value 4 3 2 1 When reading or writing SQL subqueries, you should start from the bottom upwards, working out which data is to be passed to the next query up.
  • 4. 4 SQL Subquery  Subquery or Inner query or Nested query.  An alternate way of returning data from multiple tables.  Subqueries can be used with the following SQL statements along with the comparision operators like =, <, >, >=, <= etc.  Subqueries can also be used inside the WHERE or HAVING clause.
  • 5. 5 Sub-query Syntax • The subquery (inner query) executes once before the main query. • The result of the subquery is used by the main query (outer query).
  • 6. 6 Using a Subquery to Solve a Problem  To solve this problem, you need two queries: one to find what Abel earns, and a second query to find who earns more than that amount.  You can solve this problem by combining the two queries, placing one query inside the other query.  The inner query or the subquery returns a value that is used by the outer query or the main query.  Using a subquery is equivalent to performing two sequential queries and using the result of the first query as the search value in the second query.
  • 7. 7 Example :  In the slide, the inner query determines the salary of employee Abel.  The outer query takes the result of the inner query and uses this result to display all the employees who earn more than this amount.  Execute the subquery (inner query) on its own first to show the value that the subquery returns.  Then execute the outer query using the result returned by the inner query. Finally, execute the entire query (containing the subquery), and show that the result is the same.
  • 8. 8 Types of SubQueries SubQueries Single-row subqueries Multiple-row subqueries
  • 9. 9 Types of Subqueries  Single-row subqueries: Queries that return only one row from the inner SELECT statement  Multiple-row subqueries: Queries that return more than one row from the inner SELECT statement
  • 10. 10 Single-Row Subqueries  Return only one row  Use single-row comparison operators
  • 11. 11 Executing Single-Row Subqueries  A SELECT statement can be considered as a query block.  The example on the slide displays employees whose job ID is the same as that of employee 141 and whose salary is greater than that of employee 143.  The example consists of three query blocks: the outer query and two inner queries.  The inner query blocks are executed first, producing the query results ST_CLERK and 2600, respectively.  The outer query block is then processed and uses the values returned by the inner queries to complete its search conditions.
  • 12. 12 Problems with Subqueries  A common problem with subqueries is no rows being returned by the inner query.  There is no employee named Haas. So the subquery returns no rows.
  • 13. 13 Multiple-Row Subqueries  Subqueries that return more than one row are called multiple-row subqueries.  You use a multiple-row operator, instead of a single- row operator, with a multiple-row subquery.  The multiple-row operator expects one or more values.
  • 14. 14 Example : The NOT operator can be used with IN, ANY, and ALL operators.
  • 15. 15 Exercise 1 : Track cID Num Title Time aID 1 1 Violent 239 1 1 2 Every Girl 410 1 1 3 Breather 217 1 1 4 Part of Me 279 1 2 1 Star 362 1 2 2 Teaboy 417 2 CD cID Title Price 1 Mix 9.99 2 Compilation 12.99 Artist aID Name 1 Stellar 2 Cloudboy • Find a list of all the CD titles. • Find a list of the titles of tracks that are more than 300 seconds long. • Find a list of the names of those artists who have a track on the CD with the title “Compilation”.
  • 16. 16 LOCATION Location_ID Regional_Group 122 NEW YORK 123 DALLAS 124 CHICAGO 167 BOSTON DEPARTMENT Department_ID Name Location_ID 10 ACCOUNTING 122 20 RESEARCH 124 30 SALES 123 40 OPERATIONS 167 JOB Job_ID Function 667 CLERK 668 STAFF 669 ANALYST 670 SALESPERSON 671 MANAGER 672 PRESIDENT EMPLOYEE EMPLOYEE _ID LAST_NAME FIRST_NAME MIDDLE_ NAME JOB_ID MANAGER _ID HIREDATE SALARY COMM DEPARTME NT_ID 7369 SMITH JOHN Q 667 7902 17-DEC-84 800 NULL 20 7499 ALLEN KEVIN J 670 7698 20-FEB-85 1600 300 30 7505 DOYLE JEAN K 671 7839 04-APR-85 2850 NULL 30 7506 DENNIS LYNN S 671 7839 15-MAY-85 2750 NULL 30 7507 BAKER LESLIE D 671 7839 10-JUN-85 2200 NULL 40 7521 WARK CYNTHIA D 670 7698 22-FEB-85 1250 500 30 Exercise 2 :
  • 17. 17 1. Display the employee who got the maximum salary. SELECT * FROM employee WHERE salary =(SELECT MAX(salary) FROM employee) 2. Find out no.of employees working in “Sales” department. SELECT * FROM employee WHERE department_id =(SELECT department_id FROM department WHERE name=’SALES’ GROUP BY department_id) Sub-Queries
  • 18. 18 3. Delete the employees who are working in accounting department. DELETE FROM employee WHERE department_id =(SELECT department_id FROM department WHERE name=’ACCOUNTING’) 4. Display the second highest salary drawing employee details. SELECT * FROM employee WHERE salary =( SELECT MAX(salary) FROM employee WHERE salary <(SELECT MAX(salary) FROM employee))
  • 20. 20
  翻译: