Albert Renshaw Albert Renshaw - 8 days ago 6
MySQL Question

Create a new table with rows in order of ascending

I have a database that has a table that has rows with a value "ID" that changes a lot.
It may be like:



row1.ID = 5,
row2.ID = 47,
row3.ID = -6,
etc.


Completely random order.
Can I make another table when I load a page that will take all of the rows in the first table and create a second table arranging them in order of the "ID" value.
So the second table would be:


row1.ID = -6,
row2.ID = 5,
row3.ID = 47,
etc.


Does that make sense?

Answer

Of course the easiest answer is to use ORDER BY when you query your table, and then you can control the order of rows in the query result set. But I assume you mean you want the "natural" order of rows to be in numeric order when you don't use ORDER BY.

If your table uses the InnoDB storage engine, the default order when you query without using ORDER BY is always the order of the primary key. That's because InnoDB stores tables as a clustered index by primary key. So if ID is your primary key, and you convert your table to InnoDB, then you can rely on its natural order.

mysql> ALTER TABLE MyTable ENGINE=InnoDB;

If your table is stored as MyISAM, the natural order is the order rows are physical stored in the data file, which has nothing to do with the order of the values or even the order in which you created the rows.

For these tables, you can dump your table in primary key order with:

$ mysqldump --order-by-primary databasename tablename > table.sql

Then restore the table. The data will reload in primary key order. Then subsequently the default order when you query without using ORDER BY will be by ID. But this doesn't prevent the rows from getting out of order again as the values change.


Re your comments:

The best option would be to use WHERE. That's efficient because it can use the clustered index to find the correct row very quickly.

SELECT * FROM MyTable WHERE ID = 6;

The alternative, which is less efficient but still better than returning all the rows, is to pick some row or rows by their position in the stream, instead of by their value.

SELECT * FROM MyTable LIMIT 1 OFFSET 5;

The first number is how many rows you want, the second number is how many rows to skip first.

Normally you'd want to use LIMIT only after specifying an order, otherwise you could get the rows in some meaningless order, and the fifth row wouldn't be any more desirable than the first row.

SELECT * FROM MyTable ORDER BY created_at LIMIT 1 OFFSET 5;