To sort SQL Server results according to a caller’s choice, use explicit CASE expressions when the sort menu is small and fixed. When callers can choose among more ordering expressions, build the ORDER BY from internally allow-listed SQL fragments, while passing filter and paging values as sp_executesql parameters. Never concatenate an untrusted column name or direction into a query. For paging, add a unique tie-breaker and account for changes to the data between requests.
Why dynamic sorting needs an explicit design
SQL Server does not guarantee the order of results unless the query specifies ORDER BY. A user interface that offers sorting therefore needs to translate a requested sort field and direction into a deliberate ordering expression; it cannot rely on the order rows happen to be returned in.
There are two common approaches: conditional CASE expressions for a small, known menu, or dynamic SQL assembled from a controlled set of SQL fragments. In both cases, keep the choices finite and deliberate.
Use CASE for a small, fixed set of choices
Microsoft documents conditional CASE expressions in ORDER BY as a way to choose an ordering expression. This works well when a query supports only a few sortable fields. Include separate expressions for ascending and descending choices where required:
#1 Best Overall
SELECT Id, Name, CreatedAt
FROM dbo.Items
ORDER BY
CASE WHEN @SortKey = N'name' AND @Direction = N'ASC' THEN Name END ASC,
CASE WHEN @SortKey = N'name' AND @Direction = N'DESC' THEN Name END DESC,
CASE WHEN @SortKey = N'created' AND @Direction = N'ASC' THEN CreatedAt END ASC,
CASE WHEN @SortKey = N'created' AND @Direction = N'DESC' THEN CreatedAt END DESC,
Id ASC;
The example assumes @SortKey and @Direction are values supplied to the query, and that Id is unique. Extend the explicit branches for the actual supported menu. Ensure expressions combined in a CASE have compatible data types; where they do not, use separate expressions or deliberate casts appropriate to the query rather than relying on implicit conversion.
Use allow-listed dynamic SQL for more flexible ordering
When sorting needs more expressions or a simpler mapping from a requested key to a column, dynamic SQL can make the statement easier to maintain. The sort column and direction are parts of SQL syntax, not ordinary values that can be safely substituted with parameters. Map each accepted key to a fixed, trusted expression and accept only ASC or DESC. Reject or safely default unrecognized choices.
Rank #2
Keep data values—such as filters, offsets, and page sizes—separate from the SQL text with sp_executesql. Microsoft warns that runtime-compiled SQL can expose applications to attacks and recommends parameterization; concatenating caller-entered text into a statement is a primary injection risk. Parameterizing a filter does not, by itself, make an arbitrary column name or direction safe.
DECLARE @SortExpression nvarchar(100);
DECLARE @SortDirection nvarchar(4);
-- Map incoming choices to fixed fragments; do not copy request text here.
SET @SortExpression = CASE @SortKey
WHEN N'name' THEN N'Name'
WHEN N'created' THEN N'CreatedAt'
ELSE N'Id'
END;
SET @SortDirection = CASE WHEN @Direction = N'DESC' THEN N'DESC' ELSE N'ASC' END;
DECLARE @sql nvarchar(max) = N'
SELECT Id, Name, CreatedAt
FROM dbo.Items
ORDER BY ' + @SortExpression + N' ' + @SortDirection + N', Id ASC
OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY;';
EXEC sys.sp_executesql
@sql,
N'@Offset int, @PageSize int',
@Offset = @Offset,
@PageSize = @PageSize;
This pattern is safe only because the inserted ordering fragments come from fixed choices selected inside the application or procedure. Validate that paging values are sensible for the endpoint as well. Bind other filter values in the same way as the paging parameters instead of appending them to the SQL text.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteChoose the approach that fits the sort menu
| Consideration | CASE expressions | Allow-listed dynamic SQL |
|---|---|---|
| Best fit | A small, fixed menu of sortable fields and directions. | A broader set of ordering expressions or a statement whose ordering is easier to construct from mapped fragments. |
| Sort choice | Represent choices as explicit conditional expressions in the query. | Map a sort key and direction to trusted SQL fragments; never accept arbitrary SQL syntax. |
| Values and filters | Pass values as query or procedure parameters. | Pass values separately through sp_executesql. |
| Type considerations | Keep expressions in CASE type-compatible or cast intentionally. |
Each allow-listed expression can retain the column’s native type. |
| Performance expectation | Measure the actual query and workload. | Microsoft says unchanged statement text with varying parameter values is likely to allow reuse of a previously generated plan; that is not a guarantee that this strategy is faster. |
Microsoft’s sp_executesql documentation describes likely plan reuse when statement text stays the same and only parameter values vary. It does not establish that one dynamic-sorting design is universally faster. Compare actual plans and measure representative requests in the target environment.
Make paged results dependable
OFFSET and FETCH are available with ORDER BY in SQL Server 2012 and later, as well as Azure SQL Database and Azure SQL Managed Instance. Microsoft’s ORDER BY documentation also covers Azure Synapse Analytics and Fabric SQL offerings; check the target engine because syntax support can differ.
Rank #4
Add a unique final tie-breaker
If several rows share the selected sort value, their relative order is not determined by that value alone. Add a unique key as the last sort expression—such as Id ASC in the examples—so the specified ordering uniquely identifies each row.
Account for changes between page requests
A unique ordering makes the order unambiguous for a given data state, but it does not freeze the data across separate requests. Inserts, deletes, or updates between page requests can shift rows, producing duplicates or omissions. Microsoft says consistent results across page requests require either that the underlying data does not change or that requests run in a single transaction using snapshot or serializable isolation, in addition to an order whose columns guarantee uniqueness.
Free tools Windows power users keep installed
One-click scans. No signup required.
Best Value
For a report or API that fetches pages in separate transactions, decide whether concurrent changes are acceptable. If they are not, design the paging workflow around a stable view of the data and an appropriate isolation strategy rather than assuming that OFFSET/FETCH alone provides a snapshot.
Common mistakes to avoid
- Relying on incidental row order: specify
ORDER BYwhenever output order matters. - Appending request text: never paste a supplied field name, direction, or SQL fragment directly into statement text; map it to fixed choices first.
- Assuming parameters validate identifiers: parameterize data values, but separately constrain SQL syntax such as column names and
ASC/DESC. - Paging on non-unique sort values: add a unique final key to prevent ties from leaving row order unresolved.
- Expecting stable pages while data changes: determine whether the application needs stable data or transaction isolation across page retrieval.
- Declaring one pattern faster by default: check plans and workload measurements for the actual query.
For further security context, see Microsoft’s SQL Injection guidance and Query Processing Architecture Guide.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

