SlideShare a Scribd company logo
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 (20)

Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
FP304 DATABASE SYSTEM PAPER FINAL EXAM AGAIN
FP304 DATABASE SYSTEM  PAPER FINAL EXAM AGAINFP304 DATABASE SYSTEM  PAPER FINAL EXAM AGAIN
FP304 DATABASE SYSTEM PAPER FINAL EXAM AGAIN
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
Sql joins
Sql joinsSql joins
Sql joins
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Mysql
MysqlMysql
Mysql
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
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
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql Procedure
 
Join
JoinJoin
Join
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
 
Mysql joins
Mysql joinsMysql joins
Mysql joins
 
Unit 3 - Function & Grouping,Joins and Set Operations in ORACLE
Unit 3 - Function & Grouping,Joins and Set Operations in ORACLEUnit 3 - Function & Grouping,Joins and Set Operations in ORACLE
Unit 3 - Function & Grouping,Joins and Set Operations in ORACLE
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
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
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 

Similar to MYSQL using set operators

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
 
Integrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdfIntegrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdfSaikrishna492522
 
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
 

Similar to MYSQL using set operators (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
 
Integrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdfIntegrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdf
 
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
 

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

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Alison B. Lowndes
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaRTTS
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...Sri Ambati
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsVlad Stirbu
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 

MYSQL using set operators

  • 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);