file_fdw: Reading Server Files as Tables

Last updated: 2026-11-04

file_fdw: Reading Server Files as Tables

file_fdw is also a foreign data wrapper, but what it reads is not another database — it reads files from the server's filesystem. You declare a CSV or any other COPY-readable file as a foreign table and query it directly, row by row, without importing it first. Paths are resolved relative to the data directory and the file must be readable by the server process; the program option goes further, running a command and reading its standard output.

Kindextension
Example LanguageSQL

📝 Syntax

CREATE EXTENSION IF NOT EXISTS file_fdw;

CREATE SERVER file_server FOREIGN DATA WRAPPER file_fdw;

CREATE FOREIGN TABLE t_csv (
    id   int,
    name text
) SERVER file_server
  OPTIONS (filename 'data/orders.csv', format 'csv', header 'true');

SELECT * FROM t_csv;

Returns:CREATE EXTENSION, CREATE SERVER and CREATE FOREIGN TABLE return no result set on success. A SELECT against the foreign table parses the file row by row using COPY rules and returns the declared columns; exactly one of filename and program must be given.

▶ Example

Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.

Output:

SELECT id, name, score FROM t_csv_scores_fdw ORDER BY id
 id | name  | score
----+-------+-------
  1 | row-1 |  1.50
  2 | row-2 |  3.00
  3 | row-3 |  4.50
(3 rows)

Note: the example first writes a CSV with COPY and then reads it back through file_fdw, so the script is self-contained; on a real server, writing the file with COPY TO requires superuser or the pg_write_server_files role.

📌 Key Points

More case studies coming soon.

📚 Related Reference

❓ FAQ

QCan file_fdw read any file it likes?
AYou supply the path, but permissions gate it: changing options such as filename requires superuser or the pg_read_server_files role, and the file itself must still be readable by the server process. That is why file_fdw's CREATE FOREIGN TABLE should not be handed to untrusted users in production.
Qfile_fdw or COPY into a table?
AFor a small file you only query occasionally, file_fdw saves the import step. For large data that needs indexes, complex JOINs or repeated aggregation, COPY into a regular table is the better choice — a foreign table re-parses the file on every query and has neither statistics nor usable indexes.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