In Salesforce Lightning Web Components (LWC), displaying data in a structured format is very important for users.
One of the most commonly used components for this purpose is Lightning Data Table. It allows developers to display records in rows and columns, similar to a table, and provides powerful features such as sorting, filtering, and inline editing.
Among these features, sorting plays a crucial role, helping users quickly organize and analyze data. For example, users may want to sort accounts by name, revenue, or industry to better understand business data.
In the Salesforce Lightning data table, we can sort records using the onsort attribute for local sorting in Lightning data columns. The data in the Lightning table can also be sorted by Apex call.
In this Salesforce tutorial, we will learn about Salesforce Lightning Datatable Sorting in LWC using different methods to apply sorting to columns.
What is Lightning Datatable in LWC?
Lightning Datatable is a standard Salesforce component that displays records in a tabular format. It supports multiple features such as sorting, row selection, inline editing, and pagination.
In the Salesforce Lightning data table, there is a built-in sorting feature that sorts records by column fields, either on the client side (local sorting) or on the server side (Apex sorting).
It is widely used in Salesforce applications because it provides a clean, user-friendly interface for displaying data. Developers can fetch data from Apex, Salesforce objects, or static data and show it inside the datatable.
To enable sorting, set the column definition’s sortable attribute to ‘true’ as shown in the syntax below.
const columns = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true }
]We also use the parameter sort-by to select the field columns, and sort-direction to specify the sorting direction (ascending or descending).To implement sorting in LWC data tables, we have two approaches:
- Local sorting (Client-side sorting)
- Sorting via Apex Class (Server-side sorting)
What is Sorting in Lightning Datatable?
Sorting means arranging data in a specific order, either:
- Ascending (A → Z, 1 → 10)
- Descending (Z → A, 10 → 1)
In Lightning Datatable, sorting is implemented using:
- sortable: true in column definition
- onsort event to handle sorting
This allows users to click column headers to dynamically sort records.
Types of Sorting in LWC Datatable
There are two main types of sorting:
1. Client-Side Sorting (Local Sorting)
- Data is already loaded in the component
- Sorting happens in JavaScript
- No Apex call required
Best for:
- Small datasets
- Faster performance
2. Server-Side Sorting (Apex Sorting)
- Sorting happens in Apex
- Data is fetched again from the server
- Uses SOQL ORDER BY
Best for:
- Large datasets
- Better scalability
Salesforce Lightning Datatable Sorting in LWC
The Local sorting is implemented on the client side without making an Apex call. This sorting method is used when the data is already fetched and stored in the LWC component.
In this sorting, we capture the onsort event of the lightning-data table and then implement a sorting function in JavaScript.
1. Create an LWC component and enter the code below in the HTML file.
<template>
<lightning-card title="Local Sorting in Data Table">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
onsort={handleSort}
sorted-by={sortBy}
hide-checkbox-column="true"
sorted-direction={sortDirection}>
</lightning-datatable>
</lightning-card>
</template>2. After this, enter the code below in the JS file.
import { LightningElement, track, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
export default class LocalSortingDataTable extends LightningElement {
@track data = [];
@track columns = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Industry', fieldName: 'Industry', type: 'text', sortable: true },
{ label: 'Revenue', fieldName: 'AnnualRevenue', type: 'currency', sortable: true }
];
@track sortBy;
@track sortDirection;
@wire(getAccounts)
wiredAccounts({ error, data }) {
if (data) {
this.data = data;
} else if (error) {
console.error(error);
}
}
handleSort(event) {
const { fieldName: sortedBy, sortDirection } = event.detail;
this.sortBy = sortedBy;
this.sortDirection = sortDirection;
this.sortData(sortedBy, sortDirection);
}
sortData(fieldname, direction) {
let parseData = JSON.parse(JSON.stringify(this.data));
let keyValue = (a) => a[fieldname] ? a[fieldname].toLowerCase() : '';
parseData.sort((a, b) => {
let valueA = keyValue(a);
let valueB = keyValue(b);
return direction === 'asc' ? (valueA > valueB ? 1 : -1) : (valueA < valueB ? 1 : -1);
});
this.data = parseData;
}
}The handleSort(event) is triggered when we click on a column header to sort the table. The event.detail contains the fieldName of the column being sorted and the sortDirection.
The actual sorting logic is implemented in the “parseData.sort” where it sorts the array based on the field name (the column by which the table is being sorted) and direction (ascending or descending).
It updates the sortBy and sortDirection properties and then calls the sortData method to apply sorting.
3. Make the component available to Lightning pages by entering the code below inside the tag <lightningComponentBundle>.
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>4. Navigate to the lightning page, deploy the LWC component, and save the changes.
Now, we can view the data table with column sorting enabled, and to sort the data, you simply click the arrow icon in the column header.
It will sort the records in ascending order for the up arrow and descending order for the down arrow.

