views:

16

answers:

1

I have a deal and transaction table, where the deal table has an aggregated column, 'TotalSales', which is simply a count of transactions per deal.

With the following command, is there ever a chance the transaction row count and total sales count would not be in sync (not including deleting rows)? Does the default isolation level work for this? We have many users making purchases at potentially the same time, so I'm trying to figure out the best way to handle this.

BEGIN TRANSACTION
INSERT INTO [transaction] ... 

UPDATE deal
SET TotalSales = (select count(*) from [transaction] where dealid = @dealId)
WHERE dealId = @dealId 
COMMIT TRANSACTION
+1  A: 

My perference for things like these is to use a view:

CREATE VIEW vw_sales AS
AS 
       SELECT t.dealid, 
                   COUNT(*) AS total_sales
          FROM TRANSACTION t
  GROUP BY t.dealid

Less hassle involved with keeping the value in sync, redundant data is not stored...

It's just as susceptible to isolation level issues - the default is to read committed data. Reading uncommitted data for total sales would be Bad(tm).

OMG Ponies
One of the reasons that is driving me towards an aggregated column is for historical views of deals, showing the total sales. Deals only last one day, so running an aggregate for all deals for a given date range for example seems a little wasteful.
Marco
@Marco: Why do you think aggregate functions are wasteful?
OMG Ponies
I think for performance reasons, running an aggregate over a transactional table with thousands of records (looking at historical data) seems like a little de-normalization may be needed. Maybe im doin a little *pre optimization* here. What are your thoughts on performance for this scenario. Basically, the home page always needs to show the total sales for the deal and a history page showing all previous deals and total sales.
Marco
@Marco: Given that deals only last one day, I'd be caching the aggregate results that're run on a per day basis. Maybe a smaller window if you have sales for a previous days deal, but the current days deal I'd fetch more frequently, separately.
OMG Ponies