You are on page 1of 2

Joins vs.

Sub-queries

LaRon Walker

Master of Information Technology and Internet Security

March, 2010

In most programming languages, there generally are many ways to get to the same result. SQL

is no exception to this. As we all know, all programmers code differently, but still use the same basic

concepts. In SQL, you can use the JOIN, Sub-query, or a combination of both methods to retrieve and

display the same data. Using any of the above stated methods is opinionated. Below is an example of

each:

Using a simple Query

USE Unit_2_IP

Select Order_id, Customer_name


From Customers, Orders
Where Customers.Customer_id = Orders.Customer_id

Using the JOIN method

Use Unit_2_IP

SELECT Orders.Order_id, Customers.Customer_name


FROM Customers JOIN Orders
ON Customers.Customer_id = Orders.Customer_id

Using a Sub-query and Join (EXISTS METHOD)

Use Unit_2_IP

Select Order_id, Customer_name

FROM Customers, Orders

Where Exists
(Select Orders.Order_id, Customers.Customer_name
FROM Customers JOIN Orders
ON Customers.Customer_id = Orders.Customer_id)

The above examples return the same results. Based on the above examples, using the JOIN method

seems to be more comprehensive than using combination Sub-query and JOIN method. After

researching, I have found that using the combination of Sub-query and JOIN methods together seem to

be the most universal, allowing for the most flexibility. Per Cunningham (2005), “In the context of a join,

a sub-query will include or restrict values from one table while joining to another table”. Using sub-

queries can increase the size of your statement, in turn making it harder to read and comprehend.

However by using sub-queries, you can have more control over what data is retrieved as well as how it is

retrieved. For instance, you can control where a value might be IN or NOT IN a result set, or include a

record when some condition EXISTS or does NOT EXISTS. These types of queries are sometimes referred

to as scalar sub-queries. Overall, I feel that using the JOIN method along with the ON clause and scalar

subqueries are the most useful when writing SQL Queries because of the versatility and flexibility when

combining these methods.

References

it.toolbox.com, (2006). Introduction to Basic SQL, Part 3 - Complex Joins and Sub-queries. Retrieved

March 14, 2010 from http://it.toolbox.com/blogs/oracle-guide/introduction-to-basic-sql-part-3-

complex-joins-and-subqueries-9785

You might also like