1. Home
  2. Computing & Technology
  3. Databases
photo of Mike Chapple
Mike's Databases Blog

By Mike Chapple, About.com Guide to Databases since 2000

Using Self-Joins in SQL

Sunday July 2, 2006
Did you know that you can use a self-join to simplify nested SQL queries where the inner and outer queries reference the same table? Here's a simple example.

Comments

July 12, 2006 at 6:00 am
(1) Thomas Ewald says:

In the second example, you’ll want to change “FROM employees e1, employees e1″ to “FROM employees e1, employees e2″.

——————————-
We could use this SQL query:

SELECT last_name, first_name
FROM employees
WHERE city in
( SELECT city
FROM employees
WHERE last_name=”Chapple”
AND first_name=”Mike” c)

Or we could simplify the query using a nested join, as shown below:

SELECT e1.last_name, e1.first_name
FROM employees e1, employees e1
WHERE e1.city = e2.city
AND e2.last_name=”Chapple”
AND e2.first_name=”Mike”

Give it a try the next time you’re composing a SQL query!

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Explore Databases
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Databases

©2009 About.com, a part of The New York Times Company.

All rights reserved.