I'm creating an app that selling tickets, I have a table for available tickets
id | serial | sold
-------------------------------
1 | 000001 | false
2 | 000002 | false
3 | 000003 | true
When a user request a ticket the app select a ticket and mark it as sold.
My question is: how to manage this table and prevent selling the same ticket to a different user knowing that there will be a hundreds of requests at the same time?
I'm thinking about locking but when the row is locked for a transaction, if another transaction request the lock it must wait till the first transaction is finished and update the row as sold, then the second transaction will return that the ticket is been sold. Now how can I redirect the second transaction to a different row if it found the row is locked?
Edit
According to Paul Zahra's comment I created a stored procedure
DECLARE @id varchar(MAX)
SELECT @id = (
SELECT top(1) [Id]
FROM [dbo].[AvailableItems] WITH (ROWLOCK, UPDLOCK)
WHERE ([Sold] = 0) )
UPDATE [dbo].[AvailableItems]
SET [Sold] = 1
WHERE [Id] = @id
SELECT [Id], [Serial], [CreateDate], [AvailableTo]
FROM [dbo].[AvailableItems]
WHERE ([Id] = @id)
But I need to be sure what is going to happen to the second transaction if two transactions came at the same time? will it skip this row and move to the next row? or wait the first transaction to be finished then select the same row?