In this blog, we are going to learn a few good habits that we can consider while working with MySQL to improve performance & troubleshoot, as shown below.
Do not use the same stored procedure & function parameter name as the WHERE clause field name
It will respond with all the records of the query because MySQL interprets the field value as a parameter value, which is similar to 1=1.
It will respond with all the records of the query because MySQL interprets the field value as a parameter value, which is similar to 1=1.
Example
- -- Bad
- CREATE PROCEDURE `getPersonById`(IN id INT(10))
- BEGIN
- -- return all record instead
- SELECT id,name FROM person WHERE id = id;
- END
- -- Good
- CREATE PROCEDURE getPersonById(IN personId INT(10))
- BEGIN
- SELECT id,name FROM person WHERE id = personId;
- END
Use same data-type in WHERE clause
It will impact the performance because MySQL holds extra memory for the type conversion.
It will impact the performance because MySQL holds extra memory for the type conversion.
Example
- -- Bad
- SELECT name FROM person WHERE id = '1001';
- -- Good
- SELECT name FROM person WHERE id = 1001;
Use EXISTS clause
It will improve the response time, where the need is logic based on the existence of the record in MySQL.
It will improve the response time, where the need is logic based on the existence of the record in MySQL.
Example
- -- Bad
- IF(SELECT COUNT(*) FROM person) > 0;
- -- Good
- IF EXISTS(SELECT 1 FROM person);

Join the conversation! Your thoughts help the community grow.