0 Down time
GraphQL
NextJS
Mongo
VITE
MEAN
MERN
Rust
Spring
Hibernate
Liquid
SASS
REST
Spring
React
Angular

SQL Notes

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:  

  • Enable logging: Turn on log_min_duration_statement to capture slow queries.
  • Use EXPLAIN (ANALYZE): Understand query execution plans.
  • Monitor system metrics: CPU, memory, disk I/O, and network usage.
  • Check PostgreSQL stats: Use pg_stat_activity, pg_stat_user_tables, and pg_stat_io to identify bottlenecks.

Query Optimization

Q2: How do you optimize slow-running queries in PostgreSQL?

A2:  

  • Indexing: Ensure appropriate indexes exist (B-tree, GIN, GiST, etc.).
  • Avoid SELECT *: Fetch only necessary columns.
  • Use joins wisely: Prefer explicit joins over subqueries when possible.
  • Analyze execution plans: Use EXPLAIN to identify sequential scans or nested loops.
  • Vacuum and analyze: Regularly run VACUUM and ANALYZE to keep statistics fresh.

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:  

  • shared_buffers: Memory allocated for caching data pages.
  • work_mem: Memory per query operation (sorts, hashes).
  • maintenance_work_mem: Memory for maintenance tasks like vacuuming.
  • effective_cache_size: Estimate of OS-level cache available.
  • max_connections: Too many connections can degrade performance.

Maintenance & Housekeeping

Q5: How do you keep a PostgreSQL database healthy over time?

A5:  

  • Autovacuum tuning: Adjust thresholds to prevent table bloat.
  • Partitioning: Break large tables into manageable chunks.
  • Connection pooling: Use tools like PgBouncer to reduce overhead.
  • Regular backups: Ensure disaster recovery readiness.
  • Monitoring tools: Use pg_stat_statements, Prometheus, or pgBadger.

Advanced Techniques

Q6: What are some advanced strategies for scaling PostgreSQL?

A6:  

  • Read replicas: Use streaming replication for read-heavy workloads.
  • Sharding: Distribute data across multiple nodes (e.g., Citus).
  • Parallel queries: PostgreSQL supports parallel execution for large queries.
  • Foreign data wrappers (FDW): Integrate external data sources efficiently.

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:  

  • INNER JOIN: Returns rows with matching values in both tables.
  • LEFT JOIN: Returns all rows from the left table, and matched rows from the right table.
  • FULL OUTER JOIN: Returns all rows when there is a match in one of the tables.

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:  

  • Normalize data to reduce redundancy.
  • Use appropriate data types (e.g., UUID for IDs, JSONB for flexible data).
  • Define constraints (NOT NULL, UNIQUE, CHECK, FOREIGN KEY).
  • Use indexes wisely to optimize performance.

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:  

  • CHAR(n): Fixed-length string. Pads with spaces.
  • VARCHAR(n): Variable-length string with a limit.
  • TEXT: Variable-length string with no limit. Best for large text blobs.

Migrations & Versioning

Q7: What tools can help manage PostgreSQL schema migrations?

A:  

  • Flyway
  • Liquibase
  • Sqitch
  • Alembic (for SQLAlchemy in Python)
  • Hasura migrations (for GraphQL-based setups)

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);

script