Not long ago, I published a practical guide for optimizing queries in MySQL and MariaDB when dealing with large tables (you can read it here: Master SQL Queries in MySQL and MariaDB: A Practical Guide from Scratch for Large Tables). Now I’m sharing the SQL Server edition, so here it is: focused on T-SQL, featuring the same practical approach tailored directly to Microsoft’s database engine.
In inventory and logistics systems, performance is not a “nice to have”: it is mission-critical. Picture a warehouse operator scanning a barcode to log incoming merchandise… and the screen freezes for 25–30 seconds. You aren’t just consuming server resources: you’re halting a physical operation.
This guide is aimed at developers who already use SQL Server every day and want their queries across multi-million-row tables (movement history, stock ledgers, warehouse inventory, etc.) to stop being the application’s primary bottleneck.
Why Slow Queries End Up Costing Money (and a Lot of Stress)
An inefficient query in SQL Server isn’t just an annoyance because it’s slow. It triggers a cascade of issues:
- Prolonged locks: a long-running read query can lock (or induce lock waits on) critical tables such as Orders, Sales, or CurrentStock, preventing other users from generating invoices or posting movements.
- Unnecessary memory pressure: the Buffer Pool gets flooded with data pages you likely won’t need again anytime soon.
- Direct cloud costs: in Azure SQL Database or Managed Instance, heavy queries spike DTU, vCore, or serverless compute consumption, bumping you to a higher service tier without realizing it.
In short: a slow query isn’t just a technical problem… it’s a business problem.
1. SELECT: Less Is More (Much More)
In inventory systems, it’s very common to have tables packed with audit columns (CreatedBy, CreatedAt, OriginDevice), long descriptions, notes, or even VARCHAR(MAX) columns holding JSON or XML payloads.
Executing SELECT * forces the database engine to:
- read all those columns from disk (or buffer),
- transmit them across the network,
- and deserialize them into client memory…
even if your application only needs three of those fields.
A painful (and very common) example:
SELECT *
FROM MovimientosStock
WHERE FechaRegistro >= '2026-01-01';
A much more server-friendly version:
SELECT ProductoId, Cantidad, TipoMovimiento, IdAlmacenOrigen
FROM MovimientosStock
WHERE FechaRegistro >= '2026-01-01';
Rule of thumb: only select the columns you actually plan to use in your C#, Java, Python, or other application code. The performance gains are usually massive.
2. WHERE: Write SARGable Conditions (or How to Avoid Full Table Scans)
SARGable = Search ARGument ABLE: the engine can utilize the index to perform an efficient lookup (Index Seek) instead of scanning the entire table (Index Scan or Table Scan).
The quickest way to break SARGability is applying functions directly to the indexed column.
Classic performance killer:
SELECT COUNT(*)
FROM MovimientosStock
WHERE YEAR(FechaMovimiento) = 2025
AND MONTH(FechaMovimiento) = 12;
If SQL Server has to calculate the year and month for every single row: say goodbye to your index.
The correct (and much faster) way:
SELECT COUNT(*)
FROM MovimientosStock
WHERE FechaMovimiento >= '2025-12-01'
AND FechaMovimiento < '2026-01-01';
Other patterns that break SARGability (avoid them whenever possible):
- CONVERT(varchar, Fecha, 112) = ‘20251231’
- LEFT(Codigo, 3) = ‘ABC’
- Columna LIKE ‘%something%’ (the leading wildcard prevents an Index Seek)
- Column concatenations: LastName + ‘, ’ + FirstName = @param
3. Efficient Pagination with OFFSET … FETCH
If your application displays audit logs or large lists, never fetch 10,000 rows just to display the first 50 in a grid.
Modern SQL Server syntax (2012 onwards) is clean and efficient:
SELECT Id, ProductoId, Cantidad, FechaRegistro, TipoMovimiento
FROM MovimientosStock
ORDER BY FechaRegistro DESC, Id DESC
OFFSET 0 ROWS -- página 1
FETCH NEXT 50 ROWS ONLY;
For page 10:
OFFSET 450 ROWS FETCH NEXT 50 ROWS ONLY;
Pro tip to make it fly:
Create an index that strictly matches your ORDER BY clause (or as closely as possible):
CREATE NONCLUSTERED INDEX IX_Movimientos_Fecha_Id
ON MovimientosStock (FechaRegistro DESC, Id DESC)
INCLUDE (ProductoId, Cantidad, TipoMovimiento);
Without an index aligned with the ORDER BY, using OFFSET can become painfully expensive on large tables.
4. Indexes with Included Columns (INCLUDE): Farewell, Key Lookups
A Key Lookup is one of the most frustrating operators you’ll encounter in execution plans: SQL Server finds the matching rows quickly using a non-clustered index (Seek), but then has to hop back to the base table to retrieve columns not present in that index. On large tables, this produces hundreds or thousands of extra lookups, dragging performance down drastically.
SQL Server’s elegant solution is INCLUDE columns: they are stored only at the leaf level of the index (without bloating the B-tree navigation nodes), turning the query into a covering index query (fully resolved from the index alone) and eliminating the Key Lookup.
Practical inventory example (a common query for warehouse stock):
SELECT
AlmacenId, ProductoId, CantidadActual,
FechaUltimoMovimiento, CostoPromedio
FROM StockActual
WHERE AlmacenId = 15
AND CantidadActual > 0
ORDER BY ProductoId;
Insufficient index (triggers a Key Lookup):
CREATE NONCLUSTERED INDEX IX_Stock_Almacen
ON StockActual (AlmacenId)
INCLUDE (ProductoId);
Fast Seek on AlmacenId, followed by a Key Lookup for the remaining columns requested in the SELECT statement.
Covering index with INCLUDE (optimal solution):
CREATE NONCLUSTERED INDEX IX_Stock_Almacen_Covering
ON StockActual (AlmacenId)
INCLUDE (ProductoId, CantidadActual, FechaUltimoMovimiento, CostoPromedio);
Result: Index Seek only, zero lookups, and a typical 5x to 50x speedup on large tables.
When to use INCLUDE (quick guidelines):
- Columns that appear strictly in the SELECT clause (not in WHERE, JOIN, ORDER BY, or GROUP BY).
- Columns that are frequently read but rarely updated (every UPDATE incurs index maintenance overhead).
- Don’t overdo it: aim to cover your heaviest queries; 5–10 INCLUDE columns are typically more than enough.
5. Free Tools for Diagnostics and Improvement
| Tool | Primary Purpose | Practical Takeaway |
|---|---|---|
| SQL Server Management Studio (SSMS) | Inspect execution plans in real time | Press Ctrl + M before executing: look for red flags: Table Scan, Index Scan, Key Lookup, expensive Sort |
| Azure Data Studio | Lightweight and cross-platform development | Great for writing and analyzing quick queries. Supports the Plan Explorer extension |
| Database Engine Tuning Advisor | Index recommendations | Use with caution; it occasionally suggests redundant or excessive indexes |
| Extended Events | Low-overhead production monitoring | Replaces legacy Profiler with substantially lower server impact |
Quick tip in SSMS: after running a query with the actual execution plan enabled, right-click the plan and select “Missing Index Details…”. SQL Server will often hand you the exact CREATE INDEX script you need.
6. Beware: Index Overuse Can Also Cost You Dearly
While indexes drastically speed up read operations on large tables, creating too many (or overly wide) indexes comes with a steep penalty on write operations. Every INSERT, UPDATE, or DELETE must update every index that references the modified columns, generating additional I/O, locks, and index fragmentation. In high-throughput inventory systems (thousands of entries/exits per hour), an excess of indexes can turn a lightning-fast write into a sluggish, blocking operation—driving up lock waits, deadlocks, and even your Azure SQL bill. Golden rule: aim for a maximum of 5–8 non-clustered indexes per table; inspect them regularly using sys.dm_db_index_usage_stats to identify unused indexes and prune them. A handful of well-targeted indexes is always better than dozens accumulating maintenance overhead.
Real-World Case: Before vs. After (Approximate Measurement)
Table: MovimientosStock ≈ 5.4 million rows as of January 2026
Original query (the client’s complaint):
SELECT * FROM MovimientosStock
WHERE YEAR(FechaRegistro) = 2025;
- Execution time: ~14–17 seconds
- Dominant operator: Table Scan
- Logical reads: > 180,000
Optimized query:
SELECT ProductoId, Cantidad, TipoMovimiento, AlmacenOrigen
FROM MovimientosStock
WHERE FechaRegistro >= '2025-01-01'
AND FechaRegistro < '2026-01-01';
- Execution time: 120–250 ms (depending on cache/buffer warm-up)
- Dominant operator: Index Seek
- Logical reads: ~800–2,500
Net improvement: ~60–100x faster.
Your Next Step (The Realistic To-Do List)
- Open the slowest screen or report in your application right now.
- Run its primary query in SSMS with the actual execution plan turned on (Ctrl+M).
- Look for expensive operators: Table Scan, large Index Scan, repetitive Key Lookup, high-cost Sort.
- If a green “Missing Index” hint appears, evaluate it (it’s helpful more often than not).
- Start with the low-hanging fruit: eliminate SELECT *, make the WHERE clause SARGable, and implement offset-based pagination.
- Add or refine 1–2 critical indexes (leveraging INCLUDE where appropriate).
- Measure again. Compare execution times and logical reads.
Following these straightforward steps turns most “impossible” queries into responsive, highly optimized database calls.
Thanks for reading this far! Let’s keep coding.