How can two seemingly identical databases return results sorted by different columns?












0















I've got a single query



SELECT r.id
, r.account_id
, r.name
, r.bucket_id
, r.description
, r.development
, r.created_at
, r.priority
FROM realms r
WHERE r.account_id = 3;


I run it on two different tables with the same indexes, and one result is sorted by r.id and r.created_at (same order either way), and the other is sorted by r.name. How can this be?



Looking at it through the table inspector in MySQL Workbench, the indexes for both are:



+---------------------------+-------+-----+-----------------+
| key |Type |Uni | Columns |
+ --------------------------+-------+-----+-----------------+
| PRIMARY | BTREE | YES | id |
| realms_account_id_name_UQ | BTREE | YES | account_id,name |
| realms_account_id_IX | BTREE | NO | account_id |
| realms_bucket_id_IX | BTREE | NO | bucket_id |
+---------------------------+-------+-----+-----------------+


I thought it was the indexes that decided what order rows came in, and the screen doesn't even blink when I switch between the two. If the primary key for both of them is id why does one show results ordered by name?










share|improve this question

























  • Rows in sql tables have no inherent order, so the question is meaningless

    – Strawberry
    Nov 28 '18 at 22:17






  • 1





    Let's turn "meaningless" into a lesson on using ORDER BY and understanding how indexes do work.

    – Rick James
    Nov 28 '18 at 22:19
















0















I've got a single query



SELECT r.id
, r.account_id
, r.name
, r.bucket_id
, r.description
, r.development
, r.created_at
, r.priority
FROM realms r
WHERE r.account_id = 3;


I run it on two different tables with the same indexes, and one result is sorted by r.id and r.created_at (same order either way), and the other is sorted by r.name. How can this be?



Looking at it through the table inspector in MySQL Workbench, the indexes for both are:



+---------------------------+-------+-----+-----------------+
| key |Type |Uni | Columns |
+ --------------------------+-------+-----+-----------------+
| PRIMARY | BTREE | YES | id |
| realms_account_id_name_UQ | BTREE | YES | account_id,name |
| realms_account_id_IX | BTREE | NO | account_id |
| realms_bucket_id_IX | BTREE | NO | bucket_id |
+---------------------------+-------+-----+-----------------+


I thought it was the indexes that decided what order rows came in, and the screen doesn't even blink when I switch between the two. If the primary key for both of them is id why does one show results ordered by name?










share|improve this question

























  • Rows in sql tables have no inherent order, so the question is meaningless

    – Strawberry
    Nov 28 '18 at 22:17






  • 1





    Let's turn "meaningless" into a lesson on using ORDER BY and understanding how indexes do work.

    – Rick James
    Nov 28 '18 at 22:19














0












0








0








I've got a single query



SELECT r.id
, r.account_id
, r.name
, r.bucket_id
, r.description
, r.development
, r.created_at
, r.priority
FROM realms r
WHERE r.account_id = 3;


I run it on two different tables with the same indexes, and one result is sorted by r.id and r.created_at (same order either way), and the other is sorted by r.name. How can this be?



Looking at it through the table inspector in MySQL Workbench, the indexes for both are:



+---------------------------+-------+-----+-----------------+
| key |Type |Uni | Columns |
+ --------------------------+-------+-----+-----------------+
| PRIMARY | BTREE | YES | id |
| realms_account_id_name_UQ | BTREE | YES | account_id,name |
| realms_account_id_IX | BTREE | NO | account_id |
| realms_bucket_id_IX | BTREE | NO | bucket_id |
+---------------------------+-------+-----+-----------------+


I thought it was the indexes that decided what order rows came in, and the screen doesn't even blink when I switch between the two. If the primary key for both of them is id why does one show results ordered by name?










share|improve this question
















I've got a single query



SELECT r.id
, r.account_id
, r.name
, r.bucket_id
, r.description
, r.development
, r.created_at
, r.priority
FROM realms r
WHERE r.account_id = 3;


I run it on two different tables with the same indexes, and one result is sorted by r.id and r.created_at (same order either way), and the other is sorted by r.name. How can this be?



