Introduction
In previous lessons, you learned how to query one or more tables, filter and sort rows, group data, and use aggregate functions. This lesson focuses on three techniques that make T-SQL queries more flexible and expressive: subqueries, CASE expressions, and UNION operators.
A subquery is a SELECT statement that runs inside another statement. It can calculate a value, provide a set of rows for filtering, or test whether related rows exist. CASE produces a value according to one or more conditions. UNION and UNION ALL combine compatible result sets into a single result.
The examples use a simple sales database consistent with the previous lessons:
Customers(CustomerID, FirstName, LastName, City)
Products(ProductID, ProductName, Category, UnitPrice)
Orders(OrderID, CustomerID, OrderDate, Status)
OrderDetails(OrderDetailID, OrderID, ProductID, Quantity, UnitPrice)Before running the examples in SSMS, select the database that contains these tables.
Understanding subqueries
A subquery is written inside parentheses and supplies a value or result set to an outer query. Subqueries are commonly placed in WHERE conditions, but they can also appear in the SELECT or FROM clauses.
Single-row subqueries
A single-row subquery returns one value. For example, the following query lists products whose prices are above the average price:
SELECT ProductName, Category, UnitPrice
FROM Products
WHERE UnitPrice > (
SELECT AVG(UnitPrice)
FROM Products
);The inner query returns one numeric value: the average unit price. The outer query compares every product price with that value. Aggregate functions such as AVG, MIN, and MAX are often used to create single-row subqueries.
Another example finds the product or products with the highest price:
SELECT ProductName, UnitPrice
FROM Products
WHERE UnitPrice = (
SELECT MAX(UnitPrice)
FROM Products
);The inner query returns the maximum price. If several products share that price, the outer query returns all of them.
When a subquery is used with an equality or comparison operator, it must return a compatible single value. If it unexpectedly returns multiple rows, SQL Server reports an error indicating that the subquery returned more than one value.
Subqueries in the SELECT list
A subquery can also provide a calculated column. The following example displays each order total together with the average order total:
SELECT
OrderID,
SUM(Quantity * UnitPrice) AS OrderTotal,
(
SELECT AVG(OrderTotal)
FROM (
SELECT SUM(Quantity * UnitPrice) AS OrderTotal
FROM OrderDetails
GROUP BY OrderID
) AS OrderTotals
) AS AverageOrderTotal
FROM OrderDetails
GROUP BY OrderID;This example demonstrates nested queries. In production code, a very complex nested query may be easier to maintain as a common table expression or view. Those structures will be useful when query readability becomes more important.
Multi-row subqueries
A subquery can return more than one row. In that case, it should normally be used with operators such as IN, EXISTS, ANY, or ALL, rather than with a simple equality comparison.
Filtering with IN
Suppose you want to list orders placed by customers living in Istanbul or Ankara:
SELECT OrderID, CustomerID, OrderDate
FROM Orders
WHERE CustomerID IN (
SELECT CustomerID
FROM Customers
WHERE City IN ('Istanbul', 'Ankara')
);The inner query can return several customer IDs. The IN operator checks whether the outer CustomerID is contained in that set.
The number and type of expressions must be compatible. For example, a subquery returning two columns cannot be compared with a single scalar expression in this form. If you need columns from both sides, a JOIN may be clearer.
Checking existence with EXISTS
EXISTS tests whether the subquery returns at least one row. The following query finds customers who have placed at least one order:
SELECT c.CustomerID, c.FirstName, c.LastName
FROM Customers AS c
WHERE EXISTS (
SELECT 1
FROM Orders AS o
WHERE o.CustomerID = c.CustomerID
);The inner query refers to the current row of the outer query. This is called a correlated subquery. For each customer, SQL Server checks whether a matching order exists. Because EXISTS is an existence test rather than a request for data from the inner query, SELECT 1 is commonly used.
To find customers who have never placed an order, use NOT EXISTS:
SELECT c.CustomerID, c.FirstName, c.LastName
FROM Customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM Orders AS o
WHERE o.CustomerID = c.CustomerID
);Be careful with NOT IN when the subquery can return NULL. SQL uses three-valued logic, so NULL can cause rows to be treated as unknown rather than true or false. For exclusion tests, NOT EXISTS is often easier to reason about.
CASE expressions
CASE is an expression that returns a value based on conditions. It resembles an if-else structure, but it produces a result inside a query. CASE can be used in SELECT, ORDER BY, GROUP BY, and other expression contexts.
Conditional classification
The following query classifies products according to price:
SELECT
ProductName,
UnitPrice,
CASE
WHEN UnitPrice < 100 THEN 'Economy'
WHEN UnitPrice < 500 THEN 'Standard'
ELSE 'Premium'
END AS PriceGroup
FROM Products;CASE conditions are evaluated from top to bottom, and the result from the first true condition is returned. Therefore, condition order matters. If the condition UnitPrice less than 500 were placed first, products below 100 would also be classified as Standard.
Simple CASE syntax
When one expression is compared with several possible values, the simple CASE form is convenient:
SELECT
OrderID,
Status,
CASE Status
WHEN 'P' THEN 'Processing'
WHEN 'S' THEN 'Shipped'
WHEN 'C' THEN 'Cancelled'
ELSE 'Unknown'
END AS StatusDescription
FROM Orders;In this form, SQL Server compares Status with each value after WHEN. The searched CASE form, using conditions such as WHEN UnitPrice > 500, is more flexible.
Handling NULL and unexpected values
If no condition is true and ELSE is omitted, CASE returns NULL. An explicit ELSE is usually preferable in reports because it makes unexpected or missing values visible:
SELECT
ProductName,
CASE
WHEN UnitPrice IS NULL THEN 'Price Missing'
WHEN UnitPrice >= 1000 THEN 'High Price'
ELSE 'Normal Price'
END AS PriceStatus
FROM Products;CASE is not a control-of-flow statement. It returns a value; it does not decide whether an entire statement, procedure, or block should run. Use T-SQL control-of-flow statements when execution itself must be conditional.
UNION and UNION ALL
UNION combines the rows returned by two or more SELECT statements. This is different from JOIN. A JOIN usually brings columns from related tables together horizontally. UNION appends compatible result rows vertically.
For UNION to work, each SELECT must return the same number of columns in the same order. Corresponding data types must also be compatible. The column names of the final result are generally taken from the first SELECT.
Removing duplicates with UNION
The following query combines customers from Istanbul and Ankara:
SELECT FirstName, LastName, City
FROM Customers
WHERE City = 'Istanbul'
UNION
SELECT FirstName, LastName, City
FROM Customers
WHERE City = 'Ankara';UNION removes duplicate rows from the combined result. If the final result should be sorted, place ORDER BY at the end of the complete statement:
SELECT FirstName, LastName, City
FROM Customers
WHERE City = 'Istanbul'
UNION
SELECT FirstName, LastName, City
FROM Customers
WHERE City = 'Ankara'
ORDER BY City, LastName;Preserving every row with UNION ALL
UNION ALL retains duplicates:
SELECT ProductName AS ItemName, UnitPrice
FROM Products
WHERE Category = 'Software'
UNION ALL
SELECT ProductName AS ItemName, UnitPrice
FROM Products
WHERE Category = 'Hardware';Because duplicate removal is not performed, UNION ALL is often more efficient when duplicate rows are meaningful or impossible. Use UNION only when duplicate elimination is part of the required result.
Step-by-step practical workflow
Find products priced above the average:
SELECT ProductID, ProductName, UnitPrice FROM Products WHERE UnitPrice > (SELECT AVG(UnitPrice) FROM Products);Assign each product to a price group:
SELECT ProductName, CASE WHEN UnitPrice < 100 THEN 'Economy' WHEN UnitPrice < 500 THEN 'Standard' ELSE 'Premium' END AS PriceGroup FROM Products;Find customers with orders by using EXISTS:
SELECT c.CustomerID, c.FirstName, c.LastName FROM Customers AS c WHERE EXISTS ( SELECT 1 FROM Orders AS o WHERE o.CustomerID = c.CustomerID );Combine two category lists and sort the final result:
SELECT ProductName AS ItemName, Category FROM Products WHERE Category = 'Software' UNION ALL SELECT ProductName AS ItemName, Category FROM Products WHERE Category = 'Hardware' ORDER BY ItemName;
Common mistakes
- Using a multi-row subquery with an operator that expects one value: Use IN, EXISTS, ANY, or ALL when appropriate.
- Returning different numbers of columns in UNION branches: Every SELECT must return the same number of columns.
- Ignoring data type compatibility: Use explicit CAST or CONVERT when implicit conversion could be unclear or unsafe.
- Ordering CASE conditions incorrectly: The first true WHEN condition determines the result.
- Confusing UNION with JOIN: JOIN combines related columns, while UNION appends compatible rows.
- Ignoring NULL with NOT IN: Consider NOT EXISTS for exclusion queries involving nullable values.
- Using ORDER BY in every UNION branch: Sort the final combined result at the end of the statement.
Short practice exercise
Use the example tables or equivalent tables in an AdventureWorks-style database to complete these tasks:
- List products whose price is higher than the average product price.
- Classify products as below 50, from 50 through 250, or above 250.
- Find customers with at least one order by using EXISTS.
- Combine customers from two cities with UNION and observe how duplicates are handled.
- Run equivalent examples with UNION and UNION ALL, then explain the difference in row counts.
Conclusion
In this lesson, you learned how to use values and result sets produced by one query inside another query. Single-row subqueries are useful for comparisons with one calculated value, while multi-row subqueries work naturally with IN and EXISTS. CASE expressions classify data and create readable report columns. UNION and UNION ALL combine compatible result sets; UNION removes duplicate rows, whereas UNION ALL preserves them.
These techniques form an important bridge between basic SELECT statements and more advanced query design. In the final lesson, combine them with the earlier topics to build a small, coherent SQL Server reporting and data-management workflow.
Sources
- https://learn.microsoft.com/en-us/sql/relational-databases/performance/subqueries?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/t-sql/language-elements/exists-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-union-transact-sql?view=sql-server-ver17