patternsqlMinor
INSERT data on MySQL to specific position based on its value (similar to ORDER BY)
Viewed 0 times
orderinsertpositionvaluemysqlitssimilarbasedspecificdata
Problem
I have a MySQL table with 3 columns for simplicity sake:
Note: Column
I would like all new data to be inserted into the table based on its value.
Example:
Or preferably sorted by
Is this easily achievable, or do I need to just create a page that
Datename |Date |Name
-------------+--------+-----
30/06/15test |30/06/15|test
30/06/15other|30/06/15|otherNote: Column
Datename is uniqueI would like all new data to be inserted into the table based on its value.
Example:
- If the
Dateis29/06/15, it would be inserted at bottom of table.
- If the
Dateis01/07/15, it would be inserted at the top of the table
Or preferably sorted by
Datename column so it will sort by date then name.Is this easily achievable, or do I need to just create a page that
SELECT and ORDER BY?Solution
A table is, by definition, an unordered bag of rows. There is no guarantee that if you say
No ORDER BY is essentially telling the database you don't care about order.
If you do care about order, you need two things:
-
At least one column that can dictate order (an auto increment column, a date/time column populated with now(), or something you manually specify).
-
An actual ORDER BY expression on the outermost part of the query that presents the data (and don't forget to include a tie-breaker, if the first column might not be unique).
SELECT * FROM table you will get the rows back in the same order you inserted. Think about throwing a bunch of popsicle sticks on the ground while blindfolded; now take off the blindfold and tell me which one hit the floor last.No ORDER BY is essentially telling the database you don't care about order.
If you do care about order, you need two things:
-
At least one column that can dictate order (an auto increment column, a date/time column populated with now(), or something you manually specify).
-
An actual ORDER BY expression on the outermost part of the query that presents the data (and don't forget to include a tie-breaker, if the first column might not be unique).
Context
StackExchange Database Administrators Q#105485, answer score: 7
Revisions (0)
No revisions yet.