CREATE_FOREIGN_TABLE(7pg18)
๐ฆ 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โ theCOLLATEclause 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 optionalINHERITSclause 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 ofCREATE TABLEfor 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 ofCREATE TABLEfor more details.
โ ๏ธ note that it is currently not allowed to create the foreign table as a partition of the parent table if there areUNIQUEindexes on the parent table. (see alsoALTER TABLE ATTACH PARTITION.)
LIKE source_table [ like_option ... ]โ theLIKEclause 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โCHECKconstraints 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 asnextval, 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 ALLis an abbreviated form selecting all the available individual options. (it could be useful to write individualEXCLUDINGclauses afterINCLUDING ALLto 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 likecol must be positivecan 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 ]โ theCHECKclause specifies an expression producing a Boolean result which each row in the foreign table is expected to satisfy; that is, the expression should produceTRUEorUNKNOWN, neverFALSE, 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โ theDEFAULTclause 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, seeCREATE 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
CHECKorNOT NULLclauses โ 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 ๐
ALTER FOREIGN TABLE(ALTER_FOREIGN_TABLE(7))DROP FOREIGN TABLE(DROP_FOREIGN_TABLE(7))CREATE TABLE(CREATE_TABLE(7))CREATE SERVER(CREATE_SERVER(7))IMPORT FOREIGN SCHEMA(IMPORT_FOREIGN_SCHEMA(7))
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
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms