0

I have a table structure like this :

-----------------------------------
ID  |    NAME   |   SORTED_ID
-----------------------------------
1   |    B      |      
2   |    D      |
3   |    A      | 
4   |    C      |

Using a single SQL query i want to update the SORTED_ID column like this, based on the sorted order.

-----------------------------------
ID  |    NAME   |   SORTED_ID
-----------------------------------
1   |    B      |      2
2   |    D      |      4
3   |    A      |      1
4   |    C      |      3

How can i do so?

Naveen
  • 7,944
  • 12
  • 78
  • 165

1 Answers1

0

In SQLite, this is a bit painful. Here is one method using a correlated subquery:

update t
    set sorted_id = (select count(*)
                     from t t2
                     where t2.name <= t.name
                    );

Note: this is expensive on mediumish tables (those more than a thousand rows or so).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786