5

I have a PostgreSQL database table with 4 columns - labeled column_a, column_b, etc. I want to query this table with a simple select query:

select * from table_name;

I get a handful of results looking like:

column_a | column_b
---------+---------
'a value'|'b_value'

But when I use this query:

select * from schema_name.table_name;

I get the full result:

column_a | column_b | column_c | column_d
---------+----------+----------+---------
'a value'|'b value' |'c value' |'d_value' 

Columns c and d were added at a later date, after initial table creation. My question is: Why would the database ignore the later columns when the schema name is left out of the select query?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Eric Jankowski
  • 463
  • 4
  • 9
  • 2
    Are you sure you don't have two tables (or views) with the same name, in different schemas? – IMSoP May 11 '15 at 23:14

1 Answers1

6

Table names are not unique within a database in Postgres. There can be any number of tables named 'table_name' in different schemas - including the temporary schema, which always comes first unless you explicitly list it after other schemas in the search_path. Obviously, there are multiple tables named table_name. You must understand the role of the search_path to interpret this correctly:

The first table lives in a schema that comes before schema_name in your search_path (or schema_name is not listed there at all). So the unqualified table name is resolved to this table (or view). Check the list of tables named 'table_name' that your current role has access to in your database:

SELECT *
FROM   information_schema.tables 
WHERE  table_name = 'table_name';

Views are just special tables with an attached RULE internally. They could play the same role as a regular table and are included in the above query. Details:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • This led me to discover that a handful of tables with duplicate names had been inadvertently placed in the public schema. Thanks. – Eric Jankowski May 12 '15 at 14:44