SlideShare une entreprise Scribd logo
1  sur  18
Click to add Title
e-Infochips Institute of Training Research and Academics Limited
Subquery example with
Advantages and Disadvantages
Prepared by:
Arpita vyas
Shuchi Shah
Sarfaraz Ghanta
SubQuery
 A Subquery or Inner query or Nested query is a query within another SQL query
and embedded within the WHERE clause.
 A subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.
 Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
1. Subqueries must be enclosed within parentheses.
2. An ORDER BY cannot be used in a subquery, although the main query can
use an ORDER BY. The GROUP BY can be used to perform the same
function as the ORDER BY in a subquery.
3. Subqueries that return more than one row can only be used with multiple
value operators, such as the IN operator.
For EX:
SELECT "column_name1“ FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"FROM "table_name2“ WHERE "condition");
Rules for SubQuery
Subqueries with the SELECT Statement:
• Subqueries are most frequently used with the SELECT statement.
The basic syntax is as follows:
SELECT column_name [, column_name ]
FROM table1 [, table2 ] WHERE column_name
OPERATOR (SELECT column_name [, column_name ]
FROM table1 [, table2 ] [WHERE])
Sample Example
• Consider the CUSTOMERS table having the following records:
| ID | NAME | AGE | ADDRESS | SALARY |
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
ID NAME AGE ADDRESS SALARY
1 Ramesh 35 Ahmedabad 2000
2 Khilan 25 Delhi 1500
3 kaushik 23 Kota 2000
4 Chaitali 25 Mumbai 6500
5 Hardik 27 Bopal 8500
6 Komal 22 MP 4500
7 Muffy 24 Indore 10000
Sample Example
• Now, let us check following subquery with SELECT statement:
SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID
FROM CUSTOMERS WHERE SALARY > 4500) ;
Sample Example
ID NAME AGE ADDRESS SALARY
4 Chaitali 25 Mumbai 6500
5 Hardik 27 Bopal 8500
7 Muffy 24 Indore 10000
Result
Subqueries with the INSERT Statement:
• The INSERT statement uses the data returned from the subquery to insert
into another table.
• The selected data in the subquery can be modified with any of the character,
date or number functions.
The basic syntax is as follows:
INSERT INTO table_name [ (column1 [, column2])]
SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Sample Example
• Consider a table CUSTOMERS_BKP with similar structure as
CUSTOMERS table.
• Now to copy complete CUSTOMERS table into CUSTOMERS_BKP,
following is the syntax:
INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS WHERE ID
IN (SELECT ID FROM CUSTOMERS) ;
Subqueries with the UPDATE Statement:
• The subquery can be used in conjunction with the UPDATE statement.
• Either single or multiple columns in a table can be updated when using a
subquery with the UPDATE statement.
The basic syntax is as follows:
UPDATE table SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]
Sample Example
• Assuming, we have CUSTOMERS_BKP table available which is backup
of CUSTOMERS table.
• Following example updates SALARY by 0.25 times in CUSTOMERS table
for all the customers whose AGE is greater than or equal to 27:
SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM
CUSTOMERS_BKP WHERE AGE >= 27 );
Sample Example
• This would impact two rows and finally CUSTOMERS table would have
the following records:
| ID | NAME | AGE | ADDRESS | SALARY |
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
ID NAME AGE ADDRESS SALARY
1 Ramesh 35 Ahmedabad 125
2 Khilan 25 Delhi 1500
3 kaushik 23 Kota 2000
4 Chaitali 25 Mumbai 6500
5 Hardik 27 Bopal 2125
6 Komal 22 MP 4500
7 Muffy 24 Indore 10000
Subqueries with the DELETE Statement:
• The subquery can be used in conjunction with the DELETE statement like
with any other statements mentioned above.
The basic syntax is as follows:
DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]
Sample Example
• Assuming, we have CUSTOMERS_BKP table available which is backup
of CUSTOMERS table.
• Following example deletes records from CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27:
DELETE FROM CUSTOMERS WHERE AGE IN
(SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );
Sample Example
• This would impact two rows and finally CUSTOMERS table would have
the following records:
| ID | NAME | AGE | ADDRESS | SALARY |
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
ID NAME AGE ADDRESS SALARY
2 Khilan 25 Delhi 1500
3 kaushik 23 Kota 2000
4 Chaitali 25 Mumbai 6500
6 Komal 22 MP 4500
7 Muffy 24 Indore 10000
Advantages
 Subqueries structure a complex query into isolated parts so that a complex
