-2

I need to insert values in a new table from another table with existing data.

INSERT INTO newtable(ordering,customer_id,client) 
(SELECT 1,customer_number,client_name from oldtable);

Current workflow: Id column is set as auto increment so it is not included in the query. This query will set ordering column as 1 in all rows.

What I need: The ordering column must start at 1 then increment by 1 after each row. But I do not want to set this column as auto increment. Can I achieve this through simple query or need to prepare a stored procedure/function? If so, how?

nbk
  • 45,398
  • 8
  • 30
  • 47
Ansul
  • 410
  • 5
  • 12
  • 2
    The way to generate sequential numbers is already answered [here](https://stackoverflow.com/questions/11094466/generate-serial-number-in-mysql-query) – franklwambo19 Sep 18 '22 at 17:40

1 Answers1

0

You can use window functions with row number in your select to generate what you want.

INSERT INTO newtable(ordering,customer_id,client) 
 SELECT    
    ROW_NUMBER() OVER(PARTITION BY [id]) AS row_num, customer_number,client_name  
FROM oldtable;  
Farshid Shekari
  • 2,391
  • 4
  • 27
  • 47