What is an SQL subquery?

Share

A query in SQL is used to retrieve, insert, or update the data in a table. A subquery is a query within a query.

svg viewer

Clauses of a subquery

There are three clauses of any subquery:

  • A SELECT clause: specifies the field to be extracted from the specified table.

  • A FROM clause: specifies the table from where the data is retrieved.

  • A WHERE clause: specifies the condition on which the retrieval is based.

Sample table of “employees”

emp_id first_name last_name quality
1 George Cleverly Speaks well
2 Tom Rooney Manages well
3 Jazz Cleverly Punctual
4 Clarke James Quick worker
5 Wash Ramp Manages well
6 Hill Billings Quick worker

Sample table of “ratings”

emp_id rating
1 3
2 1
3 2
4 5
5 2
6 4

​### Code The following example uses all three clauses to display the employees who have a rating higher than 3.

SELECT a.emp_id, a.first_name, a.last_name, b.rating
FROM Employee a, ratings b
WHERE a.emp_id = b.emp_id AND b.rating >
(SELECT rating
FROM ratings
WHERE rating=3);
Copyright ©2024 Educative, Inc. All rights reserved