DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • How To Fix SQL Database Restore Failed, Database Is in Use
  • Pagination in MS SQL Server
  • 9 Best Free and Open Source Tools for Reporting
  • The Materialized Path Technique: Tree Structures for Relational Database Systems

Trending

  • Deployment of Spring MVC App on a Local Tomcat Server
  • Architecture Patterns: API Gateway
  • Exploring Slowly Changing Dimensions in Data Warehousing
  • Unlocking Performance: Exploring Java 21 Virtual Threads [Video]
  1. DZone
  2. Data Engineering
  3. Databases
  4. Dynamic Sorting in MS SQL Server

Dynamic Sorting in MS SQL Server

Let users sort their columns in MS SQL.

NaveenKumar M user avatar by
NaveenKumar M
·
Oct. 09, 21 · Tutorial
Like (2)
Save
Tweet
Share
8.3K Views

Join the DZone community and get the full member experience.

Join For Free

What Is Sorting?

Sorting is a process of arranging items in a sequence by some standard or principle.

In MS SQL, the ORDER BY clause is used to arrange the data in ascending or descending order.

How Dynamic Sorting Works in MS SQL

Let's think of a web application that displays employee information in a grid with FirstName, LastName, Email, Title, Phone, and few other columns. On clicking the column heading the result set should sort accordingly.

Here, the sort column is dynamic, it depends on the user who clicks. To implement the sort on all the columns we use the CASE statement in the ORDER BY clause.

In the query below, @SortColumn defines the column that needs to be sorted, and @SortType defines ascending or descending. And the columns required for dynamic sorting are included in the CASEs under ORDER BY.

MS SQL
 
DECLARE @SortColumn AS VARCHAR(100) = 'firstname'
       ,@SortType   AS VARCHAR(100) = 'asc'

SELECT EmployeeKey,FirstName,LastName,Title,EmailAddress
FROM dbo.DimEmployee WITH(NOLOCK)
ORDER BY 
CASE WHEN @SortColumn = 'FirstName'      AND @SortType ='ASC'  THEN FirstName    END ASC,
CASE WHEN @SortColumn = 'FirstName'      AND @SortType ='DESC' THEN FirstName    END DESC,
CASE WHEN @SortColumn = 'LastName'       AND @SortType ='ASC'  THEN LastName     END ASC,
CASE WHEN @SortColumn = 'LastName'       AND @SortType ='DESC' THEN LastName     END DESC,
CASE WHEN @SortColumn = 'Title'          AND @SortType ='ASC'  THEN Title        END ASC,
CASE WHEN @SortColumn = 'Title'          AND @SortType ='DESC' THEN Title        END DESC,
CASE WHEN @SortColumn = 'EmailAddress'   AND @SortType ='ASC'  THEN EmailAddress END ASC,
CASE WHEN @SortColumn = 'EmailAddress'   AND @SortType ='DESC' THEN EmailAddress END DESC

In a real-time application, this logic can be written in the stored procedure which is called on clicking on the column which needs to be sorted, the respective column name, and the sort order to be passed as parameters to the stored procedure.

Microsoft SQL Server sql Sorting Database

Opinions expressed by DZone contributors are their own.

Related

  • How To Fix SQL Database Restore Failed, Database Is in Use
  • Pagination in MS SQL Server
  • 9 Best Free and Open Source Tools for Reporting
  • The Materialized Path Technique: Tree Structures for Relational Database Systems

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: