Skip to content
Advertisement

How do you use mysql to only return a record if no conflicts exist?

Is there a way to have a SELECT statement only return a result if there exist no records in the database that conflict with the conditions?

For example, people can reserve a table for two-hour blocks. A new reservation should only be allowed if there are no reservations that overlap with the new request.

Something like the following doesn’t work because as long as there is one reservation that doesn’t match it, then the statement will find that record and return it:

SELECT * FROM reservations WHERE (startTime NOT BETWEEN ? AND ?) AND (endTime NOT BETWEEN ? AND ?)

Advertisement

Answer

If you only want to return a result for your SELECT statement when no records conflicts with the conditions you should use EXISTS operator. It is a boolean operator.

SELECT * FROM reservations WHERE EXISTS (SELECT * FROM reservations WHERE (startTime NOT BETWEEN ? AND ?) AND (endTime NOT BETWEEN ? AND ?))

Alternatively, perhaps more logical in the context

SELECT * FROM reservations WHERE NOT EXISTS (SELECT * FROM reservations WHERE (startTime BETWEEN ? AND ?) AND (endTime BETWEEN ? AND ?))

Edit: one query, not returning all rows:

SELECT CASE WHEN count(*) > 0 THEN false ELSE true END as free FROM reservations WHERE (startTime BETWEEN ? AND ?) AND (endTime BETWEEN ? AND ?))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement