Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

nested
select
sql

How to create a nested SELECT in SQL

Educative Answers Team

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;

RELATED TAGS

nested
select
sql
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring