Search code examples
mysqlinsert

Mysql-If I insert multiple values in a column of a table simultaneously ,is it possible that the inserting orders of values get change?


I am doing these :

insert into table_name(maxdate) values 
((select max(date1) from table1)), -- goes in row1
((select max(date2) from table2)), -- goes in row2
.
.
.
((select max(date500) from table500));--goes in row500

is it possible that while insertion , order of inserting might get change ?.Eg when i will do

select maxdate from table_name limit 500;

i will get these date1 date2 . . date253 date191 ...date500


Solution

  • Short answer:

    No, not possible.

    If you want to double check :

    mysql> create table letest (f1 varchar(50), f2 varchar(50));
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> insert into letest (f1,f2) values 
    ( (SELECT SLEEP(5)), 'first'), 
    ( (SELECT SLEEP(1)), 'second');
    Query OK, 2 rows affected, 1 warning (6.00 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    
    mysql> select * from letest;
    +------+--------+
    | f1   | f2     |
    +------+--------+
    | 0    | first  |
    | 0    | second |
    +------+--------+
    2 rows in set (0.00 sec)
    

    mysql>

    SLEEP(5) is the first row to be inserted after 5 seconds,

    SLEEP(1) is the second row to be inserted after 5+1 seconds

    that is why query takes 6 seconds.

    The warning that you see is

    mysql> show warnings;
    +-------+------+-------------------------------------------------------+
    | Level | Code | Message                                               |
    +-------+------+-------------------------------------------------------+
    | Note  | 1592 | Statement may not be safe to log in statement format. |
    +-------+------+-------------------------------------------------------+
    1 row in set (0.00 sec)
    

    This can affect you only if you are using a master-slave setup, because the replication binlog will not be safe. For more info on this http://dev.mysql.com/doc/refman/5.1/en/replication-rbr-safe-unsafe.html

    Later edit: Please consider a comment if you find this answer not usefull.