The SQL UNION Operator
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.


Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS Mar 2 WordPress: How to access first and random row values from a repeater field in ACF? Mar 1 The basics of CSS Box model Feb 27 WordPress: How to display slider repeater fields in ACF? Feb 26 Simple Page Hit Counter in PHP

You might also like these

Solution to Could not cast value of type ‘NSTaggedPointerString’ to ‘NSNumber’SwiftHow to create a Progress Bar using JavaScript?JavaScriptIntroduction to Angular modules Part 2: NgModules and componentsAngularHow to Use SQL MAX() Function with Dates?SQL/MySQLHow to create a cross-browser smooth scrolling with jQuery?jQueryHow to import MySQL small sample database into phpMySQL?SQL/MySQL