The most useful SQL Server queries solve a specific problem: find the right rows, combine related data, calculate a metric, or change records without touching more than you intended. These 50 T-SQL examples cover all four tasks. Start with the basics or jump to the pattern you need, from finding customers with no orders to calculating a running total.
Most examples use dbo.Customers (CustomerID, CustomerName, City, Email), dbo.Orders (OrderID, CustomerID, OrderDate, TotalAmount, Status), and dbo.OrderItems (OrderID, ProductID, Quantity, UnitPrice). Employee examples use dbo.Employees (EmployeeID, ManagerID, DepartmentID, Salary). Assume IDs named for their own table are primary keys, except in OrderItems, where each row is an order line. Replace table and column names as needed. Run write examples in a development database and substitute IDs that fit your data.
SQL Server queries for selecting and filtering rows
Before adding a join or an aggregate, decide which rows and columns the result should contain. The SQL queries overview and SELECT tutorial provide more background on the basic structure.
1. Select only the columns you need
SELECT CustomerID, CustomerName FROM dbo.Customers;
Explicit column names make the expected result clear to both readers and application code. They also avoid returning large or sensitive fields just because those fields happen to exist in the table.
2. Filter rows with WHERE
SELECT OrderID, TotalAmount FROM dbo.Orders WHERE Status = 'Paid';
The result contains only paid orders. A row whose status is NULL does not match the equality comparison.
3. Combine conditions with AND and OR
SELECT OrderID FROM dbo.Orders WHERE TotalAmount >= 100 AND (Status = 'Paid' OR Status = 'Shipped');
The parentheses make the minimum amount apply to both statuses. Without them, SQL Server evaluates AND before OR and can return shipped orders below 100. See multiple WHERE conditions for more examples.
4. Filter against a list with IN
SELECT CustomerID, City FROM dbo.Customers WHERE City IN ('Boston', 'Chicago', 'Seattle');
Use IN instead of repeating equality comparisons on the same column. For a list maintained elsewhere, consider selecting the values from a lookup table.
5. Search by prefix with LIKE
SELECT CustomerID, CustomerName FROM dbo.Customers WHERE CustomerName LIKE 'Ann%';
The percent sign matches zero or more characters, so the query can return both Ann and Anna. Case sensitivity depends on the applicable collation.
6. Find missing values with IS NULL
SELECT CustomerID FROM dbo.Customers WHERE Email IS NULL;
Use IS NULL rather than Email = NULL. An empty string is a stored value, not a NULL, so it will not appear in this result.
7. Filter a date range without losing rows on the last day
SELECT OrderID, OrderDate FROM dbo.Orders WHERE OrderDate >= '20260101' AND OrderDate < '20260201';
This half-open range includes all of January, even when OrderDate stores time. Using midnight on January 31 as an inclusive upper bound would miss later orders that day.
8. Return distinct values
SELECT DISTINCT City FROM dbo.Customers WHERE City IS NOT NULL ORDER BY City;
This produces an alphabetical list of known cities. If you select multiple columns, DISTINCT removes duplicate combinations of those columns, not duplicates in each column independently.
9. Get the latest 10 rows with TOP
SELECT TOP (10) OrderID, OrderDate FROM dbo.Orders ORDER BY OrderDate DESC, OrderID DESC;
TOP without ORDER BY does not reliably return the newest rows. Including the unique OrderID breaks ties when multiple orders have the same timestamp.
10. Page results with OFFSET and FETCH
SELECT OrderID, OrderDate FROM dbo.Orders ORDER BY OrderDate DESC, OrderID DESC OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
This returns positions 21 through 30 in the sorted result. A unique sort order resolves ties, but inserts or deletes between requests can still shift rows across pages.
Joins, subqueries, and set operations

