Skip to content
Advertisement

Get last record id from set of records in mysql query without fetching all records

I have a query that fetches a set of records as shown:

select id 
from wallactions 
where status=1 and created > DATE_ADD(NOW(),INTERVAL -1 DAY) 
order by id desc LIMIT $priorRecordsCnt

The LIMIT variable $priorRecordsCnt changes often and can grow very large. It’s necessary because i need to know the last id in that set of records based on the $priorRecordsCnt count value.

The problem is, I need to only access the last id in this set, as shown:

$last=array_values(array_slice($result,-1))[0]['id'];

I feel like this is pretty expensive to just get the id of the last record in the set.

Is there a way to optimize this query so it uses the count variable $priorRecordsCnt but i don’t need to fetch all the records just to obtain the last value?

Advertisement

Answer

The limit clause takes two arguments – an optional offset and the row count. Instead of using $priorRecordsCnt as the record count, you should use it as the offset, and limit the record count to 1:

select id 
from wallactions 
where status=1 and created > DATE_ADD(NOW(),INTERVAL -1 DAY) 
order by id desc LIMIT $priorRecordsCnt, 1
-- Here ---------------------------------^
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement