Limit and Order Your Query Results

The query result set can sometimes be quite large if your Data Cloud org contains a lot of data. To limit the query result, use the LIMIT clause. The LIMIT clause returns the first n rows that the data store returns, where n is the number of rows specified.

This query returns 20 unified individuals only.

The LIMIT clause doesn’t guarantee the order of the rows returned. You can get different results if you run the query at different times. A more reproducible query is one that combines the LIMIT clause with the ORDER BY clause so that the results returned are in the same order in each query execution. A useful query is to get the top rows based on a certain criterion and by combining ORDER BY and LIMIT.

This query returns the top 20 oldest unified individuals based on the birth date.

This query output shows the first few rows returned for unified individuals from the result set of 20 rows. The rows are ordered by birth date.

ssot__FirstName__cssot__LastName__cssot__BirthDate__c
AviGreen1937-03-12T00:00:00.000Z
BabaraLevy1940-07-20T00:00:00.000Z
EdnaFrank1945-10-23T00:00:00.000Z
StellaPavlova1946-12-04T00:00:00.000Z
.........

The ORDER BY clause orders in ascending order by default. To order the result in descending order, use the DESC keyword. This ORDER BY clause in the query returns the top 20 youngest individuals.

Sometimes, you want to retrieve a subset of the returned result set. For example, if the results are displayed on a page with a specified number of records. OFFSET returns the row after the specified row number. You can use OFFSET to page through the results and retrieve a subset each time. OFFSET is typically used with ORDER BY to make sure that you get the same result set in subsequent queries.

Suppose you already displayed the first two rows of the oldest individuals. You want the next two rows. You can use this query with an offset of 2 and a limit of 2.

This query returns rows 3 and 4 from the previous output. The rows are ordered by birth date.

ssot__FirstName__cssot__LastName__cssot__BirthDate__c
EdnaFrank1945-10-23T00:00:00.000Z
StellaPavlova1946-12-04T00:00:00.000Z