CREATE_FOREIGN_TABLE(7pg18)

๐Ÿ“ฆ version 18.6, in opensuse-leap 16.0

๐Ÿฆ‹ CREATE FOREIGN TABLE ๐Ÿฆ‹

okay bestie, gather round, because this is CREATE FOREIGN TABLE(7) straight out of the PostgreSQL 18.6 Documentation and it's genuinely a banger. it's giving "i want my data to live somewhere else but i still want my database to think it lives here" ๐Ÿ’… and honestly? iconic.


โœจ NAME โœจ

CREATE FOREIGN TABLE โ€” define a new foreign table ๐Ÿซถ


๐ŸŒธ SYNOPSIS ๐ŸŒธ

no cap, here's the whole shape of it:

CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( [
  { column_name data_type [ OPTIONS ( option 'value' [, ... ] ) ] [ COLLATE collation ] [ column_constraint [ ... ] ]
    | table_constraint
    | LIKE source_table [ like_option ... ] }
  [, ... ]
] )
[ INHERITS ( parent_table [, ... ] ) ]
  SERVER server_name
[ OPTIONS ( option 'value' [, ... ] ) ]

CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name
  PARTITION OF parent_table [ (
  { column_name [ WITH OPTIONS ] [ column_constraint [ ... ] ]
    | table_constraint }
  [, ... ]
) ]
{ FOR VALUES partition_bound_spec | DEFAULT }
  SERVER server_name
[ OPTIONS ( option 'value' [, ... ] ) ]

and like, where column_constraint is:

[ CONSTRAINT constraint_name ]
{ NOT NULL [ NO INHERIT ] |
  NULL |
  CHECK ( expression ) [ NO INHERIT ] |
  DEFAULT default_expr |
  GENERATED ALWAYS AS ( generation_expr ) [ STORED | VIRTUAL ] }
[ ENFORCED | NOT ENFORCED ]

and table_constraint is:

[ CONSTRAINT constraint_name ]
{  NOT NULL column_name [ NO INHERIT ] |
   CHECK ( expression ) [ NO INHERIT ] }
[ ENFORCED | NOT ENFORCED ]

and like_option is:

{ INCLUDING | EXCLUDING } { COMMENTS | CONSTRAINTS | DEFAULTS | GENERATED | STATISTICS | ALL }

and partition_bound_spec is:

IN ( partition_bound_expr [, ...] ) |
FROM ( { partition_bound_expr | MINVALUE | MAXVALUE } [, ...] )
  TO ( { partition_bound_expr | MINVALUE | MAXVALUE } [, ...] ) |
WITH ( MODULUS numeric_literal, REMAINDER numeric_literal )

๐Ÿ’– DESCRIPTION ๐Ÿ’–

okay so the tea: CREATE FOREIGN TABLE makes a brand new foreign table in the current database. and the table? it's owned by whoever ran the command. you typed it, you own it, periodt. ๐Ÿ‘‘

if you give it a schema name (like, for example, CREATE FOREIGN TABLE myschema.mytable ...) then the table gets created in that schema. if you don't, it lands in the current schema. and here's the vibe check: the name of your foreign table has to be distinct from the name of literally every other relation in that same schema โ€” tables, sequences, indexes, views, materialized views, and other foreign tables. no name-stealing allowed bestie ๐Ÿšซ

also, CREATE FOREIGN TABLE automatically creates a data type that represents the composite type corresponding to one row of the foreign table. which means foreign tables cannot have the same name as any existing data type in the same schema. it's giving "your name is already taken by a type, sorry". ๐Ÿ˜ญ

if the PARTITION OF clause is specified, then the table gets created as a partition of parent_table with the bounds you specified. very demure, very partitioned.

and to be able to create a foreign table at all, you need USAGE privilege on the foreign server, plus USAGE privilege on all the column types used in the table. no privileges, no table, that's the rule ๐ŸŽ€


๐ŸŒˆ PARAMETERS ๐ŸŒˆ

  • IF NOT EXISTS โ€” do not throw an error if a relation with the same name already exists. a notice is issued in this case. > โš ๏ธ note that there is no guarantee that the existing relation is anything like the one that would have been created. like, you asked for a new table and got... whatever was already there. vibe check failed, but no error. ๐Ÿ’€
  • table_name โ€” the name (optionally schema-qualified) of the table to be created.
  • column_name โ€” the name of a column to be created in the new table.
  • data_type โ€” the data type of the column. this can include array specifiers. for more info on the data types PostgreSQL supports, refer to Chapter 8. ๐Ÿ“š
  • COLLATE collation โ€” the COLLATE clause assigns a collation to the column (which must be of a collatable data type). if you don't specify one, the column data type's default collation is used.
  • INHERITS ( parent_table [, ... ] ) โ€” the optional INHERITS clause specifies a list of tables from which the new foreign table automatically inherits all columns. parent tables can be plain tables or foreign tables. see the similar form of CREATE TABLE for more details. family tree energy ๐ŸŒณ
  • PARTITION OF parent_table { FOR VALUES partition_bound_spec | DEFAULT } โ€” this form can be used to create the foreign table as a partition of the given parent table with the specified partition bound values. see the similar form of CREATE TABLE for more details.
