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?
Of course the easiest answer is to use
ORDER BYwhen 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 useORDER BY.If your table uses the InnoDB storage engine, the default order when you query without using
ORDER BYis 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.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:
Then restore the table. The data will reload in primary key order. Then subsequently the default order when you query without using
ORDER BYwill 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.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.
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
LIMITonly 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.