Assuming you can define "first" in terms of a sort on a, b, and c you want DISTINCT ON
for this.
SELECT
DISTINCT ON ("A", "B")
"A", "B", "C"
FROM Table1
ORDER BY "A", "B", "C";
E.g. http://sqlfiddle.com/#!15/9ca16/1
See SELECT
for more on DISTINCT ON
.
If you have made the serious mistake of assuming SQL tables have an inherent order, you're going to need to fix your table before you proceed. You can use the PostgreSQL ctid
pseudo-column to guide the creation of a primary key that matches the current on-disk table order. It should be safe to just:
ALTER TABLE mytable ADD COLUMN id SERIAL PRIMARY KEY;
as PostgreSQL will tend to write the key in table order. It's not guaranteed, but neither is anything else when there's no primary key. Then you can:
SELECT
DISTINCT ON ("A", "B")
"A", "B", "C"
FROM Table1
ORDER BY id;
(Edit: I don't recommend using ctid
in queries baked into applications. It's a handy tool for solving specific problems, but it's not really public API in PostgreSQL, and it's not part of the SQL standard. It's not like ROWID
in Oracle, it changes due to vacuum etc. PostgreSQL is free to break/change/remove it in future versions.)