← Back to Snippets
JavaScript
AMPScript
LookupOrderedRows in AMPScript: Retrieve and Sort Related Data
An optimized AMPScript pattern using LookupOrderedRows to retrieve, sort, and limit related records (like transaction history) from a Data Extension. This prevents OMM timeouts by handling sorting at the database level rather than the script level.
%%[
/* Retrieve top 3 rows ordered by OrderDate Descending */
SET @rows = LookupOrderedRows("Orders_DE", 3, "OrderDate Desc", "SubscriberKey", _subscriberKey)
SET @rowCount = RowCount(@rows)
IF @rowCount > 0 THEN
FOR @i = 1 TO @rowCount DO
SET @row = Row(@rows, @i)
SET @ProductName = Field(@row, "ProductName")
SET @OrderDate = Field(@row, "OrderDate")
SET @OrderTotal = Field(@row, "Total")
]%%
<div style="border-bottom: 1px solid #eee; padding: 10px;">
<p><strong>Product:</strong> %%=v(@ProductName)=%%</p>
<p>Date: %%=Format(@OrderDate, "MMM dd, yyyy")=%% | Total: $%%=FormatNumber(@OrderTotal, "N2")=%%</p>
</div>
%%[
NEXT @i
ELSE
]%%
<div style="padding: 10px;">
<p>You have no recent orders. <a href="https://site.com/shop">Start shopping</a>.</p>
</div>
%%[ ENDIF ]%%