I have a notification table with the columns id, type, user_id and unseen.
To get new notifications count i use:
SELECT count(1)
FROM notifications
WHERE user_id=123 AND unseen=1
To mark only new notifications as seen i use:
UPDATE notifications
SET unseen=0
WHERE user_id=123 AND unseen=1
But this update query sometimes gives an error. I want to know, what is the right way to do this?
Edit:
ERROR DESC
Transaction (Process ID 68) was deadlocked on lock; communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
It can be issue of deadlock, while you are trying to update the records, some is also reading those records.
Your update statement is a complete statement, i think it is not running in a transaction. It seems, you want more priority to complete the updated statement instead of read statment (using select).
For above mentioned scenario, you can allow phantom read (every time user use executes the select query gets different output) by using NoLock while reading. In your scenario, it will be not a dirty read because you will be reading only commited records.