Mastering T-SQL: Essential Commands and Techniques for SQL Server

Learning T-SQL for SQL Server starts with a practical skill: stating exactly which rows you want to read or change. A query can run without errors and still return the wrong totals, miss records near midnight, or update more rows than intended. This guide shows how to avoid those mistakes while working with the commands you will use most often: SELECT, JOIN, GROUP BY, INSERT, UPDATE, and DELETE. It also covers transactions, window functions, and the basics of execution plans.

How T-SQL works in SQL Server

Transact-SQL, or T-SQL, is Microsoft’s extension of SQL. It includes familiar relational commands as well as features such as local variables, TRY…CATCH error handling, and the OUTPUT clause for capturing affected rows. You can issue commands from a query editor or through an application driver. In both cases, you describe the result or change you want, and SQL Server chooses how to carry out the request.

The examples use two tables. dbo.Customers contains CustomerID, CustomerName, and Region. dbo.Orders contains OrderID, CustomerID, OrderDate, OrderTotal, and Status. Assume that OrderID and CustomerID identify rows in their respective tables, and that Orders.CustomerID references Customers.CustomerID. OrderDate can include a time component. Use a development database with sample data before running any of the write examples.

These examples use schema-qualified names such as dbo.Orders so it is clear which object each statement addresses. If you want more practice with the SQL concepts shared across database systems, SQL Tutorial is a useful companion for reviewing the fundamentals alongside these SQL Server examples.

Retrieve and filter rows with SELECT

Start with the columns the reader or application actually needs. Explicit column lists make a query easier to review and keep its output from changing unexpectedly when someone adds a column to the table. SELECT * is convenient for inspecting an unfamiliar table, but it is rarely a good default for a saved report or application query.

SELECT OrderID, CustomerID, OrderDate, OrderTotal 
FROM dbo.Orders 
WHERE Status = 'Shipped' 
ORDER BY OrderDate DESC, OrderID DESC;

WHERE filters individual rows before grouping or aggregation. ORDER BY sorts the final result. Without ORDER BY, SQL Server does not guarantee the order of returned rows. Here, OrderID breaks ties between orders with the same timestamp, making the output predictable even when several orders share an OrderDate.

Use half-open date ranges

To retrieve every order placed in January 2026, use an inclusive start and an exclusive end. The upper bound is the start of February rather than an attempt to represent the last possible instant in January.

SELECT OrderID, OrderDate FROM dbo.Orders 
WHERE OrderDate >= '20260101' 
AND OrderDate < '20260201';

BETWEEN includes both endpoints. If you use the last calendar day as its upper bound and OrderDate contains a time, you can inadvertently include midnight at the start of that day but miss the rest of it. Half-open ranges work across different timestamp precisions and let adjacent reporting periods meet without overlapping. If timestamps are stored in UTC but the report uses a local calendar, calculate the correct UTC boundaries before applying the filter.

Treat NULL as missing information

Use IS NULL or IS NOT NULL rather than comparing a value to NULL with an equals sign. SQL treats a comparison with NULL as unknown, and WHERE keeps only rows for which the condition is true. For example, Region <> ‘West’ does not include customers with no recorded region. If the report should include them, say so explicitly with WHERE Region <> ‘West’ OR Region IS NULL. When combining AND and OR, use parentheses to make the intended logic visible.

Join tables without losing or multiplying the wrong rows

Use an INNER JOIN when you want only matching rows. The following query pairs orders with their customers. The aliases o and c show where each column comes from, which is especially helpful when both tables have a CustomerID column.

SELECT o.OrderID, c.CustomerName, o.OrderTotal 
FROM dbo.Orders AS o 
INNER JOIN dbo.Customers AS c 
ON c.CustomerID = o.CustomerID;

Use a LEFT JOIN when every row from the left-hand table should remain, even without a match. For example, to list all customers and show any January orders they placed, put the date criteria in the ON clause. Customers without matching orders still appear, with NULL in the order columns.

SELECT c.CustomerID, c.CustomerName, o.OrderID 
FROM dbo.Customers AS c 
LEFT JOIN dbo.Orders AS o 
ON o.CustomerID = c.CustomerID 
AND o.OrderDate >= '20260101' 
AND o.OrderDate < '20260201';

Moving those date criteria into WHERE would discard the rows with missing order dates, defeating the purpose of the outer join. The practical distinction is that ON determines which orders qualify as matches, while WHERE determines which rows survive after the join.

Check what one result row represents

The previous query returns one row per matching order, plus one row for each customer with no matching order. It does not return exactly one row per customer. This distinction matters if you later join a table of order items. An order with three items would appear three times, and summing OrderTotal at that point would count the same order value three times.

