SlideShare a Scribd company logo
1 of 21
SQL
Ahmed Farag
Information Systems Dept.
Faculty of Computers and Information
Menoufia University, Egypt.
Review
• Install MySQL, Work Bench
• Load sample Data to DB
• Select
• DISTINCT,
• WHERE, Not IN, IN, AND, OR, BETWEEN, Like, Is
null, Is Not Null, Alias
• Limit, Order by
• Sub Queries
• Trim function
Review
• MySQL single row functions (INSTR, CONCAT,
CONCAT_WS, FIND_IN_SET, Round, Truncate,
MOD, IFNULL, Format).
• MySQL multi row functions (AVG, Count, Sum,
MIN, MAX, ).
• Group by
• Having
• Join (Inner, left, right, cross, self), ON, Using
MySQL UNION
MySQL
UNION
operator
• MySQL UNION operator allows you to combine two or more
result sets of queries into a single result set.
• The following illustrates the syntax of the UNION operator:
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
...
• To combine result set of two or more queries using the UNION
operator, there are the basic rules that you must follow:
• First, the number and the orders of columns that appear
in all SELECT statements must be the same.
• Second, the data types of columns must be the same or
convertible.
• By default, the UNION operator removes duplicate rows even
if you don’t specify the DISTINCT operator explicitly.
MySQL
UNION
operator
• The following statement combines result sets returned from
t1 and t2 tables:
SELECT id
FROM t1
UNION
SELECT id
FROM t2;
ID
1
2
3
ID
2
3
4
t1 t2
Output
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
+----+
4 rows in set (0.00 sec)
Because the rows with value 2 and 3
are duplicates, the UNION operator
removed it and kept only distinct ones.
MySQL
UNION
ALL
operator
• The following statement combines result sets returned from
t1 and t2 tables: Using UNION ALL
SELECT id
FROM t1
UNION ALL
SELECT id
FROM t2;
ID
1
2
3
ID
2
3
4
t1 t2
If you use the UNION ALL explicitly, the
duplicate rows, if available, remain in the
result. Because UNION ALL does not need to
handle duplicates.
Output
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 2 |
| 3 |
| 4 |
+----+
6 rows in set (0.00 sec)
MySQL
UNION
operator
• Suppose you want to combine the first name and last name of
both employees and customers into a single result set, you
can use the UNION operator as follows:
SELECT
firstName,
lastName
FROM
employees
UNION
SELECT
contactFirstName,
contactLastName
FROM
customers;
MySQL
UNION
operator
• Suppose you want to combine the first name and last name of
both employees and customers into a single result set, you
can use the UNION operator as follows:
SELECT
firstName,
lastName
FROM
employees
UNION
SELECT
contactFirstName,
contactLastName
FROM
customers;
• As you can see, the MySQL UNION operator uses the column
names of the first SELECT statement for labeling the columns
in the output.
MySQL
UNION
operator
• If you want to use your own column aliases, you need to
specify them explicitly in the first SELECT statement as shown
in the following example:
SELECT
concat(firstName,' ',lastName) fullname
FROM
employees
UNION SELECT
concat(contactFirstName,' ',contactLastName)
FROM
customers;
MySQL
UNION
operator
• If you want to sort the result of a union, you use an ORDER
BY clause in the last SELECT statement as shown in the
following example:
• Notice that if you place the ORDER BY clause in each SELECT
statement, it will not affect the order of the rows in the final
result set.
SELECT
concat(firstName,' ',lastName) fullname
FROM
employees
UNION SELECT
concat(contactFirstName,' ',contactLastName)
FROM
customers
ORDER BY fullname;
MySQL MINUS
MySQL
MINUS
operator
• MINUS compares results of two queries and returns distinct
rows from the first query that aren’t output by the second
query.
• The following illustrates the syntax of the MINUS operator:
• The basic rules for a query that uses MINUS operator are the
following:
• The number and order of columns in both column_list_1
and column_list_2 must be the same.
• The data types of the corresponding columns in both
queries must be compatible.
SELECT column_list_1 FROM table_1
MINUS
SELECT columns_list_2 FROM table_2;
MySQL
MINUS
operator
• The following statement combines result sets returned from
t1 and t2 tables:
ID
1
2
3
ID
2
3
4
t1 t2
Output
+----+
| id |
+----+
| 1 |
+----+
1 rows in set (0.00 sec)
SELECT id FROM
t1
MINUS
SELECT id FROM
t2;
MySQL
MINUS
operator
• Unfortunately, MySQL does not support MINUS operator.
However, you can use the MySQL join or Subquery to simulate
it.
• To emulate the MINUS of two queries, you use the following
syntax:
SELECT
column_list
FROM
table_1
LEFT JOIN table_2 ON join_predicate
WHERE
table_2.id IS NULL;
OR
SELECT a.id
FROM table_1 as a
WHERE <Condition>
AND a.id NOT IN (SELECT b.id from table_2 as b where
<Condition>)
MySQL
MINUS
operator
• For example, the following query uses the LEFT JOIN clause to
return the same result as the MINUS operator:
SELECT
id
FROM
t1
LEFT JOIN
t2 USING (id)
WHERE
t2.id IS NULL;
MySQL INTERSECT
MySQL
INTERSECT
operator
• The INTERSECT operator is a set operator that returns only
distinct rows of two queries or more queries.
• The following illustrates the syntax of the INTERSECT operator.
• To use the INTERSECT operator for two queries, the following
rules are applied:
• The order and the number of columns must be the same.
• The data types of the corresponding columns must be
compatible.
(SELECT column_list
FROM table_1)
INTERSECT
(SELECT column_list
FROM table_2);
MySQL
INTERSECT
operator
• The following statement returns the distinct rows of both
result sets which include (2,3).
ID
1
2
3
ID
2
3
4
t1 t2
Output
+----+
| id |
+----+
| 2 |
| 3 |
+----+
2 rows in set (0.00 sec)
SELECT id FROM
t1
INTERSECT
SELECT id FROM
t2;
Unlike the UNION operator,
the INTERSECT operator returns
the intersection between two circles.
MySQL
MINUS
operator
• Unfortunately, MySQL does not support the INTERSECT
operator. However, you can simulate the INTERSECT operator.
• The following statement uses DISTINCT operator and INNER
JOIN clause to return the distinct rows in both tables:
SELECT DISTINCT
id
FROM t1
INNER JOIN t2 USING(id);
Output
id
----
2
3
How it works.
• The INNER JOIN clause returns rows
from both left and right tables.
• The DISTINCT operator removes the
duplicate rows.
MySQL
MINUS
operator
• The following statement uses the IN operator and a subquery
to return the intersection of the two result sets.
Output
id
----
2
3
How it works.
• The subquery returns the first result set.
• The outer query uses the IN operator to
select only values that are in the first
result set. The DISTINCT operator
ensures that only distinct values are
selected.
SELECT DISTINCT
id
FROM
t1
WHERE
id IN (SELECT
id
FROM
t2);