โš ๏ธ note that it is currently not allowed to create the foreign table as a partition of the parent table if there are UNIQUE indexes on the parent table. (see also ALTER TABLE ATTACH PARTITION.)
  • LIKE source_table [ like_option ... ] โ€” the LIKE clause specifies a table from which the new table automatically copies all column names, their data types, and their not-null constraints.

unlike INHERITS, the new table and the original table are completely decoupled after creation is complete. changes to the original table will not be applied to the new table, and it is not possible to include data of the new table in scans of the original table. it's giving "we were never together" ๐Ÿ™ˆ

also unlike INHERITS, columns and constraints copied by LIKE are not merged with similarly named columns and constraints. if the same name is specified explicitly or in another LIKE clause, an error is signaled.

the optional like_option clauses specify which additional properties of the original table to copy. specifying INCLUDING copies the property, specifying EXCLUDING omits it. EXCLUDING is the default. if multiple specifications are made for the same kind of object, the last one is used. the available options are:

  • INCLUDING COMMENTS โ€” comments for the copied columns, constraints, and extended statistics will be copied. the default behavior is to exclude comments, resulting in the corresponding objects in the new table having no comments.
  • INCLUDING CONSTRAINTS โ€” CHECK constraints will be copied. no distinction is made between column constraints and table constraints. not-null constraints are always copied to the new table.
  • INCLUDING DEFAULTS โ€” default expressions for the copied column definitions will be copied. otherwise, default expressions are not copied, resulting in the copied columns in the new table having null defaults. > โš ๏ธ note that copying defaults that call database-modification functions, such as nextval, may create a functional linkage between the original and new tables.
  • INCLUDING GENERATED โ€” any generation expressions of copied column definitions will be copied. by default, new columns will be regular base columns.
  • INCLUDING STATISTICS โ€” extended statistics are copied to the new table.
  • INCLUDING ALL โ€” INCLUDING ALL is an abbreviated form selecting all the available individual options. (it could be useful to write individual EXCLUDING clauses after INCLUDING ALL to select all but some specific options.) the "everything" combo meal ๐Ÿ“
  • CONSTRAINT constraint_name โ€” an optional name for a column or table constraint. if the constraint is violated, the constraint name is present in error messages, so constraint names like col must be positive can be used to communicate helpful constraint information to client applications. (double-quotes are needed to specify constraint names that contain spaces.) if a constraint name is not specified, the system generates a name. name your constraints bestie, future you will thank you ๐Ÿ’œ
  • NOT NULL [ NO INHERIT ] โ€” the column is not allowed to contain null values.

a constraint marked with NO INHERIT will not propagate to child tables.

  • NULL โ€” the column is allowed to contain null values. this is the default.
this clause is only provided for compatibility with non-standard SQL databases. its use is discouraged in new applications. it's giving legacy. ๐Ÿงš
  • CHECK ( expression ) [ NO INHERIT ] โ€” the CHECK clause specifies an expression producing a Boolean result which each row in the foreign table is expected to satisfy; that is, the expression should produce TRUE or UNKNOWN, never FALSE, for all rows in the foreign table. a check constraint specified as a column constraint should reference that column's value only, while an expression appearing in a table constraint can reference multiple columns.

currently, CHECK expressions cannot contain subqueries nor refer to variables other than columns of the current row. the system column tableoid may be referenced, but not any other system column.

a constraint marked with NO INHERIT will not propagate to child tables.

  • DEFAULT default_expr โ€” the DEFAULT clause assigns a default data value for the column whose column definition it appears within. the value is any variable-free expression (subqueries and cross-references to other columns in the current table are not allowed). the data type of the default expression must match the data type of the column.

the default expression will be used in any insert operation that does not specify a value for the column. if there is no default for a column, then the default is null. the fallback fit, the "if nobody picks me" fit ๐Ÿ˜Œ

  • GENERATED ALWAYS AS ( generation_expr ) [ STORED | VIRTUAL ] โ€” this clause creates the column as a generated column. the column cannot be written to, and when read, the result of the specified expression will be returned.

when VIRTUAL is specified, the column will be computed when it is read. (the foreign-data wrapper will see it as a null value in new rows and may choose to store it as a null value or ignore it altogether.) when STORED is specified, the column will be computed on write. (the computed value will be presented to the foreign-data wrapper for storage and must be returned on reading.) VIRTUAL is the default.

