SQL Subquery Interview Questions and Answers
SQL Subquery Interview Questions and Answers
Q. What is a subquery?
A. Subquery or Inner query or Nested query is a query in a query. A subquery is
usually added in the WHERE clause of the sql statement. A subquery can be nested
inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another
subquery. Subqueries are an alternate way of returning data from multiple tables.
Q. Can you create a subquery in a From clause?
A. Yes. Subqueries can be used in From, Where and Having clauses. For
example, in Sybase
select *
from
(
select 'A' as colVal
union
select 'B' as colVal
) data
Returns:
colVal
-----A
B
Joining virtual tables is one of the most powerful feature of subqueries. Virtual in
this context means the result set you are joining is built on the fly. Here is a more
advanced example:
declare @clientId varchar(30),
@reportDate date,
set nocount on
select reportId from
Report_Status s,
ReportKey k,
ReportGroupKey gk,
--subquery in from clause
(select max(s.createddttm) as maxdate, k1.clientId from
Report_Status s,
ReportKey k1,
ReportGroupKey gk
where k1.InactiveFlag ='N'
and gk.InactiveFlag ='N'
and gk.KeyId = k1.Id
and gk.Id = s.GroupKeyId
group by k1.clientId
) maxdates
where k.InactiveFlag ='N'
and gk.InactiveFlag ='N'
and gk.KeyId = k.Id
and gk.Id = s.GroupKeyId
and s.CreatedDtTm = maxdates.maxdate
and k.ClientId = @clientId
and maxdates.ClientId = k.ClientId
and k.reportDate = @reportDate
outer query.
Subqueries in some complex SQL queries can simplify coding and