immanu10
immanu10

Reputation: 17

how to add trigger to count number of rows automatically after inserting in oracle sql developer

I want to add trigger to count number of movies after inserting!

This is the table to store the count value:

CREATE TABLE mov_count
  (mcount NUMBER);

and the movie table:

create table movie
  (mov_id number primary key,
   mov_title varchar(20),
   mov_lang varchar(20));

This is the trigger I have created:

create trigger count_movie_trg
after insert on movie
for each row
BEGIN

  UPDATE mov_count
  SET    mcount = (SELECT COUNT(*) FROM movie);

END; 
/

After creating this i tried to add movie but its showing mutating trigger/function may not see it error.

Upvotes: 1

Views: 4290

Answers (3)

MT0
MT0

Reputation: 168081

Don't use the table at all; use a view instead.

CREATE VIEW mov_count ( mcount ) AS
  SELECT COUNT(*) FROM movie;

db<>fiddle

Upvotes: 1

Littlefoot
Littlefoot

Reputation: 142798

It is the FOR EACH ROW that bothers you. It is a table-level trigger, so:

Enter a dummy value for beginning (as you'll update it later):

SQL> insert into mov_count values (0);

1 row created.

Trigger:

SQL> create or replace trigger count_movie_trg
  2    after insert on movie
  3  begin
  4    update mov_count c set
  5      c.mcount = (select count(*) from movie m);
  6  end;
  7  /

Trigger created.

Testing:

SQL> insert into movie
  2    select 1, 'Titanic' from dual union all
  3    select 2, 'Superman' from dual;

2 rows created.

SQL> select count(*) from mov_count;

  COUNT(*)
----------
         1

SQL>

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1270081

Why not just maintain the value without referring to the original table?

create trigger count_movie_trg after insert on movie for each row
begin
    update mov_count set mcount = mcount + 1;
end;

To keep the count up-to-date, you'll need a delete trigger as well.

Upvotes: 1

Related Questions