Re: Function or Field?

From: Frank Bax <fbax(at)sympatico(dot)ca>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Function or Field?
Date: 2005-05-03 13:41:11
Message-ID: 5.2.1.1.0.20050503092757.0532a040@pop6.sympatico.ca
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

At 07:58 AM 5/3/05, lucas(at)presserv(dot)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 WHERE client = $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

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Ramakrishnan Muralidharan 2005-05-04 04:44:38 Re: Record Log Trigger
Previous Message Tambet Matiisen 2005-05-03 12:32:42 Re: Function or Field?