'How to reorder rows in a table SQL
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 |
Solution 1:[1]
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.
Solution 2:[2]
You can do one of the following according to your needs:
If your table does not have any Indexes or Foreign Keys then simply use
ALTERALTER 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)
- 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Divyesh Katariya |
| Solution 2 |
