Professional Documents
Culture Documents
Sub-queries
LaRon Walker
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:
USE Unit_2_IP
Use Unit_2_IP
Use Unit_2_IP
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
References
it.toolbox.com, (2006). Introduction to Basic SQL, Part 3 - Complex Joins and Sub-queries. Retrieved
complex-joins-and-subqueries-9785