Skip to content
Advertisement

Why does the id serial primary key keep changing?

I have just started a full stack web developer course which includes PostgreSQL. I have been give some practice questions to do and when I clicked on run SQL it displays the id, first_name and last_name but when I entered in more lines of code to answer more questions and clicked on run SQL again, the id number changed to a completely different number and I don’t understand why this is happening.

Screenshot Screenshot

In the practice questions I was instructed to add more rows and then to update the entry with an id of 2 to something else but how can I update id 2 if the id numbers keep changing? id 2 wasn’t even on the screen. What I understand of id serial primary key is that it auto increments the id when you add new rows but in this case the id keeps changing to random numbers, why does it do this? The screenshots are code from the course, not what I entered. http://sqlfiddle.com/#!17/a114f/2 this is the link but I am not sure if you anyone who has not signed up to the course can access it. Sorry if this is a really simple newbie question but I have spent a lot of time looking online and I really need to move forward.

Advertisement

Answer

Like a_horse_with_no_name, I too prefer db<>fiddle for SQL code sharing. But if you’re restricted to sqlfiddle for whatever reason, you can add a setval() command to your code to force the seeding value.

select setval('drivers_id_seq',1);

INSERT INTO drivers (first_name, last_name) VALUES ('Amy', 'Hua');

SELECT * from drivers;

See example here (link). Note that drivers_id_seq is a system-generated name that you can guess pretty easily (should you need to reseed the serial you create on another object).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement