Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert sequential number in MySQL

Tags:

sql

mysql

I added an empty column to a table and now I want to insert sequential numbers to its rows. Is it possible to do it using SQL?

like image 346
Rendicahya Avatar asked Jan 14 '12 12:01

Rendicahya


People also ask

How do I create a sequence number in MySQL?

The simplest way for creating a sequence in MySQL is by defining the column as AUTO_INCREMENT during table creation, which should be a primary key column.

How do you add sequential numbers in SQL?

To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row.

What is sequence how it is generated in MySQL?

A sequence is a set of integers 1, 2, 3, ... that are generated in order on a specific demand. Sequences are frequently used in the databases because many applications require each row in a table to contain a unique value and sequences provide an easy way to generate them.

What is Nextval in MySQL?

NEXTVAL returns the next sequence number, and CURRVAL returns the current sequence number. NEXTVAL(N) returns n unique sequence numbers. NEXTVAL(N) can be used only in select sequence.


2 Answers

Run the following queries to have incremented value in yourField column:

SELECT @i:=0; UPDATE yourTable SET yourField = @i:=@i+1; 
like image 146
dfsq Avatar answered Sep 21 '22 23:09

dfsq


As I said in comments you can update every row with its row number,

Here is a link to how to calculate rownum in MySQL.

To rephrase:

update player,        (select @rownum:=@rownum+1 ‘rank’, p.*          from player p,         (SELECT @rownum:=0) r          order by score desc) player1  set thatColumn= rank  where player.id = player1.id 
like image 22
Jahan Zinedine Avatar answered Sep 20 '22 23:09

Jahan Zinedine