When you need one row per order, aggregate the item rows by OrderID before joining them to orders. When you only need to know whether a related row exists, consider EXISTS instead of a join. For example, the following query returns each qualifying customer once regardless of the number of shipped orders:

SELECT c.CustomerID, c.CustomerName FROM dbo.Customers AS c 
WHERE EXISTS (SELECT 1 FROM dbo.Orders AS o WHERE o.CustomerID = c.CustomerID AND o.Status = 'Shipped');

Summarize data with GROUP BY and HAVING

Aggregate functions turn groups of rows into measures such as counts and totals. In this example, the report needs one row for each customer with at least three shipped orders. WHERE first limits the input to shipped orders, GROUP BY builds a group for each CustomerID, and HAVING filters the groups by their order counts.

SELECT CustomerID, COUNT(*) AS ShippedOrderCount, SUM(OrderTotal) AS ShippedOrderTotal 
FROM dbo.Orders 
WHERE Status = 'Shipped' 
GROUP BY CustomerID HAVING COUNT(*) >= 3;

Choose your counting expression based on what a row represents. COUNT(*) counts every result row, while COUNT(column) counts only rows where that column is not NULL. If you adapt the earlier LEFT JOIN to report January order counts for every customer, use COUNT(o.OrderID). COUNT(*) would report one row for a customer with no January orders because the outer join preserves that customer.

SUM and AVG ignore NULL values. A missing order total can therefore change an average by reducing the number of values included. Do not replace missing values with zero unless zero is the correct business interpretation. For a customer with no matching orders, displaying a total of zero may be appropriate; for a customer whose existing orders have unknown totals, it can hide a data quality problem.

Use CTEs and window functions for multi-step queries

Grouped order rows with the latest row highlighted for each customer

A common table expression, or CTE, gives a query step a name. You can reference it from the statement that immediately follows it. It is useful for separating ranking from filtering, as in a report that needs only the latest order per customer. A CTE is not a temporary table and does not, by itself, guarantee that SQL Server computes and stores the result once.

;WITH RankedOrders AS (SELECT OrderID, CustomerID, OrderDate, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderDate DESC, OrderID DESC) AS RowNum FROM dbo.Orders) 
SELECT OrderID, CustomerID, OrderDate FROM RankedOrders WHERE RowNum = 1 ORDER BY CustomerID;

ROW_NUMBER starts a separate sequence for each CustomerID because of PARTITION BY. The window’s ORDER BY puts the newest order first and uses OrderID as a tie-breaker. The final WHERE keeps that first order. If the requirement is to return all orders tied for the latest timestamp, use RANK ordered by OrderDate alone and keep every row with rank 1.

Keep row detail while calculating a running total

GROUP BY collapses rows, but a window function can calculate a summary while preserving each order. A running total per customer is a good example:

SELECT CustomerID, OrderID, OrderDate, OrderTotal, SUM(OrderTotal) 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 ROWS clause tells SQL Server to sum from the first row in the customer’s sequence through the current row. The two ORDER BY clauses serve different purposes: the one inside OVER controls the calculation, and the final one controls display. If you filter out older orders in this same query, they will not contribute to the running total. To display a shorter period while keeping earlier orders in the calculation, compute the window in a CTE and filter the display period in the outer query.

Insert, update, and delete data safely

Before changing data, identify the rows you expect to affect and decide what should happen if that expectation is not met. For an UPDATE or DELETE, start by running a SELECT with the same predicate. That preview helps you spot a wrong identifier or missing condition, but it is not a guarantee: another session can change the data before your write runs.

INSERT with an explicit column list

INSERT INTO dbo.Orders (CustomerID, OrderDate, OrderTotal, Status) VALUES (42, '20260115', 125.00, 'Pending');

This example assumes CustomerID 42 exists and that SQL Server supplies OrderID, such as through an identity column. Listing the columns shows where each value goes and avoids relying on the table’s physical column order. If the application needs the new identifier, add OUTPUT INSERTED.OrderID between the column list and VALUES. When the insert is part of a larger transaction, treat the identifier as provisional until the transaction commits.

UPDATE only rows in the expected state

UPDATE dbo.Orders 
SET Status = 'Shipped' 
WHERE OrderID = 1001 
AND Status = 'Pending';

The OrderID targets the order, and the status condition prevents overwriting a row that is no longer pending. If no row is affected, the order may be missing or its status may already have changed. Check the number of affected rows before reporting success. In T-SQL, read @@ROWCOUNT immediately after the write because subsequent statements can change it.

DELETE with a specific predicate

DELETE FROM dbo.Orders 
WHERE OrderID = 1001 
AND Status = 'Cancelled';

Review foreign keys before deleting. They can block a deletion when related records exist, or they can trigger additional deletions if a cascading rule is configured. Also check whether business policy calls for keeping the order for reporting or auditing. If the record should remain, updating its status may be more appropriate than deleting it. An UPDATE or DELETE without a WHERE clause targets every row.

