Column "..." does not exist (view + union)

From: Stefan Weiss <krewecherl(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Column "..." does not exist (view + union)
Date: 2011-12-17 02:57:55
Message-ID: 4EEC0533.9050007@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Assuming the following simple setup with two data tables, one mapping
table, and one view -

-- ----------------------------------------------------------------
CREATE TABLE dossier (
id SERIAL NOT NULL PRIMARY KEY
);
CREATE TABLE contact (
id SERIAL NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
firstname TEXT NULL
);
CREATE TABLE dossier_contact (
dossier_id INTEGER NOT NULL REFERENCES dossier(id),
contact_id INTEGER NOT NULL REFERENCES contact(id),
ctype INTEGER NOT NULL,
PRIMARY KEY (dossier_id, contact_id)
);
CREATE VIEW dossier_contact_v AS
SELECT dc.dossier_id,
dc.contact_id,
dc.ctype,
(CASE WHEN c.firstname IS NOT NULL
THEN c.name || ', ' || c.firstname
ELSE c.name
END) AS name
FROM dossier_contact dc
JOIN contact c ON c.id = dc.contact_id;
-- ----------------------------------------------------------------

- running this query -

SELECT name
FROM dossier_contact_v
WHERE dossier_id = 56993
AND ctype = 234
UNION
SELECT name
FROM dossier_contact_v
WHERE dossier_id = -1
AND ctype = -1
ORDER BY ctype;

- fails with the following error message:

ERROR: column "ctype" does not exist
LINE 10: ORDER BY ctype;
^

The same query works fine without the ORDER BY, without the UNION, or
when I select the "ctype" column in addition to "name".
Why?

Using an alias in the FROM clause gives a different error:

SELECT x.name
FROM dossier_contact_v x
WHERE x.dossier_id = 56993
AND x.ctype = 234
UNION
SELECT x.name
FROM dossier_contact_v x
WHERE x.dossier_id = -1
AND x.ctype = -1
ORDER BY x.ctype;

ERROR: missing FROM-clause entry for table "x"
LINE 10: ORDER BY x.ctype
^

I am using "PostgreSQL 8.4.10 on x86_64-pc-linux-gnu, compiled by GCC
gcc-4.5.real (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2, 64-bit".

thanks,
stefan

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Andreas Kretschmer 2011-12-17 09:02:46 Re: Column "..." does not exist (view + union)
Previous Message Adrian Klaver 2011-12-16 15:31:40 Re: using a generated series in function