Home > Software engineering >  How to reorder rows in a table SQL
How to reorder rows in a table SQL

Time:03-01

just wondering how to reorder rows in this table? I want to have 2015 through 2019 ASCENDING as happiness_rank increases, but 2015 automatically goes to the bottom of the table.

I have tried using

UPDATE table_name ORDER BY happiness_rank;

but that doesn't work, and similarly ALTER TABLE doesn't seem to work either. I know I can do it with SELECT but that doesn't save the table, and when I try to do UPDATE with SELECT and ORDER BY it doesn't work.

h_score happiness_rank economy_gdp_per_capita
2 1.52733
4 1.56497955322266
5 1.420
6 1.452
2015 1 1.39651

CodePudding user response:

SELECT query is always used while reading table, so the info about how your tables is stored in SQL is pointless to you. If I am missing something, please tell me as even during export - you will use SELECT query.

CodePudding user response:

You can do one of the following according to your needs:

  1. If your table does not have any Indexes or Foreign Keys then simply use ALTER

    ALTER TABLE tablename ORDER BY happiness_rank ASC;
    

However, it does not make sense to order them on insert. I wouldn't do this. (Not Recommended)

  1. Add a new column with datatype integer which is sorted ASC and set it as the primary key. Usually, this is the column that has some unique ID and is an auto-generated sequence. (Recommended)
  • Related