IN
In SQL programming, if a subquery returns more than one value, you might need to execute the outer query if the values within the column specified in the condition match any value in the result set of the subquery. To perform this task, you need to use the IN keyword.The syntax of using the IN keyword is:
SELECT column, column [,column]
FROM table_name
WHERE column [ NOT ] IN
(SELECT column FROM table_name [WHERE
Conditional_expression])
Consider an example. You need to retrieve the BusinessEntityID attribute of all the employees who live in Bothell, from the EmoloyeAddress table in the Adventure Works database.
To perform this task, you need to use a query to obtain the AddressID of all the addresses that contain the word Bothell. You can then obtain the BusinessEntityID from the Employee table where the AddresID matches any of the AddressIDs returned by the previous query.
To perform this task, you can use the following query:
SELECT BusinessEntityID FROM Person.BusinessEntityAddress
WHERE AddressID IN (SELECT AddressID FROM Person.Address WHERE City = 'Bothell')
The output of the subquery will show all the ID falls in the category.
EXISTS
You can also use a subquery to check if a set of records exist. For this, you need to use the EXISTS clause with a subquery. The EXISTS keyword, always returns a TRUE or FALSE value.The EXISTS clause checks for the existence of rows according to the condition specified in the inner query and passes the existence status to the outer query. The subquery returns a TRUE value if the result of the subquery contains any row.
The query introduced with the EXISTS keyword differs from other queries. The EXISTS keyword is not preceded by any column name, constant, or other expression, and it contains an asterisk (*) in the SELECT list of the inner query. The syntax of the EXISTS keyword in the SELECT query is:
SELECT column, column [column]
FROM table_name
WHERE EXISTS (SELECT column FROM table_name [WHERE
Conditional_expression] )
Consider an example. The users of AdventureWorks, Inc. need a list containing the BusinessEntityID and Title of all the employees who have worked in the Marketing department at any point of time. The department ID of the Marketing department is 4.
To generate the required list, you can write the following query by using the EXISTS keyword:
SELECT BusinessEntityID, Title FROM HumanResources.Employee
WHERE EXISTS
(SELECT * FROM HumanResources.EmployeeDepartmentHistory WHERE
BusinessEntityID = HumanResources.Employee. BusinessEntityID AND DepartmentID = 4)
The following figure displays the output generated by the query.
A subquery must be enclosed within parentheses and cannot use the ORDER BY or the COMPUTE BY clause.