query can be broken down into a series of logical steps.
 It is broken down into steps for easy understanding and code maintenance.
 Subqueries allow you to use the results of another query in the outer query.
 In some cases, subqueries can replace complex joins and unions and
subqueries are easier to understand.
Disadvantages
 When subquery is used, the database server (actually the query optimizer)
may need to perform additional steps, such as sorting, before the results from
the subquery are used
 Subqueries also can take longer to execute than a join because of how the
database optimizer processes them.
 The optimizer is more mature for MySQL for joins than for subqueries, so in
many cases a statement that uses a subquery can be executed more efficiently
if you rewrite it as a join.
Sub query example with advantage and disadvantages

Contenu connexe

Tendances

Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries LectureFelipe Costa
 
Nested queries in database
Nested queries in databaseNested queries in database
Nested queries in databaseSatya P. Joshi
 
[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 SQLEDB
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performancejkeriaki
 
Sql joins inner join self join outer joins
Sql joins inner join self join outer joinsSql joins inner join self join outer joins
Sql joins inner join self join outer joinsDeepthi Rachumallu
 
Bottom - Up Parsing
Bottom - Up ParsingBottom - Up Parsing
Bottom - Up Parsingkunj desai
 
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 Serverprogrammings guru
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursionAbdullah Al-hazmy
 
Symbol table management and error handling in compiler design
Symbol table management and error handling in compiler designSymbol table management and error handling in compiler design
Symbol table management and error handling in compiler designSwati Chauhan
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexingMahabubur Rahaman
 

Tendances (20)

Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
Nested queries in database
Nested queries in databaseNested queries in database
Nested queries in database
 
Operator precedence
Operator precedenceOperator precedence
Operator precedence
 
SQL Join Basic
SQL Join BasicSQL Join Basic
SQL Join Basic
 
[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
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
 
Hash table
Hash tableHash table
Hash table
 
Sql joins inner join self join outer joins
Sql joins inner join self join outer joinsSql joins inner join self join outer joins
Sql joins inner join self join outer joins
 
Sequences and indexes
Sequences and indexesSequences and indexes
Sequences and indexes
 
Bottom - Up Parsing
Bottom - Up ParsingBottom - Up Parsing
Bottom - Up Parsing
 
Mysql joins
Mysql joinsMysql joins
Mysql joins
 
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
 
joins in database
 joins in database joins in database
joins in database
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Sql views
Sql viewsSql views
Sql views
 
Symbol table management and error handling in compiler design
Symbol table management and error handling in compiler designSymbol table management and error handling in compiler design
Symbol table management and error handling in compiler design
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
 
Rehashing
RehashingRehashing
Rehashing
 
Joins in dbms and types
Joins in dbms and typesJoins in dbms and types
Joins in dbms and types
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 

Similaire à Sub query example with advantage and disadvantages

Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)Zohar Elkayam
 
Database Akjljljlkjlkjkljlkjldiministration.pptx
Database Akjljljlkjlkjkljlkjldiministration.pptxDatabase Akjljljlkjlkjkljlkjldiministration.pptx
Database Akjljljlkjlkjkljlkjldiministration.pptxEliasPetros
 
ADVANCED SQL FUNCTONS (1).pptx
ADVANCED SQL FUNCTONS (1).pptxADVANCED SQL FUNCTONS (1).pptx
ADVANCED SQL FUNCTONS (1).pptxshaikanjum16
 
Oracle Database Advanced Querying
Oracle Database Advanced QueryingOracle Database Advanced Querying
Oracle Database Advanced QueryingZohar Elkayam
 
Empowering Users with Analytical MDX
Empowering Users with Analytical MDXEmpowering Users with Analytical MDX
Empowering Users with Analytical MDXAlithya
 
OOW2016: Exploring Advanced SQL Techniques Using Analytic Functions
OOW2016: Exploring Advanced SQL Techniques Using Analytic FunctionsOOW2016: Exploring Advanced SQL Techniques Using Analytic Functions
OOW2016: Exploring Advanced SQL Techniques Using Analytic FunctionsZohar Elkayam
 
Creating other schema objects
Creating other schema objectsCreating other schema objects
Creating other schema objectsSyed Zaid Irshad
 
The art of querying – newest and advanced SQL techniques
The art of querying – newest and advanced SQL techniquesThe art of querying – newest and advanced SQL techniques
The art of querying – newest and advanced SQL techniquesZohar Elkayam
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL IISankhya_Analytics
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Vidyasagar Mundroy
 
data manipulation language
data manipulation languagedata manipulation language
data manipulation languageJananiSelvaraj10
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan PasrichaMananPasricha
 

Similaire à Sub query example with advantage and disadvantages (20)

Sql operator
Sql operatorSql operator
Sql operator
 
Dbms
DbmsDbms
Dbms
 
Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)
 
