Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change starting id number

I have an 'Account' model in Rails with its corresponding 'accounts' table in the database. If I wipe the database and start over, the 'account_id' field will always start at 1 and count up from there. I would like to change the starting number, so that, when the very first account is created in a fresh database, the 'account_id' is, say, 1000. Is there a way to do that in Rails, or do I need specialized database-dependent SQL code?

For the sake of illustration, here is a simplified version of my 'accounts' table:

create_table "accounts", :force => true do |t|
  t.string   "email", :null => false
  t.string   "crypted_password", :null => false
  t.string   "name", :null => false
  t.boolean  "email_verified", :default => false
end
like image 994
Jeff Terrell Ph.D. Avatar asked Jan 15 '10 23:01

Jeff Terrell Ph.D.


People also ask

How to edit ID in auto increment in SQL?

); The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

How to change auto_ increment in MySQL?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name. The name of the table whose AUTO_INCREMENT value you wish to change.

How do you make an identity column start from 1?

Step 1 : Create a table named school. CREATE TABLE school ( student_id INT IDENTITY, student_name VARCHAR(200), marks INT ); Here, the 'student_id' column of the table starts from 1 as the default value of seed is 1 and each row is incremented by 1. Step 2 : Insert some value into a table.

How do I reset AutoIncrement?

In MySQL, the syntax to reset the AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = value; table_name. The name of the table whose AUTO_INCREMENT column you wish to reset.


2 Answers

for PostgreSQL:

execute("ALTER SEQUENCE accounts_id_seq START with 1000 RESTART;")

see https://www.postgresql.org/docs/current/static/sql-altersequence.html

like image 90
Lluís Avatar answered Sep 20 '22 22:09

Lluís


You'll need to do some specialized database-dependent SQL to get this functionality.

If you're using MySQL, you can add the following code to your migration after the create_table code:

execute("ALTER TABLE tbl AUTO_INCREMENT = 1000")
like image 42
Peter Avatar answered Sep 20 '22 22:09

Peter