Mysql – Best way to check if record exists or not in MySQL

MySQL

I have a procedure that should check if a record exists or not for particular date range, if exists then fetch the record else fetch last 20 record.

For this i have to write a query multiple times, one for checking the existance , then fetch the same record or fetch record without where clause but with limit .

Query goes something like this inside procedure

set @cnt = (select count(*) from table where date_field between date1 and date2) ; 
if @cnt > 0 then 
    select * from table where date_field between date1 and date2 ; 
else 
    select * from table order by date_field desc limit 0,20 ; 
end if ;

Is there any way i can do it in a single query because my query has too many joins and too complicated, it may take some amount of time, so if i call it two times the fetching time will increase.

Best Answer

You could probably reduce this to 2 queries with something like:

select * from table where date_field between date1 and date2 ; 
set @count = found_rows()
if @count = 0 then
    select * from table order by date_field desc limit 0,20 ; 
end if ;