SQL Inserting values to an existing record if they are meeting some criteria, or updating a value to maintain an average
I am creating a database table to track stats on people running 100m sprints. Each row (record) will hold the data for a runner. A row will store how many times they have ran a 100m sprint. (totalRuns) A row will also hold the average time the runner has based on the total number of runs they have done. (timeAverage) A row will also hold the best time the runner has ever ran. (timebest) Is there a way that I can directly insert a new _run's_ data into the table and have the average timeAverage field's value calculated instead of having to pull the runner's existing data out of the database first, calculating the average in my custom code and then inserting the calculated result? When I insert a runner's first run, it is simple. Just input the data for that run like: INSERT INTO runstats ('John Smith', 1, 11.43, 11.43) so John Smith has run once, and he ran a 11.43 sprint so that's his current average and best time. When John runs again, I just want to do something like (I know this doesnt work, this is just pseudo code): INSERT OR UPDATE INTO runStats ('John Smith', AUTOINCREMENT+1, (IF thisRun < timeBest, thisRun, timeBest), (AVERAGEOF(timeAverage + thisRun, totalRuns)) So what I'm asking is can SQL (sqlite specifically) do inserts like this, where you can test against existing values in the table and update/increment them ?