In this article, we will study some cases where a clause WHERE 1 = 1 or WHERE 1 is useful.
Some database engines such as MySQL show us a WHERE 1 = 1 or WHERE 1 clause when we inspect the content of a table or when we use a template to build a query.
Image 1. MySQL query template with WHERE 1 clause
But, have you ever wondered why? In what case is that type of clause useful? Below we will see a couple of examples where this type of clause is useful.
To build the examples, we will use an Employee table with the following structure and data:
CREATE TABLE `employee` ( |
Script 1. Employee table creation
We can execute the following query to verify the Employee table content:
SELECT * FROM `employee` |
Script 2. Query to retrieve Employee table rows
Result:
Table 1. Content of the Employee table
WHERE 1 = 1 clause first example
For our first example, we are going to create a stored procedure that returns the data of an employee. To locate the employee, the stored procedure will receive two parameters.
CREATE DEFINER=`root`@`localhost` PROCEDURE `search_employee`(emp_id int, emp_gender varchar(10)) |
Script 3. WHERE 1 = 1 clause first example
In this example, we see how using the WHERE 1 = 1 clause, we avoid having to ask for each parameter if it is the first to place the word WHERE. We simply concatenate each parameter with an AND, since we always start the WHERE clause with the comparison 1 = 1.
We can execute the following query to retrieve the employee 10001 data:
CALL `employees_database`.`search_employee`(10001,'M'); |
Script 4. Call to the procedure to obtain employee 10001 data
Result:
Table 2. Employee 10001 data
WHERE 1 = 1 clause second example
In our second example, we will build a procedure that will filter employees by gender. We will use a parameter to indicate the gender to be filtered. If the parameter is empty, it will bring all the employees.
CREATE DEFINER=`root`@`localhost` PROCEDURE `search_employee_by_gender`(emp_gender varchar(10)) |
Script 5. WHERE 1 = 1 clause second example
We can execute the following query if we want to filter the female employees:
CALL `employees_database`.`search_employee_by_gender`('Female'); |
Result:
Table 3. Female employees
0 comments:
Post a Comment