How to avoid if-else statement in stored procedures

This post will give you some tips on some SQL queries.

First of all I have seen people writing queries for performing a condition checking like this.

IF @user_id ='' THEN
    SELECT usr_name FROM m_users;
ELSE
    SELECT usr_name FROM m_users WHERE usr_id = @user_id;
END IF;

So what is wrong here?  This code is so huge for such a simple logic. So, how do we simplify this code? How do we avoid the if-else block?
The answer is simple. The logic is usr_id = @user_id or @user_id = ''

You already got it right?

The simplified code is

SELECT usr_name FROM m_users WHERE usr_id = @user_id OR @user_id = '';

Comments