The last updated data shows first in the postgres selet query?

Viewed 34

I have simple query that takes some results from User model.

Query 1:

SELECT users.id, users.name, company_id, updated_at 
FROM "users" 
WHERE (TRIM(telephone) = '8973847' AND company_id = 90) 
LIMIT 20 OFFSET 0;

Result:

enter image description here

Then I have done some update on the customer 341683 and again I run the same query that time the result shows different, means the last updated shows first. So postgres is taking the last updated by default or any other things happens here?

enter image description here

1 Answers

Without an order by clause, the database is free to return rows in any order, and will usually just return them in whichever way is fastest. It stands to reason the row you recently updated will be in some cache, and thus returned first.

If you need to rely on the order of the returned rows, you need to explicitly state it, e.g.:

SELECT   users.id, users.name, company_id, updated_at
FROM     "users" 
WHERE    (TRIM(telephone) = '8973847' AND company_id = 90)
ORDER BY id -- Here!
LIMIT    20 OFFSET 0
Related