Database Akjljljlkjlkjkljlkjldiministration.pptx
Database Akjljljlkjlkjkljlkjldiministration.pptxDatabase Akjljljlkjlkjkljlkjldiministration.pptx
Database Akjljljlkjlkjkljlkjldiministration.pptx
 
ADVANCED SQL FUNCTONS (1).pptx
ADVANCED SQL FUNCTONS (1).pptxADVANCED SQL FUNCTONS (1).pptx
ADVANCED SQL FUNCTONS (1).pptx
 
Oracle Database Advanced Querying
Oracle Database Advanced QueryingOracle Database Advanced Querying
Oracle Database Advanced Querying
 
Empowering Users with Analytical MDX
Empowering Users with Analytical MDXEmpowering Users with Analytical MDX
Empowering Users with Analytical MDX
 
OOW2016: Exploring Advanced SQL Techniques Using Analytic Functions
OOW2016: Exploring Advanced SQL Techniques Using Analytic FunctionsOOW2016: Exploring Advanced SQL Techniques Using Analytic Functions
OOW2016: Exploring Advanced SQL Techniques Using Analytic Functions
 
SQL Notes
SQL NotesSQL Notes
SQL Notes
 
Access2013 ch10
Access2013 ch10Access2013 ch10
Access2013 ch10
 
Creating other schema objects
Creating other schema objectsCreating other schema objects
Creating other schema objects
 
The art of querying – newest and advanced SQL techniques
The art of querying – newest and advanced SQL techniquesThe art of querying – newest and advanced SQL techniques
The art of querying – newest and advanced SQL techniques
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
01 basic orders
01   basic orders01   basic orders
01 basic orders
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
data manipulation language
data manipulation languagedata manipulation language
data manipulation language
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan Pasricha
 
Subquery.pptx
Subquery.pptxSubquery.pptx
Subquery.pptx
 

Dernier

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 

Dernier (20)

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 