Looking at it through the table inspector in MySQL Workbench, the indexes for both are:



+---------------------------+-------+-----+-----------------+
| key |Type |Uni | Columns |
+ --------------------------+-------+-----+-----------------+
| PRIMARY | BTREE | YES | id |
| realms_account_id_name_UQ | BTREE | YES | account_id,name |
| realms_account_id_IX | BTREE | NO | account_id |
| realms_bucket_id_IX | BTREE | NO | bucket_id |
+---------------------------+-------+-----+-----------------+


I thought it was the indexes that decided what order rows came in, and the screen doesn't even blink when I switch between the two. If the primary key for both of them is id why does one show results ordered by name?







mysql sorting indexing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '18 at 22:14









Strawberry

26.8k83250




26.8k83250










asked Nov 28 '18 at 21:01









Christopher WaughChristopher Waugh

677




677













  • Rows in sql tables have no inherent order, so the question is meaningless

    – Strawberry
    Nov 28 '18 at 22:17






  • 1





    Let's turn "meaningless" into a lesson on using ORDER BY and understanding how indexes do work.

    – Rick James
    Nov 28 '18 at 22:19



















  • Rows in sql tables have no inherent order, so the question is meaningless

    – Strawberry
    Nov 28 '18 at 22:17






  • 1





    Let's turn "meaningless" into a lesson on using ORDER BY and understanding how indexes do work.

    – Rick James
    Nov 28 '18 at 22:19

















Rows in sql tables have no inherent order, so the question is meaningless

– Strawberry
Nov 28 '18 at 22:17





Rows in sql tables have no inherent order, so the question is meaningless

– Strawberry
Nov 28 '18 at 22:17




1




1





Let's turn "meaningless" into a lesson on using ORDER BY and understanding how indexes do work.

– Rick James
Nov 28 '18 at 22:19





Let's turn "meaningless" into a lesson on using ORDER BY and understanding how indexes do work.

– Rick James
Nov 28 '18 at 22:19












1 Answer
1






active

oldest

votes


















1














If you don't have an ORDER BY clause in your SELECT, the system can do whatever it feels like. Period. Full stop.



Now, I will explain what probably happened.



First, the Optimizer will analyze the indexes, the datatypes, the statistics, etc, and decide how to execute the query. You can get a peek into this operation by doing EXPLAIN SELECT .... It will say which index it is likely to use.



I see two indexes that are reasonable -- the two beginning with account_id. Either one would be fine. Probably the Optimizer had slightly different statistics on the two machine, leading it to pick one index on one machine, and the other on the other.



Analysis of using INDEX(account_id, name). That index is an ordered list of the pairs of account_ids and names. On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by name.



Analysis of using INDEX(account_id). InnoDB, in order to find the data, tacks the PRIMARY KEY columns onto each secondary index. So, that index is effectively INDEX(account_id, id). On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by id.



