Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort values in columns and update table?

Tags:

sql

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.

like image 243
Sabre Avatar asked Apr 09 '12 20:04

Sabre


People also ask

How do you sort and UPDATE in SQL?

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.

Can we use ORDER BY with UPDATE?

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 .

Can you have an ORDER BY in an UPDATE statement SQL?

You Can Use ORDER BY And LIMIT Within UPDATE And DELETE Statements In MySQL 5.6.

How do you UPDATE a column in ascending order in SQL?

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.


2 Answers

You would have to use a second table

  1. 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`;
    
  2. copy the data, sorted, into games2

    INSERT INTO `games2` (`Name`, `SomeDescription`) SELECT `Name`, `SomeDescription` FROM `games` ORDER BY `Name`
    
  3. drop or move the old table

    -- DROP TABLE `games`;
    -- or
    RENAME TABLE `games` TO `games1`;
    
  4. rename new table to old name

    RENAME TABLE `games2` TO `games`;
    

These steps will result in what you want.

like image 65
Umbrella Avatar answered Oct 04 '22 22:10

Umbrella


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 
like image 21
Anthony Faull Avatar answered Oct 04 '22 20:10

Anthony Faull