What is a subquery and how is it used in SQL?

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


Subqueries, in SQL, are a powerful and essential tool, used within the main SQL queries to form sophisticated queries and to deal with complex data and database structures. They are inner queries nested in a main, or outer query which may be Select, Update, Insert or Delete queries.

Understanding Subqueries

A subquery in SQL is also termed as inner query or nested query. It’s essentially a query within a query. By convention, a subquery is written within the parentheses and is executed first, and the result of it is used to complete the query condition for the main, or outer, query.

Types of Subqueries

In SQL, subqueries can generally be classified into two types:

  1. Single-row Subquery: where the inner query returns only one row.
  2. Multi-row Subquery: where the inner query returns multiple rows.

How to Use Subqueries in SQL

Subqueries can be used in various places within a main SQL query: in the SELECT, WHERE and FROM clauses. Now, let’s take a look at a couple of examples for a detailed understanding:

Subquery within a Select Statement

The above SQL code snippet explains the use of a subquery in a Select statement. This nested query generates a list of OrderId along with the respective CustomerName from two different tables (Orders, Customers) by matching the CustomerId.

Subquery within a Where clause

The above SQL command uses a subquery within a WHERE clause. This subquery brings out the names and departments of employees whose salaries are greater than the average salary of all employees.

Conclusion

You can see that subqueries in SQL provide a powerful, flexible tool for creating complex queries and working with database structures and relationships. When you become comfortable with these nested queries, you’ll have a much broader range of options for sorting, filtering, and selecting the data you need for your applications and reports.

Leave a Comment