Sub query example with advantage and disadvantages

  • 1. Click to add Title e-Infochips Institute of Training Research and Academics Limited Subquery example with Advantages and Disadvantages Prepared by: Arpita vyas Shuchi Shah Sarfaraz Ghanta
  • 2. SubQuery  A Subquery or Inner query or Nested query is a query within another SQL query and embedded within the WHERE clause.  A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.  Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
  • 3. There are a few rules that subqueries must follow: 1. Subqueries must be enclosed within parentheses. 2. An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery. 3. Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator. For EX: SELECT "column_name1“ FROM "table_name1" WHERE "column_name2" [Comparison Operator] (SELECT "column_name3"FROM "table_name2“ WHERE "condition"); Rules for SubQuery
  • 4. Subqueries with the SELECT Statement: • Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows: SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name OPERATOR (SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE])
  • 5. Sample Example • Consider the CUSTOMERS table having the following records: | ID | NAME | AGE | ADDRESS | SALARY | | 1 | Ramesh | 35 | Ahmedabad | 125.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 2125.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | ID NAME AGE ADDRESS SALARY 1 Ramesh 35 Ahmedabad 2000 2 Khilan 25 Delhi 1500 3 kaushik 23 Kota 2000 4 Chaitali 25 Mumbai 6500 5 Hardik 27 Bopal 8500 6 Komal 22 MP 4500 7 Muffy 24 Indore 10000
  • 6. Sample Example • Now, let us check following subquery with SELECT statement: SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) ;
  • 7. Sample Example ID NAME AGE ADDRESS SALARY 4 Chaitali 25 Mumbai 6500 5 Hardik 27 Bopal 8500 7 Muffy 24 Indore 10000 Result
  • 8. Subqueries with the INSERT Statement: • The INSERT statement uses the data returned from the subquery to insert into another table. • The selected data in the subquery can be modified with any of the character, date or number functions. The basic syntax is as follows: INSERT INTO table_name [ (column1 [, column2])] SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ]
  • 9. Sample Example • Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. • Now to copy complete CUSTOMERS table into CUSTOMERS_BKP, following is the syntax: INSERT INTO CUSTOMERS_BKP SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS) ;
  • 10. Subqueries with the UPDATE Statement: • The subquery can be used in conjunction with the UPDATE statement. • Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement. The basic syntax is as follows: UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]
  • 11. Sample Example • Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. • Following example updates SALARY by 0.25 times in CUSTOMERS table for all the customers whose AGE is greater than or equal to 27: SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );
  • 12. Sample Example • This would impact two rows and finally CUSTOMERS table would have the following records: | ID | NAME | AGE | ADDRESS | SALARY | | 1 | Ramesh | 35 | Ahmedabad | 125.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 2125.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | ID NAME AGE ADDRESS SALARY 1 Ramesh 35 Ahmedabad 125 2 Khilan 25 Delhi 1500 3 kaushik 23 Kota 2000 4 Chaitali 25 Mumbai 6500 5 Hardik 27 Bopal 2125 6 Komal 22 MP 4500 7 Muffy 24 Indore 10000
  • 13. Subqueries with the DELETE Statement: • The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above. The basic syntax is as follows: DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]
  • 14. Sample Example • Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. • Following example deletes records from CUSTOMERS table for all the customers whose AGE is greater than or equal to 27: DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );
  • 15. Sample Example • This would impact two rows and finally CUSTOMERS table would have the following records: | ID | NAME | AGE | ADDRESS | SALARY | | 1 | Ramesh | 35 | Ahmedabad | 125.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 2125.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | ID NAME AGE ADDRESS SALARY 2 Khilan 25 Delhi 1500 3 kaushik 23 Kota 2000 4 Chaitali 25 Mumbai 6500 6 Komal 22 MP 4500 7 Muffy 24 Indore 10000
  • 16. Advantages  Subqueries structure a complex query into isolated parts so that a complex query can be broken down into a series of logical steps.  It is broken down into steps for easy understanding and code maintenance.  Subqueries allow you to use the results of another query in the outer query.  In some cases, subqueries can replace complex joins and unions and subqueries are easier to understand.
  • 17. Disadvantages  When subquery is used, the database server (actually the query optimizer) may need to perform additional steps, such as sorting, before the results from the subquery are used  Subqueries also can take longer to execute than a join because of how the database optimizer processes them.  The optimizer is more mature for MySQL for joins than for subqueries, so in many cases a statement that uses a subquery can be executed more efficiently if you rewrite it as a join.