A third possibility is common and is worth noting. If there are lots of rows with account_id = 3, the Optimizer would decide to eschew the index and simply read the data. Since the data is stored according to the PRIMARY KEY, it would, again, deliver the rows in id order (but for a radically different reason).






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53528025%2fhow-can-two-seemingly-identical-databases-return-results-sorted-by-different-col%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    If you don't have an ORDER BY clause in your SELECT, the system can do whatever it feels like. Period. Full stop.



    Now, I will explain what probably happened.



    First, the Optimizer will analyze the indexes, the datatypes, the statistics, etc, and decide how to execute the query. You can get a peek into this operation by doing EXPLAIN SELECT .... It will say which index it is likely to use.



    I see two indexes that are reasonable -- the two beginning with account_id. Either one would be fine. Probably the Optimizer had slightly different statistics on the two machine, leading it to pick one index on one machine, and the other on the other.



    Analysis of using INDEX(account_id, name). That index is an ordered list of the pairs of account_ids and names. On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by name.



    Analysis of using INDEX(account_id). InnoDB, in order to find the data, tacks the PRIMARY KEY columns onto each secondary index. So, that index is effectively INDEX(account_id, id). On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by id.



    A third possibility is common and is worth noting. If there are lots of rows with account_id = 3, the Optimizer would decide to eschew the index and simply read the data. Since the data is stored according to the PRIMARY KEY, it would, again, deliver the rows in id order (but for a radically different reason).






    share|improve this answer




























      1














      If you don't have an ORDER BY clause in your SELECT, the system can do whatever it feels like. Period. Full stop.



      Now, I will explain what probably happened.



      First, the Optimizer will analyze the indexes, the datatypes, the statistics, etc, and decide how to execute the query. You can get a peek into this operation by doing EXPLAIN SELECT .... It will say which index it is likely to use.



      I see two indexes that are reasonable -- the two beginning with account_id. Either one would be fine. Probably the Optimizer had slightly different statistics on the two machine, leading it to pick one index on one machine, and the other on the other.



      Analysis of using INDEX(account_id, name). That index is an ordered list of the pairs of account_ids and names. On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by name.



      Analysis of using INDEX(account_id). InnoDB, in order to find the data, tacks the PRIMARY KEY columns onto each secondary index. So, that index is effectively INDEX(account_id, id). On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by id.



      A third possibility is common and is worth noting. If there are lots of rows with account_id = 3, the Optimizer would decide to eschew the index and simply read the data. Since the data is stored according to the PRIMARY KEY, it would, again, deliver the rows in id order (but for a radically different reason).






      share|improve this answer


























        1












        1








        1







        If you don't have an ORDER BY clause in your SELECT, the system can do whatever it feels like. Period. Full stop.



        Now, I will explain what probably happened.



        First, the Optimizer will analyze the indexes, the datatypes, the statistics, etc, and decide how to execute the query. You can get a peek into this operation by doing EXPLAIN SELECT .... It will say which index it is likely to use.



        I see two indexes that are reasonable -- the two beginning with account_id. Either one would be fine. Probably the Optimizer had slightly different statistics on the two machine, leading it to pick one index on one machine, and the other on the other.



        Analysis of using INDEX(account_id, name). That index is an ordered list of the pairs of account_ids and names. On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by name.



        Analysis of using INDEX(account_id). InnoDB, in order to find the data, tacks the PRIMARY KEY columns onto each secondary index. So, that index is effectively INDEX(account_id, id). On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by id.



        A third possibility is common and is worth noting. If there are lots of rows with account_id = 3, the Optimizer would decide to eschew the index and simply read the data. Since the data is stored according to the PRIMARY KEY, it would, again, deliver the rows in id order (but for a radically different reason).






        share|improve this answer













        If you don't have an ORDER BY clause in your SELECT, the system can do whatever it feels like. Period. Full stop.



        Now, I will explain what probably happened.



        First, the Optimizer will analyze the indexes, the datatypes, the statistics, etc, and decide how to execute the query. You can get a peek into this operation by doing EXPLAIN SELECT .... It will say which index it is likely to use.



        I see two indexes that are reasonable -- the two beginning with account_id. Either one would be fine. Probably the Optimizer had slightly different statistics on the two machine, leading it to pick one index on one machine, and the other on the other.



        Analysis of using INDEX(account_id, name). That index is an ordered list of the pairs of account_ids and names. On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by name.



        Analysis of using INDEX(account_id). InnoDB, in order to find the data, tacks the PRIMARY KEY columns onto each secondary index. So, that index is effectively INDEX(account_id, id). On the machine where it used that index, it drilled down the BTree index to the first entry for account_id = 3, then scanned forward. This gave you the results ordered by id.



        A third possibility is common and is worth noting. If there are lots of rows with account_id = 3, the Optimizer would decide to eschew the index and simply read the data. Since the data is stored according to the PRIMARY KEY, it would, again, deliver the rows in id order (but for a radically different reason).







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 28 '18 at 22:15









        Rick JamesRick James

        70.4k564104




        70.4k564104
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53528025%2fhow-can-two-seemingly-identical-databases-return-results-sorted-by-different-col%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)