Skip to content

Instantly share code, notes, and snippets.

@zzzeek
Created October 5, 2019 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzzeek/be2daac39dd5c5079003fa0d80404d47 to your computer and use it in GitHub Desktop.
Save zzzeek/be2daac39dd5c5079003fa0d80404d47 to your computer and use it in GitHub Desktop.
what happens if you have duplicate label names in a derived selectable
test=> create table foo (a integer, b integer, c integer);
CREATE TABLE
test=> insert into foo (a, b, c) values (1, 2, 3);
INSERT 0 1
test=> -- dupe column names are OK
test=> select a as a, b as b, c as c, a as a, b as a, b as b from foo;
a | b | c | a | a | b
---+---+---+---+---+---
1 | 2 | 3 | 1 | 2 | 2
(1 row)
test=> -- dupe column names as a derived selectable, we can get them with *
test=> select * from (select a as a, b as b, c as c, a as a, b as a, b as b from foo) as anon;
a | b | c | a | a | b
---+---+---+---+---+---
1 | 2 | 3 | 1 | 2 | 2
(1 row)
test=> -- but what good is *, how about by name...nope
test=> select a, b, c, a, a, b from (select a as a, b as b, c as c, a as a, b as a, b as b from foo) as anon;
ERROR: column reference "a" is ambiguous
LINE 1: select a, b, c, a, a, b from (select a as a, b as b, c as c,...
^
test=> -- ?!?! the cols are there! what is star accessing?
test=> select anon.a from (select a as a, b as b, c as c, a as a, b as a, b as b from foo) as anon;
ERROR: column reference "a" is ambiguous
LINE 1: select anon.a from (select a as a, b as b, c as c, a as a, b...
^
test=> -- !?!?!
test=> -- star ! what is your magic power?
select * from (select a as a, b as b, c as c, a as a, b as a, b as b from foo) as anon;
a | b | c | a | a | b
---+---+---+---+---+---
1 | 2 | 3 | 1 | 2 | 2
(1 row)
test=> -- so what do we do in the real world? something like this.
test=> -- e.g. use tools. most dupe col situations occur because we
test=> -- are using tools in the first place, but they also come up when doing
test=> -- set operations e.g. UNION and such, as column position counts in that
test=> -- case
test=> select anon.a, anon.b, anon.c from (select a as a, b as b, c as c, a as a__1, b as a__2, b as b__1 from foo) as anon;
a | b | c
---+---+---
1 | 2 | 3
(1 row)
test=>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment