I'm completely new to sql and can't do that myself. So I need your help. I want to sort values in column and then save changes. But I don't know how to do that.
Table looks like that:
Id | Name | SomeDescription
---------------------------
1 |Best | Description1
2 |Worth | Description2
3 |Good | Description3
I want to get something like that:
Id | Name | SomeDescription
---------------------------
1 |Best | Description1
2 |Good | Description3
3 |Worth | Description2
So I need to sort "id" and "name" columns.
I use following statement to sort values of "name" column:
SELECT * FROM games ORDER BY name ASC
But how can I sort the values of id column and save changes in table? Please, help.
You would want to select the table's contents into a temp table, and create a sort order column that's correct at that time... Then update the original sort order using that. I eventually resolved this in SSMS - not a fully "SQL" solution but it did the job I needed done.
UPDATE t SET id = id + 1 ORDER BY id DESC; You can also perform UPDATE operations covering multiple tables. However, you cannot use ORDER BY or LIMIT with a multiple-table UPDATE .
You Can Use ORDER BY And LIMIT Within UPDATE And DELETE Statements In MySQL 5.6.
If you want to sort some of the data in ascending order and other data in descending order, then you would have to use the ASC and DESC keywords. SELECT * FROM table ORDER BY column1 ASC, column2 DESC; That is how to use the ORDER BY clause in SQL to sort data in ascending order.
You would have to use a second table
create a new table games2
with the same structure as your games
table, making sure the ID is auto-incrementing
CREATE TABLE `games2` LIKE `games`;
copy the data, sorted, into games2
INSERT INTO `games2` (`Name`, `SomeDescription`) SELECT `Name`, `SomeDescription` FROM `games` ORDER BY `Name`
drop or move the old table
-- DROP TABLE `games`;
-- or
RENAME TABLE `games` TO `games1`;
rename new table to old name
RENAME TABLE `games2` TO `games`;
These steps will result in what you want.
You can use the ROW_NUMBER ranking function to renumber the rows.
SELECT UnsortedId = id
, SortedId = ROW_NUMBER() OVER (ORDER BY g.name, g.id)
FROM games
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With