Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite trigger to update Summary Counts

Tags:

sqlite

Consider the following two (hypothetical) tables

Temperature

* day
* time
* lake_name
* station
* temperature_f

Temperature_summary

* day
* lake_name
* station
* count_readings_over_75f
* count_readings_below_75f

How can I write an SQLite Trigger to update the temperature_summary table on insert. I want to increment the count.

Thank You, Jeff

like image 934
jrhicks Avatar asked Jul 21 '26 10:07

jrhicks


1 Answers

This assumes you have already created the record for the day/lake_name/station before inserting temperatures on that day. Of course, you could add another trigger to do that.

create trigger Temperature_count_insert_trigger_hi after insert on Temperature
  when new.temperature_f >= 75
  begin
    update Temperature_summary set count_readings_over_75f = count_readings_over_75f + 1
    where new.day = day and new.lake_name = lake_name and new.station = station;
  end;

create trigger Temperature_count_insert_trigger_lo after insert on Temperature
  when new.temperature_f < 75
  begin
    update Temperature_summary set count_readings_below_75f = count_readings_below_75f + 1
    where new.day = day and new.lake_name = lake_name and new.station = station;
  end;

You can combine these into one slightly more complex trigger

create trigger Temperature_count_insert_trigger after insert on Temperature
  begin
    update Temperature_summary
    set count_readings_below_75f = count_readings_below_75f + (new.temperature_f < 75),
      count_readings_over_75f = count_readings_over_75f + (new.temperature_f >= 75)
    where new.day = day and new.lake_name = lake_name and new.station = station;
  end;

To insure that there is a row in Temperature_summary to update (a) make a unique index on Temperature_summary's (day, lake_name, station), or make those columns the primary key, and (b) do an insert or ignore in the trigger like so:

create trigger Temperature_count_insert_trigger after insert on Temperature
  begin
    insert or ignore into Temperature_summary
      values (new.day, new.lake_name, new.station, 0, 0);
    update Temperature_summary
    set count_readings_below_75f = count_readings_below_75f + (new.temperature_f < 75),
      count_readings_over_75f = count_readings_over_75f + (new.temperature_f >= 75)
    where new.day = day and new.lake_name = lake_name and new.station = station;
  end;
like image 176
Doug Currie Avatar answered Jul 24 '26 06:07

Doug Currie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!