18

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.

4
  • 4
    You don't change data when you sort generally, data tables are never guarnateed to return data in a particular order.
    – HLGEM
    Apr 9, 2012 at 20:59
  • 2
    Why would you want to save database tables sorted?
    – MarioDS
    Apr 9, 2012 at 21:02
  • @MarioDeSchaepmeester It's a long history. In brief I need that for my application.
    – Sabre
    Apr 9, 2012 at 21:05
  • I don't think there is a way to effectively sort database tables without saving the sorted ones as a copy or using a very complex or series of update statement(s). Your best bet is to write a stored procedure or save the query that sorts the table. That way you just have to execute that to get the sorted table. You won't muck up your database that way. I can still see the value of reading it sorted, but saving it sorted makes no sense. So what I'm saying is you should "save the sorted read".
    – MarioDS
    Apr 9, 2012 at 21:09

7 Answers 7

30

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.

3
  • 1
    @Sabre & Umbrella Table implemenaton/storage has order but a table is an unordered abstraction. The only way to ever get order in a query is an outermost ORDER BY.
    – philipxy
    Aug 28, 2017 at 21:23
  • How is this so upvoted? If the table has an autogenerated PK then this code probably replaces the original table with one in which the PK order (initially) is consistent with ordering by the Name column, but SQL has no sense of sorting a table itself, only sorting results. Mar 20, 2019 at 19:11
  • It answers the question precisely. The problem you describe is with the question, where the asker is trying to do something we generally don't do -- reorder rows on the disk. I can't think of a use case for that, because we all just use ORDER BY on our result sets, but, that's apparently what the question was, and this is how you do it.
    – Umbrella
    Mar 22, 2019 at 17:38
4

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 
0
3

You can use alter table command which is simpler.

mysql> ALTER TABLE games ORDER BY name asc;

That's all !

1
  • Maybe this works in mysql, but definitely not t-sql. Would be pretty convenient!
    – Lenny K
    Mar 23, 2018 at 14:41
1

it is simple. just use a few codes. I have tried this and it is working. first create a temporary table while sorting values at the same time.

    create table new as select * from games order by name;

and then drop the games table using,

    drop table games;

now create games table again with same properties and data as in new (where sorting here is an optional) using,

    create table games as select * from new order by name;

now drop the temp table 'new'

    drop table new;

now check your table. it must be sorted out.

0

you can sort on two fields at the same time.

SELECT *
FROM games
ORDER BY id DESC, name ASC

I don't understand what you mean by save changes in the table. The ORDER BY, is just changing the display that you are looking at it doesn't change the data in the table unless you perform an UPDATE.

If you are unfamiliar with SQL, there are a lot of tutorials online that can help:

SQL Course

Beginner SQL Tutorial

SQL Tutorial - Learn SQL

Edit based on the comments, this can be done in one step:

create table #temp
(
    id int,
    name varchar(50),
    somedesc varchar(50)
)

insert into #temp values (1, 'best', 'desc1')
insert into #temp values (2, 'worth', 'desc2')
insert into #temp values (3, 'good', 'desc3')

update t1
SET t1.id = t2.rn
    , t1.somedesc = t1.somedesc
FROM #temp t1
JOIN 
(
    select id, name, somedesc, row_number() over(order by name, id) as rn
    from #temp 
) t2
on t1.id = t2.id

select *
from #temp
order by id

drop table #temp
3
  • What you're saying is correct, of course, but notice what he wants done in his example - the Id column stays the same.
    – cha0site
    Apr 9, 2012 at 21:01
  • @cha0site you are right. When I sort two fields in that way I got no changes in table
    – Sabre
    Apr 9, 2012 at 21:03
  • @cha0site you are right, i misunderstood the OP. I have updated my answer
    – Taryn
    Apr 9, 2012 at 22:08
0

This is my fix... stupid simple:

  1. Extract to temp table

SELECT SortKeyValue (add any other fixed values, just don't include the existing sequence) INTO #Temp FROM SourceTable;

  1. Empty the table:

TRUNCATE TABLE SourceTable

  1. Reinsert:

INSERT INTO SourceTable (SortKeyValue, DisplayOrder (plus other fields)) SELECT SortKeyValue, ROW_NUMBER() OVER (ORDER BY SortKeyValue) AS DispOrd (plus other fields) FROM #Temp;

  1. Done!
-3

SQL> SELECT * FROM games ORDER BY ID,NAME;

1
  • 1
    Could you please elaborate more your answer adding a little more description about the solution you provide?
    – abarisone
    Oct 14, 2015 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.