Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recount SQL auto increment ID while keeping the other columns intact

I have a table like this

ID NAME
1 MICHAEL
2 JORDAN
5 DONALD
7 JAYCE
8 ROY
11 JOHN
16 DOE

Is there a way to recount the ID from the beggining so there is a sequel and keeping the others columns intact to be like this:

ID NAME
1 MICHAEL
2 JORDAN
3 DONALD
4 JAYCE
5 ROY
6 JOHN
7 DOE

Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If your MySQL version supports window function, you could use ROW_NUMBER.

Suppose you have the following table:

create table test(
ID int NOT NULL ,
NAME VARCHAR (25)
);

insert into test values 
(1,'MICHAEL'),
(2,'JORDAN'),
(5,'DONALD'),
(7,'JAYCE'),
(8,'ROY'),
(11,'JOHN'),
(16,'DOE');

Using row_number would give:

select ID,NAME, row_number() over(order by ID ASC ) as rownum
from test

Result:

ID    NAME    rownum
1   MICHAEL     1
2   JORDAN      2
5   DONALD      3
7   JAYCE       4
8   ROY         5
11  JOHN        6
16  DOE         7

Now, create another table test2.

create table test2(
ID int NOT NULL ,
NAME VARCHAR (25)
);

We can use INSERT INTO SELECT:

INSERT INTO test2( ID, NAME )
  WITH cte AS (
            select ID,NAME, row_number() over(order by ID ASC ) as rownum
            from test t1
  )
  SELECT rownum,NAME
  FROM cte;

select * from test2;

Result:

ID    NAME
1 MICHAEL
2 JORDAN
3 DONALD
4 JAYCE
5 ROY
6 JOHN
7 DOE

See fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading