Re: Function or Field? - Mailing list pgsql-sql

From Frank Bax
Subject Re: Function or Field?
Date
Msg-id 5.2.1.1.0.20050503092757.0532a040@pop6.sympatico.ca
Whole thread Raw
In response to Re: Function or Field?  (lucas@presserv.org)
List pgsql-sql
At 07:58 AM 5/3/05, lucas@presserv.org wrote:

>Do I have to create another table to put this data???
>But, Isn't it redundancy? :-/
>
>The question is: For example:
>  I have a "clients" table and I have a "taxes" table that is a chield of 
> client.
>  Is more efficient put fields into client table that contains:
>   -) the count for paid taxes
>   -) the count for unpaid taxes
>   -) the count for all taxes
>   -) the last tax expiration date
>  Or is more efficient construct a function that will count this field 
> runtime,
>as a view for example, or a simple function.
>   -) SELECT count(*) from taxes where client=$1 and not nullvalue(dt_pay);
>   -) SELECT count(*) from taxes where client=$1 and nullvalue(dt_pay);
>   -) SELECT count(*) from taxes where client=$1;
>   -) SELECT dt_expiration from taxes where client=$1 order by 
> dt_expiration desc
>limit 1;
>
>While having few records in "taxes" table, the function (runtime) work 
>right and
>in good time, but when the "taxes" table grows I think the function will 
>run so
>slow...
>What is correct???
>Construct a Function to count runtime? or Create a Trigger to update the
>"clients" fields before all action and use those fields in select???


Placing the count fields in client table is redundant and 
expensive.  Creating a function with four selects in it could be slow, but 
you can obtain those four data items in a single select:

SELECT    CASE WHEN dt_pay IS NULL THEN 0 ELSE count(*) END AS CountPaidTaxes,    CASE WHEN dt_pay IS NULL THEN
count(*)ELSE 0 END AS CountUnPaidTaxes,    COUNT(*) AS CountTaxes,    MAX(dt_expiration) AS LastExpiry    FROM taxes
WHEREclient = $1;
 

With an index on client, this should always be quite speedy.  Using "order 
by dt_expiration desc
limit 1;" is a nice trick, but not useful in this case because all rows for 
one client are being retrieved anyway for the other three data items.

Frank  



pgsql-sql by date:

Previous
From: "Tambet Matiisen"
Date:
Subject: Re: Function or Field?
Next
From: Enrico Weigelt
Date:
Subject: Mutex via database