Decide what one output row should represent before combining tables. Joining orders to order items changes the result from one row per order to one row per matching line item. That change matters when you count rows or sum amounts.
11. Match related records with INNER JOIN
SELECT o.OrderID, c.CustomerName FROM dbo.Orders AS o INNER JOIN dbo.Customers AS c ON c.CustomerID = o.CustomerID;
Use an inner join when you only want rows with a match on both sides. An order without a matching customer does not appear.
12. Keep unmatched rows with LEFT JOIN
SELECT c.CustomerID, o.OrderID FROM dbo.Customers AS c LEFT JOIN dbo.Orders AS o ON o.CustomerID = c.CustomerID;
Every customer appears, including those with no orders. The latter have a NULL OrderID. See the LEFT JOIN guide for more on how unmatched rows are represented.
13. Filter matches without dropping customers
SELECT c.CustomerID, o.OrderID FROM dbo.Customers AS c LEFT JOIN dbo.Orders AS o ON o.CustomerID = c.CustomerID AND o.Status = 'Paid';
Putting the status test in ON keeps customers who have no paid orders. Moving it to WHERE removes the rows where the joined order columns are NULL.
14. Reconcile two lists with FULL OUTER JOIN
SELECT a.CustomerID AS OldID, b.CustomerID AS NewID FROM dbo.OldCustomers AS a FULL OUTER JOIN dbo.NewCustomers AS b ON b.CustomerID = a.CustomerID WHERE a.CustomerID IS NULL OR b.CustomerID IS NULL;
Assuming both snapshot tables have unique, non-null customer IDs, this returns IDs found in only one snapshot. Remove WHERE to see matches too.
15. Join a table to itself
SELECT e.EmployeeID, m.EmployeeID AS ManagerID FROM dbo.Employees AS e LEFT JOIN dbo.Employees AS m ON m.EmployeeID = e.ManagerID;
The aliases distinguish the employee from the manager. The left join retains employees with no matching manager, such as the person at the top of the hierarchy.
16. Check whether a related row exists
SELECT c.CustomerID FROM dbo.Customers AS c WHERE EXISTS (SELECT 1 FROM dbo.Orders AS o WHERE o.CustomerID = c.CustomerID AND o.Status = 'Paid');
EXISTS answers a yes-or-no question without multiplying customer rows. A customer with ten paid orders still appears once.
17. Find records without a match
SELECT c.CustomerID FROM dbo.Customers AS c WHERE NOT EXISTS (SELECT 1 FROM dbo.Orders AS o WHERE o.CustomerID = c.CustomerID);
This lists customers who have never ordered. Unlike a NOT IN comparison, NOT EXISTS is not thrown off by an unrelated NULL in the inner list.
18. Compare a value with a subquery result
SELECT OrderID, TotalAmount FROM dbo.Orders WHERE TotalAmount > (SELECT AVG(TotalAmount) FROM dbo.Orders);
Each order is compared with the overall average. To compare with the average for its own customer instead, correlate the inner query on CustomerID.
19. Append results with UNION ALL
SELECT OrderID, OrderDate FROM dbo.Orders UNION ALL SELECT OrderID, OrderDate FROM dbo.ArchivedOrders;
This combines current and archived orders without removing duplicate rows. Both SELECT statements must return the same number of columns in the same order, with compatible types. Use UNION only when you want duplicate result rows removed.
20. Find values common to two result sets
SELECT CustomerID FROM dbo.Orders WHERE Status = 'Paid' INTERSECT SELECT CustomerID FROM dbo.Orders WHERE Status = 'Pending';
The result is a distinct list of customers who appear in both sets. It does not require a single order to have both statuses.
Aggregation queries for reports and dashboards

