I have some Orders created by Customers stored in postgres db.Some of the Orders may have 'pending' status.I want the user to be able to work on his last pending Order.
order table
id | order_num | order_date |customer_id | status
-----+-----------+------------+------------+---------
80 | 1234 | 02-01-2000 | 20 | pending
----------------------------------------------------
81 | 2345 | 02-01-2000 |20 | confirmed
-----------------------------------------------------
82 | 3456 | 02-01-2000 |20 | pending
--------------------------------------------------
83 | 3498 | 02-001-2000| 20 | confirmed
----------------------------------------------------
Is there anything wrong with using
select * from orders where customer_id =20 and status='pending' order by id DESC limit 1
The order_date for multiple records may be same.The order number may not always be in ascending order. Is ordering by id safe in this regards?
You should order by the
order_datewithidas a secondary sort key:You want the most recent order so you should sort to express that intent. You also have to deal with duplicate
order_datevalues so you can throwidin as a secondary sort key to, hopefully, get the most recent one on the most recentorder_date. This assumes thatidis aserialorbigserialcolumn.You’re probably safe using
order by id descas long as theorder_dateis not allowed to change after the record is created. However, if youorder by order_date desc, id descthen it will be immediately obvious what your intent is, the people maintaining your code (possibly you) might appreciate it when you saying exactly what you mean.