the generation expression can refer to other columns in the table, but not other generated columns. any functions and operators used must be immutable. references to other tables are not allowed. no cap, read-only main character energy โœจ

  • server_name โ€” the name of an existing foreign server to use for the foreign table. for details on defining a server, see CREATE SERVER (CREATE_SERVER(7)).
  • OPTIONS ( option 'value' [, ...] ) โ€” options to be associated with the new foreign table or one of its columns. the allowed option names and values are specific to each foreign data wrapper and are validated using the foreign-data wrapper's validator function. duplicate option names are not allowed (although it's OK for a table option and a column option to have the same name). ๐Ÿ‘‘

okay that's the whole first chunk bestie, and there is so much more coming โ€” do not go anywhere, the rest of this page is right behind me ๐Ÿซถ

๐Ÿฆ‹ NOTES ๐Ÿฆ‹

okay bestie, this is the part where we get real ๐Ÿ’€ because there's some stuff you need to know before you go feral with foreign tables.

  • Constraints on foreign tables โ€” think CHECK or NOT NULL clauses โ€” are not enforced by the core PostgreSQL system. And most foreign data wrappers don't try to enforce them either ๐Ÿ™ˆ. Like, the constraint is just assumed to be true. That's it.
  • And honestly? There'd be little point in enforcing them, because it would only apply to rows inserted or updated via the foreign table, and not to rows modified by other means โ€” like, say, someone just messing with things directly on the remote server ๐Ÿ‘€. So instead, a constraint attached to a foreign table should represent a constraint that's being enforced by the remote server. That's the vibe. That's the assignment. periodt.

Some special-purpose foreign data wrappers might be the only access mechanism for the data they access ๐ŸŒˆ, and in that case it might be appropriate for the foreign data wrapper itself to perform constraint enforcement. But do not assume a wrapper does that unless its documentation says so. No cap, check the docs first.

So here's the tea ๐Ÿต: even though PostgreSQL does not attempt to enforce constraints on foreign tables, it does assume they're correct for purposes of query optimization. So if there are rows visible in the foreign table that don't satisfy a declared constraint, queries on the table might produce errors or incorrect answers ๐Ÿ˜ญ. It is the user's responsibility to ensure that the constraint definition matches reality. That's on you, babe.

โš ๏ธ Caution โš ๏ธ When a foreign table is used as a partition of a partitioned table, there is an implicit constraint that its contents must satisfy the partitioning rule. Again, it is the user's responsibility to ensure that that is true โ€” and the best way to do that is by installing a matching constraint on the remote server. slay responsibly ๐Ÿ’…

Within a partitioned table containing foreign-table partitions, an UPDATE that changes the partition key value can cause a row to be moved from a local partition to a foreign-table partition โ€” provided the foreign data wrapper supports tuple routing โœจ. However, it is not currently possible to move a row from a foreign-table partition to another partition. An UPDATE that would require doing that will fail due to the partitioning constraint, assuming that that is properly enforced by the remote server. so likeโ€ฆ know the limits ๐Ÿซถ

Similar considerations apply to generated columns ๐Ÿงš. Stored generated columns are computed on insert or update on the local PostgreSQL server and handed to the foreign-data wrapper for writing out to the foreign data store, but it is not enforced that a query of the foreign table returns values for stored generated columns that are consistent with the generation expression. Again, this might result in incorrect query results ๐Ÿ˜ญ. it's giving "trust but verify."


๐ŸŒธ EXAMPLES ๐ŸŒธ

okay let's actually do the thing ๐Ÿ’–

Create foreign table films, which will be accessed through the server film_server:

CREATE FOREIGN TABLE films (
    code        char(5) NOT NULL,
    title       varchar(40) NOT NULL,
    did         integer NOT NULL,
    date_prod   date,
    kind        varchar(10),
    len         interval hour to minute
)
SERVER film_server;

Create foreign table measurement_y2016m07, which will be accessed through the server server_07, as a partition of the range partitioned table measurement:

CREATE FOREIGN TABLE measurement_y2016m07
    PARTITION OF measurement FOR VALUES FROM ('2016-07-01') TO ('2016-08-01')
    SERVER server_07;

look at her go ๐Ÿ‘‘โœจ


๐ŸŒˆ COMPATIBILITY ๐ŸŒˆ

The CREATE FOREIGN TABLE command largely conforms to the SQL standard ๐ŸŽ€ โ€” however, much as with CREATE TABLE, NULL constraints and zero-column foreign tables are permitted. The ability to specify column default values is also a PostgreSQL extension. Table inheritance, in the form defined by PostgreSQL, is nonstandard. The LIKE clause, as supported in this command, is nonstandard.

so likeโ€ฆ mostly standard, a few little PostgreSQL-exclusive sparkles ๐Ÿ’… iykyk.


๐Ÿ‘‘ SEE ALSO ๐Ÿ‘‘

go read those next bestie, they're all in the group chat ๐Ÿ“š๐Ÿ’œ


and that's the whole page, fr fr ๐Ÿซถ this was PostgreSQL 18.6, dated 2026, and yes the page is literally called CREATE FOREIGN TABLE(7). mwah, go create something iconic ๐Ÿ’–โœจ๐ŸŽ€๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from