More Related Content

What's hot

What's hot (20)

Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
1.2 sql create and drop table
1.2 sql create and drop table1.2 sql create and drop table
1.2 sql create and drop table
 
Sql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.pptSql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.ppt
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3
 
SQL
SQLSQL
SQL
 
Mysql
MysqlMysql
Mysql
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan Pasricha
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
SQL UNION
SQL UNIONSQL UNION
SQL UNION
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
 
Sql views
Sql viewsSql views
Sql views
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
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
 
Sql joins
Sql joinsSql joins
Sql joins
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
SQL practice questions set - 2
SQL practice questions set - 2SQL practice questions set - 2
SQL practice questions set - 2
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query Optimization
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational Schema
 

Similar to SQL Review of MySQL Operators UNION, MINUS, INTERSECT

MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index TuningManikanda kumar
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive dataAmrit Kaur
 
MySQL Query tuning 101
MySQL Query tuning 101MySQL Query tuning 101
MySQL Query tuning 101Sveta Smirnova
 
IBM Informix Database SQL Set operators and ANSI Hash Join
IBM Informix Database SQL Set operators and ANSI Hash JoinIBM Informix Database SQL Set operators and ANSI Hash Join
IBM Informix Database SQL Set operators and ANSI Hash JoinAjay Gupte
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfTamiratDejene1
 
database_set_operations_&_function.pptx
database_set_operations_&_function.pptxdatabase_set_operations_&_function.pptx
database_set_operations_&_function.pptxtanvirkhanfahim
 
Introduction into MySQL Query Tuning
Introduction into MySQL Query TuningIntroduction into MySQL Query Tuning
Introduction into MySQL Query TuningSveta Smirnova
 
MYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-havingMYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-havingAhmed Farag
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)Dave Stokes
 
Optimizer in oracle 11g by wwf from ebay COC
Optimizer in oracle 11g by wwf from ebay COCOptimizer in oracle 11g by wwf from ebay COC
Optimizer in oracle 11g by wwf from ebay COCLouis liu
 
4. Data Manipulation.ppt
4. Data Manipulation.ppt4. Data Manipulation.ppt
4. Data Manipulation.pptKISHOYIANKISH
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL FundamentalsBrian Foote
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptxEllenGracePorras
 

Similar to SQL Review of MySQL Operators UNION, MINUS, INTERSECT (20)

set operators.pptx
set operators.pptxset operators.pptx
set operators.pptx
 
Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
MYSQL join
MYSQL joinMYSQL join
MYSQL join
 
