I need to display a list of records from a database table ordered by some numeric column. The table looks like this:
CREATE TABLE items ( position int NOT NULL, name varchar(100) NOT NULL, ); INSERT INTO items (position, name) VALUE (1, 'first'), (5, 'second'), (8, 'third'), (9, 'fourth'), (15, 'fifth'), (20, 'sixth');
Now, the order of the list should change according to a parameter provided by the user. This parameter specifies which record comes first like this:
position = 0 order should be = 1, 5, 8, 9, 15, 20 position = 1 order should be = 20, 1, 5, 8, 9, 15 position = 2 order should be = 15, 20, 1, 5, 8, 9
In other words the last record becomes the first and so on. Can you think of a way to do this in SQL?
I’m using MySQL but an example in any SQL database will do.
Thanks
See how this works for you. Uses generic SQL so it should be valid for MySql (untested) as well.
Note: * If the user provided sort index is greater than the row count, the value will wrap to within the valid range. To remove this functionality, remove the ‘% maxrows’ from the ORDER BY.
Results:
SET @user_sort = 0
SET @user_sort = 1
SET @user_sort = 2
SET @user_sort = 9