Problem
A table that loads every row up front does not survive a large data set: the page is slow, memory climbs and governor limits get close. The users still need to sort, edit in place and move through the data quickly.
What I built
LWC datatables backed by Apex: inline editing, dynamic sorting, server-side pagination and real-time queries, so each page of data is fetched when it is needed.
How it works
Rows and the total count come back along the same path.
The pattern: the server owns the window. The component sends page size, offset or cursor, sort field, direction and filters to Apex; Apex runs a SOQL query for exactly that window and returns the rows plus the total count.
Sort is a query concern. Sorting only the visible page would lie about the data, so the sort field and direction are validated against an allow list and put in the ORDER BY of the dynamic query. Never concatenate raw client input into SOQL.
Inline edit with draft values. lightning-datatable hands back a draftValues array on save. The component sends only the changed fields to Apex, which updates in a single DML call and returns per-row errors for the table to display.
public with sharing class AccountPageController {
private static final Set<String> SORTABLE = new Set<String>{ 'Name', 'Industry', 'AnnualRevenue', 'CreatedDate' };
public class Page {
@AuraEnabled public List<Account> rows;
@AuraEnabled public Integer total;
}
@AuraEnabled
public static Page getPage(Integer pageSize, Integer pageNumber, String sortBy, String sortDir) {
String field = SORTABLE.contains(sortBy) ? sortBy : 'Name';
String dir = sortDir == 'desc' ? 'DESC' : 'ASC';
Integer size = Math.min(Math.max(pageSize, 1), 200);
Integer offs = (Math.max(pageNumber, 1) - 1) * size;
Page p = new Page();
p.total = [SELECT COUNT() FROM Account WITH USER_MODE];
p.rows = Database.query(
'SELECT Id, Name, Industry, AnnualRevenue FROM Account WITH USER_MODE ' +
'ORDER BY ' + field + ' ' + dir + ', Id LIMIT :size OFFSET :offs'
);
return p;
}
}import { LightningElement } from 'lwc';
import getPage from '@salesforce/apex/AccountPageController.getPage';
export default class AccountTable extends LightningElement {
pageSize = 25;
pageNumber = 1;
sortBy = 'Name';
sortDirection = 'asc';
rows = [];
total = 0;
connectedCallback() { this.load(); }
async load() {
const { rows, total } = await getPage({
pageSize: this.pageSize, pageNumber: this.pageNumber,
sortBy: this.sortBy, sortDir: this.sortDirection,
});
this.rows = rows;
this.total = total;
}
handleSort({ detail: { fieldName, sortDirection } }) {
this.sortBy = fieldName;
this.sortDirection = sortDirection;
this.pageNumber = 1; // a new sort starts from the first page
this.load();
}
get lastPage() { return Math.max(1, Math.ceil(this.total / this.pageSize)); }
get onFirst() { return this.pageNumber === 1; }
get onLast() { return this.pageNumber >= this.lastPage; }
next() { this.pageNumber += 1; this.load(); }
prev() { this.pageNumber -= 1; this.load(); }
}