HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

INSERT data on MySQL to specific position based on its value (similar to ORDER BY)

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
orderinsertpositionvaluemysqlitssimilarbasedspecificdata

Problem

I have a MySQL table with 3 columns for simplicity sake:

Datename     |Date    |Name
-------------+--------+-----
30/06/15test |30/06/15|test
30/06/15other|30/06/15|other


Note: Column Datename is unique

I would like all new data to be inserted into the table based on its value.

Example:

  • If the Date is 29/06/15, it would be inserted at bottom of table.



  • If the Date is 01/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 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.