1

I'm curious how to create table2 of the same structure with the same data as table1, but with order by the column frequency.

Or, the equivalent of this problem is: to change the id of rows in the table properly.

It doesn't matter, whether by ASC, or DESC.

As result, the table1:

**id - name - frequency**

    1 - John - 33
    2 - Paul - 127
    3 - Andy - 74

Should become table2:

**id - name - frequency**

    1 - Paul - 127
    2 - Andy - 74
    3 - John - 33

What's the shortest way to do that?

Also, I would be interesting in the query that's fastest for huge tables (although performance is not so important for me).

double-beep
  • 5,031
  • 17
  • 33
  • 41
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

2 Answers2

2

Like this?

CREATE TABLE b SELECT col FROM a ORDER BY col

Be aware, there is no way to guarantee row order in a database (other than physically). You must always use an ORDER BY.

Reference

Community
  • 1
  • 1
Kermit
  • 33,827
  • 13
  • 85
  • 121
1

For this, you need to create the new id. Here is a MySQL way to do it:

create table table2 as
    select @rn := @rn + 1 as id, name, frequency
    from table1 cross join (select @rn := 0) const
    order by frequency desc
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786