Here’s a set of insightful questions and answers that explore strategies for improving PostgreSQL database performance. These could be useful for interviews, team discussions, or just sharpening your own database optimization skills.
General Performance Tuning
Q1: What are the first steps you'd take to diagnose performance issues in a PostgreSQL database?
A1:
Query Optimization
Q2: How do you optimize slow-running queries in PostgreSQL?
A2:
Indexing Strategy
Q3: What types of indexes are available in PostgreSQL and when would you use them?
A3:
Index Type |
Use Case |
B-tree |
Default; good for equality and range queries. |
Hash |
Fast for equality, but limited use. |
GIN |
Full-text search, array containment. |
GiST |
Geospatial data, custom types. |
BRIN |
Large tables with naturally ordered data. |
Configuration Tuning
Q4: Which PostgreSQL configuration parameters impact performance the most?
A4:
Maintenance & Housekeeping
Q5: How do you keep a PostgreSQL database healthy over time?
A5:
Advanced Techniques
Q6: What are some advanced strategies for scaling PostgreSQL?
A6:
PostgreSQL Database Development Q&A
Query Development
Q1: How do you write a query to fetch the top 5 highest-paid employees from an employees table?
A:
SELECT * FROM employees
ORDER BY salary DESC
LIMIT 5;
Q2: What’s the difference between INNER JOIN, LEFT JOIN, and FULL OUTER JOIN?
A:
Q3: How can you prevent SQL injection in PostgreSQL?
A:
Use parameterized queries or prepared statements. For example, in Python with psycopg2:
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
Schema Design
Q4: What are some best practices for designing a PostgreSQL schema?
A:
Q5: How do you define a table with a foreign key in PostgreSQL?
A:
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_id INT REFERENCES customers(id),
order_date DATE NOT NULL
);
Q6: What’s the difference between VARCHAR, TEXT, and CHAR?
A:
Migrations & Versioning
Q7: What tools can help manage PostgreSQL schema migrations?
A:
Q8: How do you safely apply a migration that adds a new column with a default value?
A:
Split into two steps to avoid locking large tables:
ALTER TABLE users ADD COLUMN is_active BOOLEAN;
UPDATE users SET is_active = TRUE;
ALTER TABLE users ALTER COLUMN is_active SET DEFAULT TRUE;
Q9: How do you rollback a migration in PostgreSQL?
A:
Depends on the tool. For manual rollback:
ALTER TABLE users DROP COLUMN is_active;
With tools like Flyway:
flyway undo
Testing Queries
Q10: How do you test performance of a query in PostgreSQL?
A:
Use EXPLAIN ANALYZE to see the query plan and execution time:
EXPLAIN ANALYZE SELECT * FROM orders WHERE order_date > '2023-01-01';
Q11: How can you create test data quickly in PostgreSQL?
A:
Use generate_series():
INSERT INTO users (id, name)
SELECT generate_series(1, 1000), 'User_' || generate_series(1, 1000);