Yogesh Chauhan's Blog

The SQL UNION Operator

in SQL/MySQL on September 24, 2019

The SQL UNION Operator (Works in MySQL as well)

As per the name suggests, UNION operator merges/combines/joins two or more results of SELECT statements. But you have to be careful while joining the result sets as it has to follow some conditions. For example,

  • You have to select same number of columns for each select statements. It makes sense. You can’t merge 1 column with 2 different columns data. Right?
  • Those columns MUST have same data type. For example, you can’t join columns with INT and VARCHAR data types.
  • The columns needs to be (read as MUST be) in the same order. For example if there are two columns; city column from customer and city column from merchants, which you want to join then it should be in the exact same order in the table. That’s tough one!

Let’s take a look at the syntax:

SELECT column(s) FROM table1
SELECT column(s) FROM table2;

The UNION operator by default selects distinct values. Means no place or duplicate values. For example, if there is a Chicago in a city columns of customers and merchants both then it will only give us one Chicago city in result set.

To allow duplicates, use UNION ALL. For e.g.

SELECT column(s) FROM table1
SELECT column(s) FROM table2;

Let’s take a look at the example.

SELECT City FROM Customers
SELECT City FROM merchants

The example query above will give us all the cities list which are in the city column of Customers table as well as in merchants table.

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to get front page or home page ID in WordPress?WordPressHow to make a UILabel clickable in Swift 5?SwiftHow to Commit and Rollback Changes in SQL?SQL/MySQLResponsive Masonry Grid using CSS columns PropertyCSSColleague UI Basics: Accessing the user interfaceColleagueWordPress: How to create a folder if it doesn’t already exist?WordPress