ADV PPT 8 LAB.pptx
ADV PPT 8 LAB.pptxADV PPT 8 LAB.pptx
ADV PPT 8 LAB.pptx
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
MySQL Query tuning 101
MySQL Query tuning 101MySQL Query tuning 101
MySQL Query tuning 101
 
MySQL performance tuning
MySQL performance tuningMySQL performance tuning
MySQL performance tuning
 
IBM Informix Database SQL Set operators and ANSI Hash Join
IBM Informix Database SQL Set operators and ANSI Hash JoinIBM Informix Database SQL Set operators and ANSI Hash Join
IBM Informix Database SQL Set operators and ANSI Hash Join
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
 
database_set_operations_&_function.pptx
database_set_operations_&_function.pptxdatabase_set_operations_&_function.pptx
database_set_operations_&_function.pptx
 
Introduction into MySQL Query Tuning
Introduction into MySQL Query TuningIntroduction into MySQL Query Tuning
Introduction into MySQL Query Tuning
 
MYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-havingMYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-having
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
 
Optimizer in oracle 11g by wwf from ebay COC
Optimizer in oracle 11g by wwf from ebay COCOptimizer in oracle 11g by wwf from ebay COC
Optimizer in oracle 11g by wwf from ebay COC
 
4. Data Manipulation.ppt
4. Data Manipulation.ppt4. Data Manipulation.ppt
4. Data Manipulation.ppt
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
Introduction to mysql part 2
Introduction to mysql part 2Introduction to mysql part 2
Introduction to mysql part 2
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
 

More from Ahmed Farag

Sql modifying data - MYSQL part I
Sql modifying data - MYSQL part ISql modifying data - MYSQL part I
Sql modifying data - MYSQL part IAhmed Farag
 
Introduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBIntroduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBAhmed Farag
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP conceptsAhmed Farag
 
Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Ahmed Farag
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++Ahmed Farag
 

More from Ahmed Farag (12)

Intro to php
Intro to phpIntro to php
Intro to php
 
MYSql manage db
MYSql manage dbMYSql manage db
MYSql manage db
 
Normalization
NormalizationNormalization
Normalization
 
Sql modifying data - MYSQL part I
Sql modifying data - MYSQL part ISql modifying data - MYSQL part I
Sql modifying data - MYSQL part I
 
Introduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBIntroduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDB
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 
Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
OOP C++
OOP C++OOP C++
OOP C++
 
Functions C++
Functions C++Functions C++
Functions C++
 
intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++
 
Intro to C++
Intro to C++Intro to C++
Intro to C++
 

