Re: Help with quotes in plpgsql

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Hector Villarreal" <HVillarreal(at)mynewplace(dot)com>
Cc: "Milen A(dot) Radev" <milen(at)radev(dot)net>, pgsql-sql(at)postgresql(dot)org
Subject: Re: Help with quotes in plpgsql
Date: 2006-12-20 00:27:00
Message-ID: 14125.1166574420@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

"Hector Villarreal" <HVillarreal(at)mynewplace(dot)com> writes:
> select into a now() - ($1::text||'days')::interval;

People keep suggesting variants of that as ways to convert numeric
values to intervals, but it's really extremely bad practice. Much
better is to use number-times-interval multiplication:

select into a now() - $1 * '1 day'::interval;

This is less typing, at least as easy to understand, more flexible
(you can use any scale factor you want), and considerably more
efficient. The first way involves coercing the integer to text,
then text-concatenating that with a constant, then applying
interval_in which does a fairly nontrivial parsing process.
The second way is basically just a multiplication, because
'1 day'::interval is already a constant value of type interval.

regards, tom lane

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Ashish Ahlawat 2006-12-20 03:25:58 Fetching BLOBs
Previous Message Hector Villarreal 2006-12-20 00:00:00 Re: Help with quotes in plpgsql