Which of the following best describes how a nested loop join works in PostgreSQL?
Think about the simplest join method that compares every row from one table to every row of the other.
A nested loop join works by taking each row from the first table and scanning the entire second table to find matches. This is simple but can be slow for large tables.
Given two tables employees and departments, which query output matches the use of a hash join in PostgreSQL?
Assume employees has 1000 rows and departments has 10 rows.
EXPLAIN (ANALYZE, BUFFERS) SELECT e.name, d.name FROM employees e JOIN departments d ON e.department_id = d.id;
Hash joins are efficient when one table is much smaller and can be hashed in memory.
PostgreSQL uses a hash join by building a hash table on the smaller table (departments) and then probes it with rows from the larger table (employees).
Which SQL query is most likely to trigger a merge join in PostgreSQL?
Merge joins require both tables to be sorted on the join keys.
Merge join is efficient when both tables are sorted on the join keys. The query with ORDER BY on join keys encourages PostgreSQL to use merge join.
You have two tables: big_sales with 1 million rows and small_regions with 100 rows. Which join algorithm will PostgreSQL most likely choose for SELECT * FROM big_sales JOIN small_regions ON big_sales.region_id = small_regions.id; and why?
Think about which join is efficient when one table is very small.
Hash join is efficient here because PostgreSQL builds a hash table on the small table (small_regions) and probes it with the large table (big_sales), avoiding scanning the big table multiple times.
You wrote this query:
SELECT * FROM products p JOIN categories c ON p.category_id = c.id;
PostgreSQL uses a nested loop join instead of a hash or merge join, causing slow performance. Which of the following is the most likely reason?
Indexes help PostgreSQL choose efficient join methods.
Without indexes on join keys, PostgreSQL may fall back to nested loop join because it cannot efficiently build hash tables or sort for merge joins.