---
title: "How to use CASE statement in Order By Clause in SQL Server?"  
description: "How to use CASE statement in Order By Clause in SQL Server?"  
author: "Ashutosh Patel"  
published: 2024-12-27  
updated: 2025-01-02  
canonical: https://www.mindstick.com/forum/161085/how-to-use-case-statement-in-order-by-clause-in-sql-server  
category: "mssql server"  
tags: ["mssql server", "sql server", "sql"]  
reading_time: 2 minutes  

---

# How to use CASE statement in Order By Clause in SQL Server?

How to use the [CASE statement](https://www.mindstick.com/blog/290/case-statement-in-sql-server) in [Order](https://www.mindstick.com/articles/12276/how-timely-order-deliveries-can-improve-customer-experience) By [Clause in SQL](https://www.mindstick.com/forum/33663/use-of-group-by-and-having-clause-in-sql-server) [Server](https://www.mindstick.com/articles/43769/what-is-serverless-architecture-is-it-worth-switching-over)?

## Replies

### Reply by Khushi Singh

The **ORDER BY [clause](https://www.mindstick.com/forum/33937/difference-between-throw-exception-and-throw-clause)** of [SQL Server](https://www.mindstick.com/articles/12999/what-is-table-valued-function-in-sql-server) has an important option called CASE statement that enable the sorting of a query results depending on some conditions. Here's a simple explanation:

**What is it used for?**\
The CASE statement helps you:

- Arrange data in a manner different from other arrangements according to certain criteria.
- Use extensive reasoning as to how rows should order data sets.

**Example:**\
Imagine you have a table called Products with two columns: ProductName and Category. You want to sort:

- Any row that has its Category value equal to ‘Electronics’ should come first.
- Then sort the rest of them by ProductName in alphabetical order.

Here’s how you can do it:

```plaintext
SELECT ProductName, Category
FROM Products
ORDER BY
   CASE
       WHEN Category = 'Electronics' THEN 1
       ELSE 2
   END,
   ProductName;
```

### Explanation:

1. The **CASE** statement assigns a value:

   - to rows where `Category = 'Electronics'`.
   - to all other rows.

2. SQL Server uses these values to sort rows in ascending order:

   - Rows with (Electronics) come first.
   - Rows with come next.

3. Within each group, it sorts alphabetically by `ProductName.`

## Key Points:

- Just like any other place of the query, the CASE statement operates in the ORDER BY clause as well.
- You can use multiple sort conditions to have the type of sort order flexibility that you want.

This makes the CASE statement useful in dynamic sorting in the SQL query statement.

\
\

.


---

Original Source: https://www.mindstick.com/forum/161085/how-to-use-case-statement-in-order-by-clause-in-sql-server

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
