[SOLVED] Mysql Cursor not sorting result in correct order

Issue

This is an abstraction of my original code as it´ll be easier to read for you guys.

I´m new to Mysql Storage procedures and from Cursors.

Whats happening is that Cursor is not bringing the results properly sorted as I set the ORDER BY instruction on the query.

Here´s all the structure and data for the tables to reproduce the issue.

Log Table :

    DROP TABLE IF EXISTS `log`;
    CREATE TABLE `log` (
      `key` text NOT NULL,
      `value` text NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Test Table :

    DROP TABLE IF EXISTS `test1`;
    CREATE TABLE `test1` (
      `ID` bigint(8) unsigned NOT NULL AUTO_INCREMENT,
      `price` float(16,8) NOT NULL,
      PRIMARY KEY (`ID`),
      KEY `price` (`price`)
    ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;

Test table data :

    INSERT INTO `test1` (`price`)
    VALUES (100),(200),(300),(400),(300),(200),(100);

Query:

    SELECT *
    FROM `test1`
    ORDER BY price DESC;

Expected results works fine with query directly:

  • 4 – 400.00000000
  • 5 – 300.00000000
  • 3 – 300.00000000
  • 6 – 200.00000000
  • 2 – 200.00000000
  • 7 – 100.00000000
  • 1 – 100.00000000

Stored Procedure

    DROP PROCEDURE IF EXISTS `test_proc1`;
    DELIMITER ;;

    CREATE DEFINER=`root`@`localhost` PROCEDURE `test_proc1`()
    BEGIN

      DECLARE done INT DEFAULT 0;
      DECLARE ID BIGINT(8);
      DECLARE price FLOAT(16,8);

      DECLARE cur1 CURSOR FOR
      SELECT * FROM `test1` ORDER BY price DESC; #Exact Query

      DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

      START TRANSACTION;
        OPEN cur1;
        #Cleaning log
        TRUNCATE `log`;
        read_loop:
        LOOP
          FETCH cur1 INTO ID,price;
          IF done = 1 THEN
            LEAVE read_loop;
          END IF;
          #Inserting data to log
          INSERT INTO `log`
          VALUES (ID,price);
        END LOOP read_loop;

        CLOSE cur1;
      COMMIT;

    #Bring log for result
    SELECT * FROM log;

    END;;
    DELIMITER ;

Call procedure

    CALL test_proc1();

The CURSOR has exactly the same query as I posted at the top, you can check that on the Stored Procedure. But when I loop through it, I get another order.

  • 15 100.00000000
  • 21 100.00000000
  • 16 200.00000000
  • 20 200.00000000
  • 17 300.00000000
  • 19 300.00000000
  • 18 400.00000000

Whats going on? Can somebody help me on this?
I also tried nesting the query like this with no fix at all.

SELECT * FROM(
SELECT *
FROM `test1`
ORDER BY price DESC) AS tmp_tbl

Solution

Looks like you have a “variable collision”. Variable price is used instead of table column with that exact name. Change variable name, or use table alias like this:

SELECT * FROM `test1` as `t` ORDER BY `t`.`price` DESC;

Answered By – BlitZ

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.