Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Multiple Filter - Optimal Way

How do you implement this simple scenario with the least possible cost (SQL) ?

(implement a stored procedure supporting all combinations of the filters applied.)

Table

    name | dateOfbirth | phone | email
     N1  | 01-01-1992  | P1    | E1
     N2  | 12-08-1976  | P2    | E2
     N3  | 09-11-1989  | P3    | E3
     N4  | 04-06-1991  | P4    | E4

    Filter 
    [x] Name
    [x] dateOfbirth 
    [x] phone
    [x] email

After seeing SQL queries and filters implemented for many years and in many ways.

I think it's high time for me to refresh.

References

  1. http://bit.ly/RYHzaF

  2. http://bit.ly/QyX103

Mark / Correct this question if found as duplicate

like image 680
Umesh .A Bhat Avatar asked Nov 23 '12 09:11

Umesh .A Bhat


1 Answers

Whenever I do optional filters, I choose some data that will represent all data, and then use something like this:

SELECT name, dateOfbirth, phone, email
  FROM Table
 WHERE (@a_name  = '' or name = @a_name)
   AND (@a_date  = '1900-01-01' or dateOfbirth = @a_date)
   AND (@a_phone = '' or phone = @a_phone)
   AND (@a_email = '' or email = @a_email)
like image 74
Philipi Willemann Avatar answered Sep 21 '22 15:09

Philipi Willemann