EXISTS (Transact-SQL)
Aplica-se a: SQL Server Banco de Dados SQL do Azure Instância Gerenciada de SQL do Azure Azure Synapse Analytics PDW (Analytics Platform System) Ponto de extremidade de análise do SQL Warehouse no Microsoft Fabric
Especifica uma subconsulta a ser testada quanto à existência de linhas.
Convenções de sintaxe de Transact-SQL
Sintaxe
EXISTS ( subquery )
Argumentos
subquery
É uma instrução SELECT restrita. A palavra-chave INTO não é permitida. Para obter mais informações, confira as informações sobre subconsultas em SELECT (Transact-SQL).
Tipos de resultado
Booliano
Valores de resultado
Retornará TRUE se uma subconsulta tiver qualquer linha.
Exemplos
a. Usando NULL em uma subconsulta para ainda a retornar um conjunto de resultados
O exemplo a seguir retorna um conjunto de resultados com NULL
especificado na subconsulta e ainda é avaliado como TRUE usando EXISTS
.
-- Uses AdventureWorks
SELECT DepartmentID, Name
FROM HumanResources.Department
WHERE EXISTS (SELECT NULL)
ORDER BY Name ASC ;
B. Comparando consultas usando EXISTS e IN
O exemplo a seguir compara duas consultas semanticamente equivalentes. A primeira consulta usa EXISTS
e a segunda usa IN
.
-- Uses AdventureWorks
SELECT a.FirstName, a.LastName
FROM Person.Person AS a
WHERE EXISTS
(SELECT *
FROM HumanResources.Employee AS b
WHERE a.BusinessEntityID = b.BusinessEntityID
AND a.LastName = 'Johnson') ;
GO
A consulta a seguir usa IN
.
-- Uses AdventureWorks
SELECT a.FirstName, a.LastName
FROM Person.Person AS a
WHERE a.LastName IN
(SELECT a.LastName
FROM HumanResources.Employee AS b
WHERE a.BusinessEntityID = b.BusinessEntityID
AND a.LastName = 'Johnson') ;
GO
Este é o conjunto de resultados para ambas as consultas.
FirstName LastName
-------------------------------------------------- ----------
Barry Johnson
David Johnson
Willis Johnson
(3 row(s) affected)
C. Comparando consultas usando EXISTS e = ANY
O exemplo a seguir mostra duas consultas para localizar lojas cujo nome seja igual ao de um fornecedor. A primeira consulta usa EXISTS
e a segunda usa = ANY
.
-- Uses AdventureWorks
SELECT DISTINCT s.Name
FROM Sales.Store AS s
WHERE EXISTS
(SELECT *
FROM Purchasing.Vendor AS v
WHERE s.Name = v.Name) ;
GO
A consulta a seguir usa = ANY
.
-- Uses AdventureWorks
SELECT DISTINCT s.Name
FROM Sales.Store AS s
WHERE s.Name = ANY
(SELECT v.Name
FROM Purchasing.Vendor AS v ) ;
GO
D. Comparando consultas usando EXISTS e IN
O exemplo a seguir mostra consultas para localizar os funcionários de departamentos que começam com P
.
-- Uses AdventureWorks
SELECT p.FirstName, p.LastName, e.JobTitle
FROM Person.Person AS p
JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = p.BusinessEntityID
WHERE EXISTS
(SELECT *
FROM HumanResources.Department AS d
JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON d.DepartmentID = edh.DepartmentID
WHERE e.BusinessEntityID = edh.BusinessEntityID
AND d.Name LIKE 'P%') ;
GO
A consulta a seguir usa IN
.
-- Uses AdventureWorks
SELECT p.FirstName, p.LastName, e.JobTitle
FROM Person.Person AS p JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = p.BusinessEntityID
JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON e.BusinessEntityID = edh.BusinessEntityID
WHERE edh.DepartmentID IN
(SELECT DepartmentID
FROM HumanResources.Department
WHERE Name LIKE 'P%') ;
GO
E. Usando NOT EXISTS
NOT EXISTS funciona de forma contrária a EXISTS. A cláusula WHERE em NOT EXISTS será atendida se nenhuma linha for retornada pela subconsulta. O exemplo a seguir localiza funcionários que não estão em departamentos que têm nomes que começam com P
.
SELECT p.FirstName, p.LastName, e.JobTitle
FROM Person.Person AS p
JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = p.BusinessEntityID
WHERE NOT EXISTS
(SELECT *
FROM HumanResources.Department AS d
JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON d.DepartmentID = edh.DepartmentID
WHERE e.BusinessEntityID = edh.BusinessEntityID
AND d.Name LIKE 'P%')
ORDER BY LastName, FirstName
GO
Veja a seguir o conjunto de resultados.
FirstName LastName Title
------------------------------ ------------------------------ ------------
Syed Abbas Pacific Sales Manager
Hazem Abolrous Quality Assurance Manager
Humberto Acevedo Application Specialist
Pilar Ackerman Shipping & Receiving Superviso
François Ajenstat Database Administrator
Amy Alberts European Sales Manager
Sean Alexander Quality Assurance Technician
Pamela Ansman-Wolfe Sales Representative
Zainal Arifin Document Control Manager
David Barber Assistant to CFO
Paula Barreto de Mattos Human Resources Manager
Shai Bassli Facilities Manager
Wanida Benshoof Marketing Assistant
Karen Berg Application Specialist
Karen Berge Document Control Assistant
Andreas Berglund Quality Assurance Technician
Matthias Berndt Shipping & Receiving Clerk
Jo Berry Janitor
Jimmy Bischoff Stocker
Michael Blythe Sales Representative
David Bradley Marketing Manager
Kevin Brown Marketing Assistant
David Campbell Sales Representative
Jason Carlson Information Services Manager
Fernando Caro Sales Representative
Sean Chai Document Control Assistant
Sootha Charncherngkha Quality Assurance Technician
Hao Chen HR Administrative Assistant
Kevin Chrisulis Network Administrator
Pat Coleman Janitor
Stephanie Conroy Network Manager
Debra Core Application Specialist
Ovidiu Crãcium Sr. Tool Designer
Grant Culbertson HR Administrative Assistant
Mary Dempsey Marketing Assistant
Thierry D'Hers Tool Designer
Terri Duffy VP Engineering
Susan Eaton Stocker
Terry Eminhizer Marketing Specialist
Gail Erickson Design Engineer
Janice Galvin Tool Designer
Mary Gibson Marketing Specialist
Jossef Goldberg Design Engineer
Sariya Harnpadoungsataya Marketing Specialist
Mark Harrington Quality Assurance Technician
Magnus Hedlund Facilities Assistant
Shu Ito Sales Representative
Stephen Jiang North American Sales Manager
Willis Johnson Recruiter
Brannon Jones Finance Manager
Tengiz Kharatishvili Control Specialist
Christian Kleinerman Maintenance Supervisor
Vamsi Kuppa Shipping & Receiving Clerk
David Liu Accounts Manager
Vidur Luthra Recruiter
Stuart Macrae Janitor
Diane Margheim Research & Development Enginee
Mindy Martin Benefits Specialist
Gigi Matthew Research & Development Enginee
Tete Mensa-Annan Sales Representative
Ramesh Meyyappan Application Specialist
Dylan Miller Research & Development Manager
Linda Mitchell Sales Representative
Barbara Moreland Accountant
Laura Norman Chief Financial Officer
Chris Norred Control Specialist
Jae Pak Sales Representative
Wanda Parks Janitor
Deborah Poe Accounts Receivable Specialist
Kim Ralls Stocker
Tsvi Reiter Sales Representative
Sharon Salavaria Design Engineer
Ken Sanchez Chief Executive Officer
José Saraiva Sales Representative
Mike Seamans Accountant
Ashvini Sharma Network Administrator
Janet Sheperdigian Accounts Payable Specialist
Candy Spoon Accounts Receivable Specialist
Michael Sullivan Sr. Design Engineer
Dragan Tomic Accounts Payable Specialist
Lynn Tsoflias Sales Representative
Rachel Valdez Sales Representative
Garrett Vargar Sales Representative
Ranjit Varkey Chudukatil Sales Representative
Bryan Walton Accounts Receivable Specialist
Jian Shuo Wang Engineering Manager
Brian Welcker VP Sales
Jill Williams Marketing Specialist
Dan Wilson Database Administrator
John Wood Marketing Specialist
Peng Wu Quality Assurance Supervisor
(91 row(s) affected)
Exemplos: Azure Synapse Analytics e PDW (Analytics Platform System)
F. Usando EXISTS
O exemplo a seguir identifica se uma linha na tabela ProspectiveBuyer
pode corresponder a linhas na tabela DimCustomer
. A consulta retornará linhas apenas quando os valores LastName
e BirthDate
nas duas tabelas forem correspondentes.
-- Uses AdventureWorks
SELECT a.LastName, a.BirthDate
FROM DimCustomer AS a
WHERE EXISTS
(SELECT *
FROM dbo.ProspectiveBuyer AS b
WHERE (a.LastName = b.LastName) AND (a.BirthDate = b.BirthDate)) ;
G. Usando NOT EXISTS
NOT EXISTS funciona como o oposto de EXISTS. A cláusula WHERE em NOT EXISTS será atendida se nenhuma linha for retornada pela subconsulta. O exemplo a seguir localiza linhas na tabela DimCustomer
em que LastName
e BirthDate
não corresponde a nenhuma entrada na tabela ProspectiveBuyers
.
-- Uses AdventureWorks
SELECT a.LastName, a.BirthDate
FROM DimCustomer AS a
WHERE NOT EXISTS
(SELECT *
FROM dbo.ProspectiveBuyer AS b
WHERE (a.LastName = b.LastName) AND (a.BirthDate = b.BirthDate)) ;
Consulte Também
Expressões (Transact-SQL)
Funções internas (Transact-SQL)
WHERE (Transact-SQL)