How to create a nested SELECT in SQL

The SELECT command is used to retrieve data from one or more tables. To do so, we use the word SELECT in our query. If we wish to add conditions or more restraints to the retrieval query, we may use nested SELECT.

A nested query, i.e. a query within a query, is known as a subquery.

svg viewer

Example

In the code below, there is a nested SELECT which is used to display the PersonID from the table ‘Person’. The inner select is used to view the PersonID, LastName, FirstName; it does not SELECT City from the table. The outer SELECT then selects the list of PersonIDs already selected by the inner SELECT, and displays them.

This syntax can be better understood through the code below:​

CREATE TABLE Person (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
City varchar(255)
);
INSERT INTO Person (PersonID, LastName, FirstName, City)
VALUES (1 , 'Erichsen', 'Tom', 'Newyork'),
(2 , 'Cleverly', 'John', 'Texas'),
(3 , 'George', 'Bill', 'Chicago');
-- Nested SELECT ------
SELECT A.PersonID FROM (
SELECT PersonID, LastName, FirstName FROM Person
) AS A;
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved