HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Best way to check if record exists or not in MySQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
wayrecordmysqlexistschecknotbest

Problem

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.

Solution

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 ;

Code Snippets

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 ;

Context

StackExchange Database Administrators Q#183816, answer score: 5

Revisions (0)

No revisions yet.