'if' decision making in an SQL statement

From: nik(at)iii(dot)co(dot)uk
To: pgsql-sql(at)postgresql(dot)org
Subject: 'if' decision making in an SQL statement
Date: 1998-08-10 10:23:11
Message-ID: 19980810112311.C3592@iii.co.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hi,

After searching the documentation and mailing list archives I can't find
anything about this -- I'm pretty certain it can't be done, but I
thought the mailing list might be able to help.

Is there anyway to perform IF...THEN...ELSE logic in a PostgreSQL query?

The specific problem I'm trying to solve is as follows. Given the class

create table People (
ID int default nextvalue('seqPeople'),
Firstname text not null,
Middlenames text,
Lastname text not null
);

insert into People (Firstname, Middlenames, Lastname)
values ('Nik', 'John', 'Clayton');

insert into People (Firstname, Middlenames, Lastname)
values ('Helen', 'Jane', 'Baker');

insert into People (Firstname, Lastname)
values ('Justin', 'Otto');

...

I want to create a query (which will be used as the basis for a view) that
merges the Firstname, Middlenames and Lastname columns together into one
column, with the correct spacing.

In Oracle, I'd use the decode() function for this, and write

select ID, decode(Middlenames, null, Firstname || ' ' || Lastname,
Firstname || ' ' || Middlenames || ' ' || Lastname)
as Fullname
from People;

which expresses the logic

IF Middlenames IS NULL THEN
Firstname || ' ' || Lastname
ELSE
Firstname || ' ' || Middlenames || ' ' || Lastname
END IF

and would give

ID Fullname
-------------
1 Nik John Clayton
2 Helen Jane Baker
3 Justin Otto
...

I can't see a way of doing this in PostgreSQL, and I don't really want
to have to do this sort of processing in the front end (since I have
several front ends, and putting the same logic in each one strikes me as
foolish when that logic really belongs in the database).

Many thanks for any suggestions.

N
--
"So it does!" said Pooh. "It goes in!"
"So it does!" said Piglet. "And it comes out!"
"Doesn't it?" said Eyeore. "It goes in and out like anything."

Browse pgsql-sql by date

  From Date Subject
Next Message James Oden 1998-08-10 10:51:12 Re: [SQL] Installing PostgreSQL 6.3.2 On Linux
Previous Message Stuart logan 1998-08-10 09:01:22 Installing PostgreSQL 6.3.2 On Linux