Madan Sapkota
Madan Sapkota

Reputation: 26091

MySQL performance comparison between Stored Procedure and Prepared Statements

Here is MySQL prepared statement

SELECT 
    ag.`attendance_type`,
    ag.`description`,
    COUNT(a.`attendance`) attendance_count 
FROM
    `ems_attendance` a 
    RIGHT JOIN `ems_att_group` ag 
        ON ag.`id` = a.`attendance` 
        AND a.`added_date` BETWEEN '2011-06-01' 
        AND '2011-06-17' 
        AND a.`users_id` = '9' 
GROUP BY a.`attendance` 
ORDER BY ag.`id`;

and equivalent Store Procedure

DELIMITER $$

DROP PROCEDURE IF EXISTS `users_attendance_report` $$

CREATE PROCEDURE `users_attendance_report` (
    IN users_id INT,
    IN start_date DATE,
    IN end_date DATE
) 
BEGIN
    SELECT 
        ag.`attendance_type`,
        ag.`description`,
        COUNT(a.`attendance`) attendance_count 
    FROM
        `ems_attendance` a 
        RIGHT JOIN `ems_att_group` ag 
            ON ag.`id` = a.`attendance` 
            AND a.`added_date` BETWEEN start_date 
            AND end_date 
            AND a.`users_id` = users_id 
    GROUP BY a.`attendance` 
    ORDER BY ag.`id` ;
END $$

DELIMITER;

After I run the query both outputs the same results.

Array
(
    [0] => stdClass Object
        (
            [attendance_type] => present
            [description] => Present
            [attendance_count] => 10
        )

    [1] => stdClass Object
        (
            [attendance_type] => absent
            [description] => Absent
            [attendance_count] => 2
        )

    [2] => stdClass Object
        (
            [attendance_type] => other
            [description] => Other
            [attendance_count] => 0
        )

    [3] => stdClass Object
        (
            [attendance_type] => dayoff
            [description] => Day Off
            [attendance_count] => 2
        )

)

I closely look into the execution time, both are same. When and where one is better and faster than another?

Upvotes: 2

Views: 4379

Answers (2)

Abhay
Abhay

Reputation: 6645

I think in your case it doesn't matter if you run the query standalone or as part of stored procedure. A procedure is nice in situations where you've got a query batch to perform. Therefore, for your query it's best to run standalone.

Upvotes: 2

Bohemian
Bohemian

Reputation: 425043

"Faster" and "better" are not necessarily aligned. Please see this recent similar SO question, and consider these attributes of a solution:

  • maintainable (readable, skills requirements - who can work on this code)
  • testable
  • releasable
  • flexible
  • portable

Generally speaking, stored procedures are faster, but fail on every other metric.

Upvotes: 4

Related Questions