Foreign data wrappers concept in PostgreSQL - Time & Space Complexity
When using foreign data wrappers, we access data stored outside our main database. Understanding time complexity helps us see how query time changes as the external data grows.
We want to know: How does the time to get data from a foreign source grow when that data gets bigger?
Analyze the time complexity of this foreign table query.
CREATE EXTENSION IF NOT EXISTS postgres_fdw;
CREATE SERVER foreign_srv FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'remote_host', dbname 'foreign_db');
CREATE USER MAPPING FOR CURRENT_USER SERVER foreign_srv OPTIONS (user 'foreign_user', password 'secret');
IMPORT FOREIGN SCHEMA public LIMIT TO (foreign_table) FROM SERVER foreign_srv INTO local_schema;
SELECT * FROM local_schema.foreign_table WHERE column = 'value';
This code sets up a connection to a remote database and queries a foreign table through the wrapper.
Look at what repeats when querying foreign data.
- Primary operation: Fetching rows from the foreign table over the network.
- How many times: Once per row requested, depending on query and filters.
As the foreign table grows, the number of rows to fetch can increase, making the query take longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row fetches |
| 100 | About 100 row fetches |
| 1000 | About 1000 row fetches |
Pattern observation: The time grows roughly in direct proportion to the number of rows fetched from the foreign source.
Time Complexity: O(n)
This means the time to get data grows linearly with the number of rows fetched from the foreign table.
[X] Wrong: "Querying a foreign table is always instant because it's just like a local table."
[OK] Correct: Accessing foreign data involves network calls and remote processing, so time grows with the amount of data fetched, unlike local tables.
Understanding how foreign data wrappers affect query time shows you can think beyond local data and consider real-world data access costs. This skill helps you design efficient systems that work well with external data sources.
"What if we added a filter that reduces the number of rows fetched from the foreign table? How would the time complexity change?"