SQL Subquery
## Introduction to Subquery
Subquery is a query within another query. It is a set of SQL statements that are nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. Subqueries can return individual values or a list of records. Subqueries can be used in different ways and at different locations inside a query.
A subquery is usually added within the WHERE clause of another SQL statement. A subquery can also be used as a parameter to a function call. Subqueries can be used to return either a scalar (single) value or a row set; and, the SQL-92 standard permits subqueries in the FROM, WHERE, and SELECT clauses.
Subqueries are often used to manipulate data that is already present in the database. They can also be used to perform calculations, to compare values from different tables, or to create temporary tables for processing data. Subqueries are sometimes referred to as sub-selects, as they allow a SELECT statement to be executed inside the body of another SQL statement. Subqueries can be used to return a set of rows for processing by the parent query. Subqueries can also be used to compare values between different rows in the same table or between different tables.
Subqueries are useful in situations where you need to select rows from a table based on values in another table. The subquery is used to calculate values that can then be compared with values in the main query. Subqueries can also be used to update or delete rows in a table, or to insert new rows into a table.
Subqueries can also be used to create more complex queries, such as to calculate the sum of multiple columns, or to calculate the average of multiple columns. Subqueries can also be used to perform table joins, or to select data from multiple tables in a single query. Subqueries can even be used to create temporary tables for further processing.
Subqueries can be very useful when used properly and can save a lot of time and effort. However, it is important to keep in mind that subqueries can be resource intensive and can slow down query execution if not used carefully.
Worried About Failing Tech Interviews?
Attend our webinar on
"How to nail your next tech interview" and learn
.png)
Hosted By
Ryan Valles
Founder, Interview Kickstart

Our tried & tested strategy for cracking interviews

How FAANG hiring process works

The 4 areas you must prepare for

How you can accelerate your learnings
Register for Webinar
**SQL Subquery**
A subquery is a SELECT statement nested inside another statement such as SELECT, INSERT, UPDATE, or DELETE. Subqueries are often used to retrieve data from multiple related tables in a single query.
**Example:**
The following example uses a subquery to retrieve the city and country of each customer:
```SQL
SELECT
first_name,
last_name,
(SELECT city FROM customers c2 WHERE c2.id = c1.id) AS city,
(SELECT country FROM customers c2 WHERE c2.id = c1.id) AS country
FROM customers c1
```