Search code examples
mysqlmysql-workbenchsql-insertcreate-table

MySQL CREATE and INSERT yields an unordered sequence of records when the table is populated


Please, I acknowledge my #newbie state. Eery help is well appreciated.

So I created a table n_s as follows

CREATE TABLE n_s (
    state_id INT PRIMARY KEY AUTO_INCREMENT,
    state_name VARCHAR(50),
    state_capital VARCHAR(50),
    faac DECIMAL(16,2)
);

Then populated it like so

INSERT INTO n_s(state_name, state_capital, faac) VALUES ('Ab','Um',520),
('Ad','Yl',483),
('Akm','Uy',171);

At this point, I got a nice-looking table.

enter image description here

The problem then arises when I want to populate this table with new values. First, I did this: ALTER TABLE n_s ADD g_usd DECIMAL(30,2); and it worked fine. But then I tried populating the table with

INSERT INTO n_s(g_usd)  VALUES
(6073488295.68),
(5815471618.60),
(13267272645.16);

The result SELECT * FROM n_s; is the following "unordered 😁" table:

the ugly table

However, what I really want to achieve using the above steps is:

Expectation


Solution

  • Found a solution, finally.

    I only had to replace

    INSERT INTO n_s(g_usd)  VALUES
    (6073488295.68),
    (5815471618.60),
    (13267272645.16);
    

    with

    INSERT INTO n_s(state_id, g_usd)  VALUES
    (1, 6073488295.68),
    (2, 5815471618.60),
    (3, 13267272645.16) AS gs
    ON DUPLICATE KEY UPDATE g_usd = gs.g_usd;
    

    And it works fine now.