Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this sequence increments by 2?

I can't understand why this sequence is incremented by 2.

Is there any error in sequence to increment by 1? I need this to insert primary key value in table 'food'.

CREATE SEQUENCE food_id_ai START WITH 1 INCREMENT BY 1 CACHE 100;

create table food(
    food_id  integer,
    f_name   varchar(30) not null,
    category varchar(30) not null,
    price    number(4),
    amount   number(4)  
);

alter table food add constraint fpk primary key(food_id);

CREATE OR REPLACE TRIGGER insert_into_food
  BEFORE INSERT ON food
  FOR EACH ROW
BEGIN
  :new.food_id:= food_id_ai.nextval;
END;
/

insert into food values(food_id_ai.nextval,'ruchi', 'chanachur' , 8, 50);
insert into food values(food_id_ai.nextval,'chips', 'chips' , 8, 50);
insert into food values(food_id_ai.nextval,'aeromatic', 'soap' , 8, 50);
insert into food values(food_id_ai.nextval,'handwash', 'toyletries', 8, 50);
insert into food values(food_id_ai.nextval,'tissue', 'toyletries' , 8, 50);
like image 223
Masum Avatar asked Mar 15 '23 00:03

Masum


1 Answers

Because you're accessing the sequence both in your INSERT statement and in the trigger that is launched for each row, of course it's incremented by two.

Choose one.
I'd go for the trigger-based one, since you won't have to remember to specify the sequence in each insert statement you may execute.

In that case, you'll have to explicitly list the columns you are going to insert VALUES to:

INSERT INTO food (f_name, category, price, amount)
VALUES ('ruchi', 'chanachur' , 8, 50);
like image 127
watery Avatar answered Mar 24 '23 10:03

watery