Recently uploaded

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Recently uploaded (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

SQL Review of MySQL Operators UNION, MINUS, INTERSECT

  • 1. SQL Ahmed Farag Information Systems Dept. Faculty of Computers and Information Menoufia University, Egypt.
  • 2. Review • Install MySQL, Work Bench • Load sample Data to DB • Select • DISTINCT, • WHERE, Not IN, IN, AND, OR, BETWEEN, Like, Is null, Is Not Null, Alias • Limit, Order by • Sub Queries • Trim function
  • 3. Review • MySQL single row functions (INSTR, CONCAT, CONCAT_WS, FIND_IN_SET, Round, Truncate, MOD, IFNULL, Format). • MySQL multi row functions (AVG, Count, Sum, MIN, MAX, ). • Group by • Having • Join (Inner, left, right, cross, self), ON, Using
  • 5. MySQL UNION operator • MySQL UNION operator allows you to combine two or more result sets of queries into a single result set. • The following illustrates the syntax of the UNION operator: SELECT column_list UNION [DISTINCT | ALL] SELECT column_list UNION [DISTINCT | ALL] SELECT column_list ... • To combine result set of two or more queries using the UNION operator, there are the basic rules that you must follow: • First, the number and the orders of columns that appear in all SELECT statements must be the same. • Second, the data types of columns must be the same or convertible. • By default, the UNION operator removes duplicate rows even if you don’t specify the DISTINCT operator explicitly.
  • 6. MySQL UNION operator • The following statement combines result sets returned from t1 and t2 tables: SELECT id FROM t1 UNION SELECT id FROM t2; ID 1 2 3 ID 2 3 4 t1 t2 Output +----+ | id | +----+ | 1 | | 2 | | 3 | | 4 | +----+ 4 rows in set (0.00 sec) Because the rows with value 2 and 3 are duplicates, the UNION operator removed it and kept only distinct ones.
  • 7. MySQL UNION ALL operator • The following statement combines result sets returned from t1 and t2 tables: Using UNION ALL SELECT id FROM t1 UNION ALL SELECT id FROM t2; ID 1 2 3 ID 2 3 4 t1 t2 If you use the UNION ALL explicitly, the duplicate rows, if available, remain in the result. Because UNION ALL does not need to handle duplicates. Output +----+ | id | +----+ | 1 | | 2 | | 3 | | 2 | | 3 | | 4 | +----+ 6 rows in set (0.00 sec)
  • 8. MySQL UNION operator • Suppose you want to combine the first name and last name of both employees and customers into a single result set, you can use the UNION operator as follows: SELECT firstName, lastName FROM employees UNION SELECT contactFirstName, contactLastName FROM customers;
  • 9. MySQL UNION operator • Suppose you want to combine the first name and last name of both employees and customers into a single result set, you can use the UNION operator as follows: SELECT firstName, lastName FROM employees UNION SELECT contactFirstName, contactLastName FROM customers; • As you can see, the MySQL UNION operator uses the column names of the first SELECT statement for labeling the columns in the output.
  • 10. MySQL UNION operator • If you want to use your own column aliases, you need to specify them explicitly in the first SELECT statement as shown in the following example: SELECT concat(firstName,' ',lastName) fullname FROM employees UNION SELECT concat(contactFirstName,' ',contactLastName) FROM customers;
  • 11. MySQL UNION operator • If you want to sort the result of a union, you use an ORDER BY clause in the last SELECT statement as shown in the following example: • Notice that if you place the ORDER BY clause in each SELECT statement, it will not affect the order of the rows in the final result set. SELECT concat(firstName,' ',lastName) fullname FROM employees UNION SELECT concat(contactFirstName,' ',contactLastName) FROM customers ORDER BY fullname;
  • 13. MySQL MINUS operator • MINUS compares results of two queries and returns distinct rows from the first query that aren’t output by the second query. • The following illustrates the syntax of the MINUS operator: • The basic rules for a query that uses MINUS operator are the following: • The number and order of columns in both column_list_1 and column_list_2 must be the same. • The data types of the corresponding columns in both queries must be compatible. SELECT column_list_1 FROM table_1 MINUS SELECT columns_list_2 FROM table_2;
  • 14. MySQL MINUS operator • The following statement combines result sets returned from t1 and t2 tables: ID 1 2 3 ID 2 3 4 t1 t2 Output +----+ | id | +----+ | 1 | +----+ 1 rows in set (0.00 sec) SELECT id FROM t1 MINUS SELECT id FROM t2;
  • 15. MySQL MINUS operator • Unfortunately, MySQL does not support MINUS operator. However, you can use the MySQL join or Subquery to simulate it. • To emulate the MINUS of two queries, you use the following syntax: SELECT column_list FROM table_1 LEFT JOIN table_2 ON join_predicate WHERE table_2.id IS NULL; OR SELECT a.id FROM table_1 as a WHERE <Condition> AND a.id NOT IN (SELECT b.id from table_2 as b where <Condition>)
  • 16. MySQL MINUS operator • For example, the following query uses the LEFT JOIN clause to return the same result as the MINUS operator: SELECT id FROM t1 LEFT JOIN t2 USING (id) WHERE t2.id IS NULL;
  • 18. MySQL INTERSECT operator • The INTERSECT operator is a set operator that returns only distinct rows of two queries or more queries. • The following illustrates the syntax of the INTERSECT operator. • To use the INTERSECT operator for two queries, the following rules are applied: • The order and the number of columns must be the same. • The data types of the corresponding columns must be compatible. (SELECT column_list FROM table_1) INTERSECT (SELECT column_list FROM table_2);
  • 19. MySQL INTERSECT operator • The following statement returns the distinct rows of both result sets which include (2,3). ID 1 2 3 ID 2 3 4 t1 t2 Output +----+ | id | +----+ | 2 | | 3 | +----+ 2 rows in set (0.00 sec) SELECT id FROM t1 INTERSECT SELECT id FROM t2; Unlike the UNION operator, the INTERSECT operator returns the intersection between two circles.
  • 20. MySQL MINUS operator • Unfortunately, MySQL does not support the INTERSECT operator. However, you can simulate the INTERSECT operator. • The following statement uses DISTINCT operator and INNER JOIN clause to return the distinct rows in both tables: SELECT DISTINCT id FROM t1 INNER JOIN t2 USING(id); Output id ---- 2 3 How it works. • The INNER JOIN clause returns rows from both left and right tables. • The DISTINCT operator removes the duplicate rows.
  • 21. MySQL MINUS operator • The following statement uses the IN operator and a subquery to return the intersection of the two result sets. Output id ---- 2 3 How it works. • The subquery returns the first result set. • The outer query uses the IN operator to select only values that are in the first result set. The DISTINCT operator ensures that only distinct values are selected. SELECT DISTINCT id FROM t1 WHERE id IN (SELECT id FROM t2);