GROUP BY changes the result from individual rows to summaries. Check whether the input represents orders, line items, or customers before interpreting a total. In particular, summing an order total after joining to line items can count the same order multiple times.
21. Count rows, known values, and distinct values
SELECT COUNT(*) AS Customers, COUNT(Email) AS KnownEmails, COUNT(DISTINCT Email) AS UniqueEmails FROM dbo.Customers;
COUNT(*) counts every row. COUNT(Email) ignores NULL, and COUNT(DISTINCT Email) also removes duplicates. Empty strings are not treated as missing values.
22. Summarize orders per customer
SELECT CustomerID, COUNT(*) AS OrderCount, SUM(TotalAmount) AS OrderTotal FROM dbo.Orders GROUP BY CustomerID;
Each CustomerID present in Orders produces one row. The GROUP BY tutorial explains how grouping columns define the level of detail.
23. Filter groups with HAVING
SELECT CustomerID, COUNT(*) AS PaidOrders FROM dbo.Orders WHERE Status = 'Paid' GROUP BY CustomerID HAVING COUNT(*) >= 5;
WHERE filters individual orders before grouping. HAVING filters the grouped result, keeping customers with at least five paid orders. See the HAVING guide for more examples.
24. Keep zero-count groups in a report
SELECT c.CustomerID, COUNT(o.OrderID) AS OrderCount FROM dbo.Customers AS c LEFT JOIN dbo.Orders AS o ON o.CustomerID = c.CustomerID GROUP BY c.CustomerID;
Count the non-null order key, not COUNT(*). A customer with no match still has a placeholder row from the left join, but that row has no OrderID to count.
25. Count multiple categories in one result
SELECT SUM(CASE WHEN Status = 'Paid' THEN 1 ELSE 0 END) AS PaidCount, SUM(CASE WHEN Status = 'Pending' THEN 1 ELSE 0 END) AS PendingCount FROM dbo.Orders;
Conditional aggregation puts both metrics on one row. If the source table is empty, these SUM expressions return NULL; use COALESCE around each SUM if the report needs zero instead.
26. Group totals by calendar month
SELECT DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1) AS MonthStart, SUM(TotalAmount) AS MonthlyTotal FROM dbo.Orders WHERE OrderDate IS NOT NULL GROUP BY DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1) ORDER BY MonthStart;
The month-start date includes the year, so January orders from different years stay separate. Months with no orders do not appear; use a calendar table when you need to show them.
27. Find the first and latest order dates
SELECT CustomerID, MIN(OrderDate) AS FirstOrder, MAX(OrderDate) AS LastOrder FROM dbo.Orders GROUP BY CustomerID;
MIN and MAX return the dates, not the orders that hold those dates. Use ROW_NUMBER when the report also needs columns from the latest order row.
28. Find duplicate email values
SELECT Email, COUNT(*) AS Occurrences FROM dbo.Customers WHERE Email IS NOT NULL GROUP BY Email HAVING COUNT(*) > 1;
This identifies values to review before you add a uniqueness rule. Grouping follows the email column’s collation, which matters if addresses differ only in case.
29. Calculate a percentage safely
SELECT 100.0 * COUNT_BIG(CASE WHEN Status = 'Paid' THEN 1 END) / NULLIF(COUNT_BIG(*), 0) AS PaidPercent FROM dbo.Orders;
The decimal literal avoids integer truncation. NULLIF prevents division by zero, leaving the percentage undefined when there are no orders.
30. Return category totals and a grand total
SELECT Status, GROUPING(Status) AS IsGrandTotal, SUM(TotalAmount) AS OrderTotal FROM dbo.Orders GROUP BY GROUPING SETS ((Status), ());
The empty grouping set adds a grand total. GROUPING distinguishes its generated NULL status from an actual group of orders whose status is NULL.
CTEs and window functions for multi-step queries

