Yogesh Chauhan's Blog

Learn how to use Self JOIN in SQL and MySQL

in SQL/MySQL on September 24, 2019

Self JOIN in SQL

SQL SELF JOIN works the same way as the JOIN keyword itself. The only difference is that SELF JOIN joins the columns form a table itself.

Take a look at the syntax:

SELECT columns
FROM table Aliases_1, table Aliases_2 WHERE condition;

 So as we can in the syntax above, the columns are from the same tables and we just join it to get desired results. We can use Aliases to give the columns different names in the result set.

Let’s take a look at the example.

SELECT b.CustomerName AS [Customer Name], b.ContactName AS [Contact Name]
FROM customers a, customers b 
WHERE a.ContactName=b.ContactName 
  and a.CustomerName='Janis D. Triplett';

That is an example for SQL.

NOTE: Square brackets are used in the aliases’ names as they contain spaces.

Now take a look at the example for MySQL. There is just slight difference. If you’re using phpmyadmin then you need to use the following example.

SELECT b.CustomerName, b.ContactName 
FROM customers AS a, 
      customers AS b 
WHERE a.ContactName=b.ContactName 
  and a.CustomerName='Janis D. Triplett';

We used aliases in the column names in SQL and in MySQL, we are using it for tables names. 

Both of the above example will give same results and they will find customer’s name and related contact person for that customer. 

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to create a blurry text effect using CSS?CSSThe Sort and Compare Functions in JavaScriptJavaScript@forward rule in SCSS (Sass)SCSSHow to create a link tag button using CSS?CSSHow does Binding work in JavaScript?JavaScriptHow to add a ribbon inside a container using CSS?CSS