MySQL: Dynamic Select Queries

As we start to transfer our code to stored procedures, now we would have to start putting more logic in MySQL than before. In the past we would create an sql statement in our hosting language, and pass it by to mysql, put as we see the more improvement of performance and security in writing stored procedures, (also we employee people just experienced in MySQL to handle the sql Job) we now need a way to manipulate our sql statements with sql itself.
What I’m putting here is an example for a search procedure. imagine that you are looking for a certain profiles in the database, while specifing some data to be checked upon, and some data if missing won’t be included in our condition, lets say a user would check on gender and a range of age for our table like

CREATE TABLE Profiles (
id INT PRIMARY KEY,
gender CHAR(1),
age INT);

ok let’s create our search stored procedure

CREATE PROCEDURE SearchProfiles(
  IN pGender CHAR(1),
  IN pAgeStart INT,
  IN pAgeEnd INT
BEGIN
  SELECT id FROM Profiles
    WHERE ((pGender IS NULL OR pGender = '') OR gender = pGender)
      AND (pAgeStart IS NULL OR age >= pAgeStart)
      AND (pAgeEnd IS NULL OR age <= pAgeEnd); END

So now if you Null any of the inputs, it's part of the query is removed, for example a NULL Gender would make the condition (pGender IS NULL OR pGender = '') evaluates to true and it's the right side of the total gender condition, which would let the gender = pGender Not Evaluated.
I guess you can improve the code more, by evaluating your stop conditions before you get in the select statement, and only calling a variable to test.

Hope it was useful 🙂

4 thoughts on “MySQL: Dynamic Select Queries”

  1. dear Alaa
    what if the value of pGender come NULL 🙂
    Is this equation come up with some thing in this case
    (pGender IS NULL OR pGender = ”) (NULL is NULL OR NULL = ”)

    so for sure NULL IS NULL is not equal, am i right?

    so i think that you can correct your code by IFNULL(pGender,-1) = -1

    i don’t know if i explain it right because i feel sleepy 🙂

  2. Alaa! shut the f*** up, this is Bashar! the MCDBNMA!
    Allah taba3 el MySQL!!!!!!!!!

    3ala rasi el Gerneral 😛

    *sigh* Mierda 3ala hal youm ma a6walo……….

Leave a Reply

Your email address will not be published. Required fields are marked *