This way, we can implement local sorting or client-side sorting in the Salesforce Lightning data table in LWC.
Implement Sorting via an Apex Class in the LWC Data Table
When we implement sorting via an Apex class, it calls the entire sorting logic from the Apex controller to the data table. This method is helpful for large datasets, for which local sorting is inefficient.
To implement the sorting via an Apex class or the server-side sorting, follow the steps below.
1. Create an apex controller class for the account object, and enter the below with the defined sorting logic that we will call in the events later.
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getSortedAccounts(String sortField, String sortDirection) {
Set<String> allowedFields = new Set<String>{'Name', 'Industry', 'AnnualRevenue'};
if (!allowedFields.contains(sortField)) {
throw new AuraHandledException('Invalid sort field');
}
if (sortDirection != 'ASC' && sortDirection != 'DESC') {
throw new AuraHandledException('Invalid sort direction');
}
String query = 'SELECT Id, Name, Industry, AnnualRevenue FROM Account ORDER BY ' + sortField + ' ' + sortDirection;
return Database.query(query);
}
}2. Enter the code below in the JS file of the LWC component.
import { LightningElement, track, wire } from 'lwc';
import getSortedAccounts from '@salesforce/apex/AccountController.getSortedAccounts';
export default class ApexSortingDataTable extends LightningElement {
@track data = [];
@track columns = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Industry', fieldName: 'Industry', type: 'text', sortable: true },
{ label: 'Revenue', fieldName: 'AnnualRevenue', type: 'currency', sortable: true }
];
@track sortBy = 'Name';
@track sortDirection = 'asc';
@wire(getSortedAccounts, { sortField: '$sortBy', sortDirection: '$sortDirection' })
wiredAccounts({ error, data }) {
if (data) {
this.data = data;
} else if (error) {
console.error(error);
}
}
handleSort(event) {
this.sortBy = event.detail.fieldName;
this.sortDirection = event.detail.sortDirection;
}
}This LWC component retrieves and displays a sorted list of accounts in a Lightning Data Table. It fetches sorted data from an Apex method (getSortedAccounts) and allows us to dynamically change the sorting by clicking column headers.
The handleSort(event) is triggered when a user clicks a sortable column header. Then event.detail.fieldName gets the field selected for sorting and event.detail.sortDirection gets the sorting order (asc or desc).
3. Enter the code below in the HTML file and deploy the code to the org.
<template>
<lightning-card title="Sorting via Apex in Data Table">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
onsort={handleSort}
sorted-by={sortBy}
sorted-direction={sortDirection}>
</lightning-datatable>
</lightning-card>
</template>4. After this, make the component available for the Lightning pages by entering the code below inside the LightningComponentBundle tag.
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>5. Navigate to the lightning page and deploy the LWC component.
After deploying the LWC component, you will see the Lightning Data Table with the sorting we implemented from the Apex class.

This way, we can implement sorting in the LWC data table by calling the apex class method for the server-side sorting.
Frequently Asked Questions
Q1: What is sorting in the LWC datatable?
It is used to arrange records in ascending or descending order
Q2: How many types of sorting are there?
Two types: client-side and server-side
Q3: When should we use Apex sorting?
When working with large datasets
Q4: Is sorting available by default?
Yes, but you must enable it using sortable: true
Conclusion
In this Salesforce tutorial, we learned to implement server-side and client-side sorting in the LWC data table using the two methods outlined above. By sorting, we can improve the presentation of data in the LWC data table.
Salesforce Lightning Datatable sorting is a powerful feature that enhances the user experience by enabling users to easily organize data.
Developers can implement sorting on the client or server side, depending on data size and requirements.
Understanding how sorting works, when to use each method, and following best practices will help you build efficient and scalable Salesforce applications.
By using proper techniques and optimizing your code, you can create high-performance datatables that handle real-world business data effectively.
You may also like to read:
- Add Styling to a Salesforce Lightning Datatable in LWC?
- Infinite Loading in Data Table in Salesforce LWC
- Implement Infinite Loading in the Salesforce LWC Data Table
- Pagination in Salesforce LWC Data Table
- LWC vs Aura Components in Salesforce (Complete Guide)
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.