A common table expression, or CTE, names an intermediate result for one statement. A window function compares or aggregates rows without collapsing them into a single summary row. Use the two together when you need to calculate a ranking and then filter on it.
31. Name an intermediate result with a CTE
;WITH PaidTotals AS (SELECT CustomerID, SUM(TotalAmount) AS PaidTotal FROM dbo.Orders WHERE Status = 'Paid' GROUP BY CustomerID) SELECT CustomerID, PaidTotal FROM PaidTotals WHERE PaidTotal > 1000;
The final SELECT reads like a filter on a named result. A CTE is not a stored table and does not guarantee that SQL Server computes it only once. See the SQL CTE guide for more patterns.
32. Walk an employee hierarchy with a recursive CTE
;WITH Org AS (SELECT EmployeeID, ManagerID, 0 AS Depth FROM dbo.Employees WHERE ManagerID IS NULL UNION ALL SELECT e.EmployeeID, e.ManagerID, g.Depth + 1 FROM dbo.Employees AS e INNER JOIN Org AS g ON e.ManagerID = g.EmployeeID) SELECT EmployeeID, ManagerID, Depth FROM Org OPTION (MAXRECURSION 100);
The first branch starts at employees with no manager; the second follows direct reports. Employees not reachable from a root are absent. The recursion limit raises an error if the query exceeds it.
33. Return the latest order per customer with ROW_NUMBER
;WITH Ranked AS (SELECT CustomerID, OrderID, OrderDate, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderDate DESC, OrderID DESC) AS rn FROM dbo.Orders) SELECT CustomerID, OrderID, OrderDate FROM Ranked WHERE rn = 1;
Each customer with orders gets one result. The OrderID tie-breaker makes the result deterministic when two orders share a timestamp.
34. Rank salaries with gaps after ties
SELECT EmployeeID, DepartmentID, Salary, RANK() OVER (PARTITION BY DepartmentID ORDER BY Salary DESC) AS SalaryRank FROM dbo.Employees WHERE Salary IS NOT NULL;
RANK assigns the same position to ties and skips subsequent positions: two people tied for first are followed by third place.
35. Rank salaries without gaps
SELECT EmployeeID, DepartmentID, Salary, DENSE_RANK() OVER (PARTITION BY DepartmentID ORDER BY Salary DESC) AS SalaryRank FROM dbo.Employees WHERE Salary IS NOT NULL;
With DENSE_RANK, two people tied for first are followed by second place. Use it to rank distinct salary levels. Compare behaviors in the DENSE_RANK tutorial.
36. Get the three largest distinct order amounts per customer
;WITH Ranked AS (SELECT CustomerID, OrderID, TotalAmount, DENSE_RANK() OVER (PARTITION BY CustomerID ORDER BY TotalAmount DESC) AS AmountRank FROM dbo.Orders WHERE TotalAmount IS NOT NULL) SELECT CustomerID, OrderID, TotalAmount FROM Ranked WHERE AmountRank <= 3;
This keeps all ties at the three highest amount levels, so it may return more than three orders per customer. For at most three orders, use ROW_NUMBER with a unique tie-breaker.
37. Calculate a running order total
SELECT CustomerID, OrderID, OrderDate, SUM(TotalAmount) OVER (PARTITION BY CustomerID ORDER BY OrderDate, OrderID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal FROM dbo.Orders ORDER BY CustomerID, OrderDate, OrderID;
The frame starts at each customer’s first order and ends at the current row. The outer ORDER BY displays rows in the same sequence used for the calculation.
38. Compare each order with the previous one
SELECT CustomerID, OrderID, TotalAmount - LAG(TotalAmount) OVER (PARTITION BY CustomerID ORDER BY OrderDate, OrderID) AS ChangeFromPrevious FROM dbo.Orders;
LAG looks backward in the specified order. The first order for each customer has no previous value, so its difference is NULL.
39. Find the next order date
SELECT CustomerID, OrderID, OrderDate, LEAD(OrderDate) OVER (PARTITION BY CustomerID ORDER BY OrderDate, OrderID) AS NextOrderDate FROM dbo.Orders;
LEAD looks forward without a self-join. The final order in each customer’s sequence has no next date.
40. Calculate a three-order moving average
SELECT CustomerID, OrderID, AVG(TotalAmount) OVER (PARTITION BY CustomerID ORDER BY OrderDate, OrderID ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS MovingAverage FROM dbo.Orders;
This averages the current order and up to two prior orders. It is a three-row window, not a three-day window, and AVG ignores NULL amounts.
41. Show each order’s share of its customer’s total
SELECT CustomerID, OrderID, 100.0 * TotalAmount / NULLIF(SUM(TotalAmount) OVER (PARTITION BY CustomerID), 0) AS PercentOfTotal FROM dbo.Orders;
The windowed SUM repeats the customer total on every order row. With no ORDER BY inside OVER, the denominator covers the whole customer partition rather than a running total.
42. Find the latest order with OUTER APPLY
SELECT c.CustomerID, x.OrderID, x.OrderDate FROM dbo.Customers AS c OUTER APPLY (SELECT TOP (1) o.OrderID, o.OrderDate FROM dbo.Orders AS o WHERE o.CustomerID = c.CustomerID ORDER BY o.OrderDate DESC, o.OrderID DESC) AS x;
OUTER APPLY keeps customers with no orders, unlike the ROW_NUMBER example that starts from Orders. Use this pattern when you want a single related row alongside every customer.
Data changes and query diagnostics
Before changing data, run a SELECT with the same filter to verify the row set. For diagnostic examples, measure performance with representative data and parameter values rather than assuming a rewrite is faster.
43. Insert a row and return its generated ID
INSERT INTO dbo.Customers (CustomerName, City, Email) OUTPUT inserted.CustomerID VALUES ('Taylor Morgan', 'Boston', NULL);
This assumes CustomerID is generated automatically. Listing the target columns makes the insert independent of their physical order in the table.
44. Insert multiple rows from a query
INSERT INTO dbo.ArchivedOrders (OrderID, OrderDate) SELECT OrderID, OrderDate FROM dbo.Orders WHERE OrderDate < '20240101';
This copies rows into an existing archive table; it does not remove them from Orders. Before scheduling it, define how reruns handle IDs already in the archive.
45. Update a row only if it is in the expected state
UPDATE dbo.Orders SET Status = 'Shipped' WHERE OrderID = 101 AND Status = 'Paid'; SELECT @@ROWCOUNT AS RowsUpdated;
A zero count means no row matched both conditions. Check @@ROWCOUNT immediately after the update because later statements can reset it.
46. Recalculate an order total from its line items
UPDATE o SET TotalAmount = s.LineTotal FROM dbo.Orders AS o INNER JOIN (SELECT OrderID, SUM(Quantity * UnitPrice) AS LineTotal FROM dbo.OrderItems GROUP BY OrderID) AS s ON s.OrderID = o.OrderID WHERE o.OrderID = 101;
The grouped source supplies at most one total per order. An order with no line items is left unchanged. Use this only if quantity times unit price matches your definition of the order total.
47. Delete a test row and return its key
DELETE FROM dbo.Orders OUTPUT deleted.OrderID WHERE OrderID = 101 AND Status = 'Cancelled';
Use a known test order and preview the filter first. Foreign keys may block the delete or cascade it depending on their configuration; the returned key identifies only the row deleted by this statement from Orders.
48. Rehearse an update inside a transaction
BEGIN TRANSACTION; UPDATE dbo.Orders SET Status = 'Cancelled' WHERE OrderID = 101 AND Status = 'Pending'; SELECT @@ROWCOUNT AS RowsUpdated; ROLLBACK TRANSACTION;
Run this in a development session with no existing transaction. The rollback undoes the database update. Run the batch as a unit rather than leaving the session waiting with an open transaction and held locks.
49. Pass a value to parameterized dynamic SQL
EXEC sys.sp_executesql N'SELECT OrderID, TotalAmount FROM dbo.Orders WHERE CustomerID = @id;', N'@id int', @id = 42;
Pass values separately instead of concatenating them into the statement. Match the parameter type to the target column. For a fixed query in application code, use the database driver’s parameter binding rather than building dynamic SQL unnecessarily.
50. Measure logical reads and execution time
SET STATISTICS IO ON; SET STATISTICS TIME ON; SELECT OrderID, TotalAmount FROM dbo.Orders WHERE CustomerID = 42; SET STATISTICS TIME OFF; SET STATISTICS IO OFF;
Review the logical reads, CPU time, and elapsed time in your client’s Messages output. Pair these numbers with the actual execution plan to see whether a change reduces work or simply moves it elsewhere.
To put these queries into practice, choose one report you already maintain and write down what each output row represents. Test it with duplicate matches, NULLs, ties, and an empty result. Those cases often reveal mistakes that a typical sample result won’t show.