Manage SQL Server transactions and errors

A transaction groups changes so they can be committed together or rolled back. Suppose order confirmation updates the order and also writes to an audit table. If the audit write fails, the order should not be confirmed on its own. Put both statements in one transaction and keep unrelated work outside it.

The following standalone example uses a single update to show the pattern. It expects exactly one pending order to change. Run it as a single batch in a session that is not already inside a transaction.

SET XACT_ABORT ON; 
BEGIN TRY BEGIN TRANSACTION; 
UPDATE dbo.Orders SET Status = 'Confirmed' WHERE OrderID = 1001 AND Status = 'Pending'; 
IF @@ROWCOUNT <> 1 BEGIN THROW 50001, 'Expected one pending order.', 1; END; 
COMMIT TRANSACTION; 
END TRY BEGIN CATCH IF XACT_STATE() <> 0 BEGIN ROLLBACK TRANSACTION; END; THROW; END CATCH;

TRY contains the work and the commit. If a catchable error occurs, CATCH rolls back any remaining transaction and rethrows the error for the caller. SET XACT_ABORT ON helps ensure many run-time errors do not leave a transaction partially completed. This example owns its transaction; do not copy its unconditional rollback into a procedure that must preserve a caller-owned transaction without first reviewing how that procedure should handle errors and transaction ownership.

Keep transactions short. Opening one and then waiting for user input, an external service, or a manual check can hold locks longer than necessary and block other sessions. For large maintenance operations, smaller committed batches can reduce the duration of individual transactions, but they also give up the ability to roll back the full job as one unit. Choose the approach based on the consistency requirement, not just the number of rows.

Improve SQL Server query performance with evidence

Start by confirming that the query returns the correct data. Then inspect how SQL Server obtains it. An estimated execution plan shows the optimizer’s expected steps without running the statement. An actual execution plan includes run-time information from executing it, such as actual row counts. Remember that obtaining an actual plan for a write statement runs the write; use an appropriate test environment.

Write predicates that can use an index efficiently

A query that applies YEAR to OrderDate and compares the result to 2026 generally cannot use an ordinary index on OrderDate to seek directly to that year’s range. Instead, write WHERE OrderDate >= ‘20260101’ AND OrderDate < ‘20270101’. Leaving the column unwrapped gives the optimizer the option to seek to the relevant range if a suitable index exists and the plan makes that choice.

Use parameter types that match the columns you compare them with. An implicit conversion on the indexed column can make a straightforward lookup more expensive. When sending queries from an application, bind values using the database driver’s parameter mechanism instead of concatenating them into SQL. This separates data values from the statement and helps protect against SQL injection.

Design indexes for the queries you actually run

If users frequently retrieve orders for a specific customer within a date range, an index beginning with CustomerID followed by OrderDate is a reasonable candidate to test. The equality condition narrows the search to one customer, and the date condition limits the range within that customer’s orders. A report that filters only on OrderDate may need a different index because it does not constrain the first key.

Indexes are not free: they take storage and must be maintained as data changes. Before adding one, check existing indexes for overlap and measure whether the proposed index helps a representative workload. A table or index scan is not automatically a problem. If a report reads much of the table, scanning may be cheaper than many individual lookups.

Compare plans and measurements before and after a change

Use SET STATISTICS IO ON to see logical reads and SET STATISTICS TIME ON to review CPU and elapsed time. Compare equivalent queries with representative parameters, and remember that elapsed time can vary with caching and concurrent activity. Turn the settings off when you are finished measuring.

In the actual plan, compare estimated and actual row counts around filters and joins. A large gap is a clue, not a diagnosis. It may point to skewed data, stale statistics, or a predicate that is hard to estimate. Change one thing at a time, then verify both the result and the measurements. A faster query that changes which rows the report counts is not an improvement.

Build a repeatable T-SQL review routine

  1. State what one result row represents. Decide whether it should represent an order, a customer, or another entity before choosing joins and aggregates.
  2. Test boundaries and missing values. Include rows at the start and end of a date range, customers without orders, and records with NULL values.
  3. Check ordering and ties. Add a unique tie-breaker when selecting the latest row or limiting a sorted result.
  4. Validate writes in a test database. Preview the predicate, check the affected row count, and confirm how failures are handled before using the statement on live data.
  5. Measure performance on realistic data. Use the execution plan and read counts to decide whether to change a predicate, rewrite a join, or test an index.

To put these techniques together, build a January report that lists every customer, counts shipped orders, and shows the latest shipped order date. Test a customer with no orders, one whose only orders are outside January, and one with several shipments on the same day. If each case returns the intended result, you have verified the core logic before optimizing it or putting it into an application.