PostgreSQL Interview Master

The ultimate guide to 100+ expert PostgreSQL questions. Master the world's most advanced open-source relational database, from basics to internal architecture.

0 / 100 MasteredExecution PlansJSONB & NoSQL
Showing 100 high-quality results in All Questions category.
1
What is PostgreSQL?
Beginner

PostgreSQL is a powerful, open-source object-relational database system (ORDBMS) with over 35 years of active development. It is known for its reliability, feat...

Expert Postgres Solution
PostgreSQL is a powerful, open-source object-relational database system (ORDBMS) with over 35 years of active development. It is known for its reliability, feature robustness, and performance. It supports both SQL and JSON querying and is highly extensible.
Beginner
2
What are the key features of PostgreSQL?
Beginner

Key features include: 1. **ACID Compliance**: Ensures reliable transactions. 2. **Conjoined Scalability**: Support for complex queries and large data volumes. 3...

Expert Postgres Solution
Key features include: 1. **ACID Compliance**: Ensures reliable transactions. 2. **Conjoined Scalability**: Support for complex queries and large data volumes. 3. **Extensibility**: Custom types, functions, and operators. 4. **Advanced Data Types**: JSONB, HSTORE, Arrays, Ranges. 5. **MVCC**: Multi-Version Concurrency Control for high performance.
Beginner
3
What is the difference between PostgreSQL and MySQL?
Beginner

- **MySQL**: Traditional RDBMS, focused on speed and simplicity, traditionally better for read-heavy web apps. - **PostgreSQL**: ORDBMS, focused on compliance a...

Expert Postgres Solution
- **MySQL**: Traditional RDBMS, focused on speed and simplicity, traditionally better for read-heavy web apps. - **PostgreSQL**: ORDBMS, focused on compliance and advanced features, better for complex queries, high concurrency, and technical data types like JSONB.
Beginner
4
What is a Schema in PostgreSQL?
Beginner

In PostgreSQL, a schema is a namespace that contains named database objects such as tables, views, indexes, and functions. A database can contain one or more sc...

Expert Postgres Solution
In PostgreSQL, a schema is a namespace that contains named database objects such as tables, views, indexes, and functions. A database can contain one or more schemas.
Beginner
5
How do you create a table in PostgreSQL?
Beginner

You use the `CREATE TABLE` command.

Expert Postgres Solution
You use the `CREATE TABLE` command.
SQL Query
CREATE TABLE employees (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(100) UNIQUE,
  salary NUMERIC(10, 2)
);
Beginner
6
What is the SERIAL data type?
Beginner

The `SERIAL` type is a shorthand for creating an integer column that automatically increments. It creates a sequence behind the scenes. `SERIAL` is 4 bytes, whi...

Expert Postgres Solution
The `SERIAL` type is a shorthand for creating an integer column that automatically increments. It creates a sequence behind the scenes. `SERIAL` is 4 bytes, while `BIGSERIAL` is 8 bytes.
Beginner
7
How do you insert a row into a table?
Beginner

You use the `INSERT INTO` command.

Expert Postgres Solution
You use the `INSERT INTO` command.
SQL Query
INSERT INTO employees (name, email, salary) VALUES ('John Doe', 'john@example.com', 50000);
Beginner
8
What is the purpose of the 'psql' utility?
Beginner

`psql` is the interactive terminal (command-line interface) for working with PostgreSQL. It allows you to run queries and manage the database directly.

Expert Postgres Solution
`psql` is the interactive terminal (command-line interface) for working with PostgreSQL. It allows you to run queries and manage the database directly.
Beginner
9
How do you list all tables in 'psql'?
Beginner

You use the meta-command `\dt` (display tables).

Expert Postgres Solution
You use the meta-command `\dt` (display tables).
SQL Query
\dt
Beginner
10
How do you see the structure of a table in 'psql'?
Beginner

You use the meta-command `\d tableName` (describe).

Expert Postgres Solution
You use the meta-command `\d tableName` (describe).
SQL Query
\d employees
Beginner
11
What is a Primary Key?
Beginner

A primary key is a field or combination of fields that uniquely identifies each row in a table. It cannot be NULL and must be unique.

Expert Postgres Solution
A primary key is a field or combination of fields that uniquely identifies each row in a table. It cannot be NULL and must be unique.
Beginner
12
What is a Foreign Key?
Beginner

A foreign key is a column or group of columns used to establish a link between two tables. It ensures referential integrity by pointing to the primary key of an...

Expert Postgres Solution
A foreign key is a column or group of columns used to establish a link between two tables. It ensures referential integrity by pointing to the primary key of another table.
Beginner
13
Explain the 'LIMIT' and 'OFFSET' clauses.
Beginner

- **LIMIT**: Restricts the maximum number of rows returned. - **OFFSET**: Skips the first N rows before starting to return rows.

Expert Postgres Solution
- **LIMIT**: Restricts the maximum number of rows returned. - **OFFSET**: Skips the first N rows before starting to return rows.
SQL Query
SELECT * FROM employees LIMIT 10 OFFSET 20;
Beginner
14
How do you update data in a table?
Beginner

You use the `UPDATE` command.

Expert Postgres Solution
You use the `UPDATE` command.
SQL Query
UPDATE employees SET salary = salary * 1.1 WHERE id = 1;
Beginner
15
How do you delete data from a table?
Beginner

You use the `DELETE` command.

Expert Postgres Solution
You use the `DELETE` command.
SQL Query
DELETE FROM employees WHERE id = 5;
Beginner
16
What is the 'TRUNCATE' command?
Beginner

`TRUNCATE` quickly removes all rows from a table. It is generally faster than `DELETE` because it doesn't log individual row deletions and ignores most triggers...

Expert Postgres Solution
`TRUNCATE` quickly removes all rows from a table. It is generally faster than `DELETE` because it doesn't log individual row deletions and ignores most triggers.
Beginner
17
What is a View in PostgreSQL?
Beginner

A view is a virtual table based on the result-set of an SQL query. It does not store data itself but provides a way to simplify complex queries.

Expert Postgres Solution
A view is a virtual table based on the result-set of an SQL query. It does not store data itself but provides a way to simplify complex queries.
Beginner
18
What is an Index?
Beginner

An index is a pointer that helps speed up data retrieval. PostgreSQL supports several index types like B-tree (default), Hash, GIN, and GIST.

Expert Postgres Solution
An index is a pointer that helps speed up data retrieval. PostgreSQL supports several index types like B-tree (default), Hash, GIN, and GIST.
Beginner
19
What is the 'WHERE' clause used for?
Beginner

The `WHERE` clause is used to filter records that fulfill a specified condition.

Expert Postgres Solution
The `WHERE` clause is used to filter records that fulfill a specified condition.
Beginner
20
What is the 'GROUP BY' clause?
Beginner

The `GROUP BY` clause groups rows that have the same values into summary rows, typically used with aggregate functions like `COUNT()`, `MAX()`, `MIN()`, `SUM()`...

Expert Postgres Solution
The `GROUP BY` clause groups rows that have the same values into summary rows, typically used with aggregate functions like `COUNT()`, `MAX()`, `MIN()`, `SUM()`, `AVG()`.
Beginner
21
Explain 'INNER JOIN' vs 'LEFT JOIN'.
Beginner

- **INNER JOIN**: Returns records that have matching values in both tables. - **LEFT JOIN**: Returns all records from the left table, and the matched records fr...

Expert Postgres Solution
- **INNER JOIN**: Returns records that have matching values in both tables. - **LEFT JOIN**: Returns all records from the left table, and the matched records from the right table. If no match, NULLs are returned for the right side.
Beginner
22
What is the 'COALESCE' function?
Beginner

`COALESCE(val1, val2, ...)` returns the first non-null value from a list of expressions. It is commonly used to provide default values for NULL columns.

Expert Postgres Solution
`COALESCE(val1, val2, ...)` returns the first non-null value from a list of expressions. It is commonly used to provide default values for NULL columns.
Beginner
23
What is the purpose of 'VACUUM'?
Beginner

`VACUUM` reclaims storage occupied by dead tuples (deleted or updated rows) to keep the database efficient. PostgreSQL has an 'Autovacuum' daemon that does this...

Expert Postgres Solution
`VACUUM` reclaims storage occupied by dead tuples (deleted or updated rows) to keep the database efficient. PostgreSQL has an 'Autovacuum' daemon that does this automatically.
Beginner
24
What is 'COPY' command for?
Beginner

The `COPY` command is used to move data between PostgreSQL tables and standard file-system files. It is much faster than `INSERT` for large data sets.

Expert Postgres Solution
The `COPY` command is used to move data between PostgreSQL tables and standard file-system files. It is much faster than `INSERT` for large data sets.
SQL Query
COPY employees FROM '/tmp/data.csv' WITH (FORMAT csv);
Beginner
25
What is the default port for PostgreSQL?
Beginner

The default port for PostgreSQL is **5432**.

Expert Postgres Solution
The default port for PostgreSQL is **5432**.
Beginner
26
What is a Window Function in PostgreSQL?
Intermediate

A window function performs a calculation across a set of table rows that are somehow related to the current row. Common functions include `ROW_NUMBER()`, `RANK(...

Expert Postgres Solution
A window function performs a calculation across a set of table rows that are somehow related to the current row. Common functions include `ROW_NUMBER()`, `RANK()`, `DENSE_RANK()`, and `SUM() OVER ()`.
SQL Query
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) FROM employees;
Intermediate
27
What is a CTE (Common Table Expression)?
Intermediate

A CTE is a temporary result set that you can reference within another SQL statement. It is defined using the `WITH` clause and makes complex queries more readab...

Expert Postgres Solution
A CTE is a temporary result set that you can reference within another SQL statement. It is defined using the `WITH` clause and makes complex queries more readable.
SQL Query
WITH high_earners AS (
  SELECT * FROM employees WHERE salary > 100000
)
SELECT * FROM high_earners WHERE department = 'Sales';
Intermediate
28
Explain the 'EXPLAIN' and 'EXPLAIN ANALYZE' commands.
Intermediate

- **EXPLAIN**: Shows the execution plan that the PostgreSQL planner generates for a query. - **EXPLAIN ANALYZE**: Actually executes the query and shows the real...

Expert Postgres Solution
- **EXPLAIN**: Shows the execution plan that the PostgreSQL planner generates for a query. - **EXPLAIN ANALYZE**: Actually executes the query and shows the real timing and row counts, providing much more detail.
Intermediate
29
What is MVCC (Multi-Version Concurrency Control)?
Intermediate

MVCC allows multiple users to access the same data at the same time without locking each other out. When data is modified, a new version is created rather than ...

Expert Postgres Solution
MVCC allows multiple users to access the same data at the same time without locking each other out. When data is modified, a new version is created rather than overwriting the old one, ensuring that readers see a consistent snapshot.
Intermediate
30
What are the differences between JSON and JSONB?
Intermediate

- **JSON**: Stores an exact copy of the input text. Parsing is done on every query. - **JSONB**: Stores data in a decomposed binary format. It is slower to inse...

Expert Postgres Solution
- **JSON**: Stores an exact copy of the input text. Parsing is done on every query. - **JSONB**: Stores data in a decomposed binary format. It is slower to insert but much faster to query and supports indexing (GIN/GIST).
Intermediate
31
What is a GIN Index?
Intermediate

GIN stands for **Generalized Inverted Index**. It is designed for data that contains multiple components, such as arrays or JSONB documents. It is excellent for...

Expert Postgres Solution
GIN stands for **Generalized Inverted Index**. It is designed for data that contains multiple components, such as arrays or JSONB documents. It is excellent for searching within complex data types.
Intermediate
32
What is a Partial Index?
Intermediate

A partial index is built over a subset of a table, defined by a conditional expression (the `WHERE` clause of the index). This saves space and improves performa...

Expert Postgres Solution
A partial index is built over a subset of a table, defined by a conditional expression (the `WHERE` clause of the index). This saves space and improves performance.
SQL Query
CREATE INDEX active_orders_idx ON orders (id) WHERE status = 'active';
Intermediate
33
How do you perform a recursive query in PostgreSQL?
Intermediate

You use the `WITH RECURSIVE` clause. This is commonly used for hierarchical data like organizational charts or bill of materials.

Expert Postgres Solution
You use the `WITH RECURSIVE` clause. This is commonly used for hierarchical data like organizational charts or bill of materials.
SQL Query
WITH RECURSIVE sub_org AS (
  SELECT * FROM org WHERE name = 'Leadership'
  UNION
  SELECT org.* FROM org JOIN sub_org ON org.parent_id = sub_org.id
)
SELECT * FROM sub_org;
Intermediate
34
What is the 'UPSERT' (INSERT ON CONFLICT) operation?
Intermediate

Upsert allows you to either insert a new row or update an existing one if a conflict (like a unique constraint violation) occurs.

Expert Postgres Solution
Upsert allows you to either insert a new row or update an existing one if a conflict (like a unique constraint violation) occurs.
SQL Query
INSERT INTO users (email, last_login) VALUES ('test@test.com', NOW())
ON CONFLICT (email) DO UPDATE SET last_login = EXCLUDED.last_login;
Intermediate
35
What are the different isolation levels in PostgreSQL?
Intermediate

PostgreSQL supports four isolation levels: 1. **Read Uncommitted** (behaves like Read Committed) 2. **Read Committed** (default) 3. **Repeatable Read** 4. **Ser...

Expert Postgres Solution
PostgreSQL supports four isolation levels: 1. **Read Uncommitted** (behaves like Read Committed) 2. **Read Committed** (default) 3. **Repeatable Read** 4. **Serializable**
Intermediate
36
What is an extension in PostgreSQL?
Intermediate

Extensions allow you to add new features, data types, and functions to your database. Common extensions include `postgis` (spatial data), `pg_stat_statements` (...

Expert Postgres Solution
Extensions allow you to add new features, data types, and functions to your database. Common extensions include `postgis` (spatial data), `pg_stat_statements` (performance monitoring), and `uuid-ossp` (UUID generation).
Intermediate
37
Explain the 'RETURNING' clause in PostgreSQL.
Intermediate

The `RETURNING` clause allows you to return values from rows that were impacted by an `INSERT`, `UPDATE`, or `DELETE` operation.

Expert Postgres Solution
The `RETURNING` clause allows you to return values from rows that were impacted by an `INSERT`, `UPDATE`, or `DELETE` operation.
SQL Query
INSERT INTO users (name) VALUES ('Bob') RETURNING id;
Intermediate
38
What is a Materialized View?
Intermediate

A materialized view stores the result-set of a query physically on disk. It provides much faster read performance for complex queries but must be manually or sc...

Expert Postgres Solution
A materialized view stores the result-set of a query physically on disk. It provides much faster read performance for complex queries but must be manually or scheduled to be refreshed.
SQL Query
REFRESH MATERIALIZED VIEW my_view;
Intermediate
39
How do you generate a UUID in PostgreSQL?
Intermediate

You can use the `gen_random_uuid()` function (built-in for Postgres 13+) or install the `uuid-ossp` extension and use `uuid_generate_v4()`.

Expert Postgres Solution
You can use the `gen_random_uuid()` function (built-in for Postgres 13+) or install the `uuid-ossp` extension and use `uuid_generate_v4()`.
SQL Query
SELECT gen_random_uuid();
Intermediate
40
What is 'ILIKE'?
Intermediate

`ILIKE` is a PostgreSQL-specific operator for case-insensitive pattern matching. `LIKE` is case-sensitive.

Expert Postgres Solution
`ILIKE` is a PostgreSQL-specific operator for case-insensitive pattern matching. `LIKE` is case-sensitive.
Intermediate
41
Explain the 'OVER' clause.
Intermediate

The `OVER` clause defines the 'window' over which a window function operates. It can include `PARTITION BY` and `ORDER BY` sub-clauses.

Expert Postgres Solution
The `OVER` clause defines the 'window' over which a window function operates. It can include `PARTITION BY` and `ORDER BY` sub-clauses.
Intermediate
42
What are Savepoints in a transaction?
Intermediate

Savepoints allow you to roll back parts of a transaction without canceling the entire transaction. They are useful for error handling within large transactions.

Expert Postgres Solution
Savepoints allow you to roll back parts of a transaction without canceling the entire transaction. They are useful for error handling within large transactions.
SQL Query
BEGIN;
INSERT INTO t1 VALUES (1);
SAVEPOINT my_save;
INSERT INTO t1 VALUES (2); -- Oops!
ROLLBACK TO my_save;
COMMIT;
Intermediate
43
What is a Sequence in PostgreSQL?
Intermediate

A sequence is a special kind of table that generates a sequence of numbers. They are commonly used to generate primary key values.

Expert Postgres Solution
A sequence is a special kind of table that generates a sequence of numbers. They are commonly used to generate primary key values.
SQL Query
SELECT nextval('my_sequence');
Intermediate
44
What is the difference between 'VARCHAR' and 'TEXT'?
Intermediate

In PostgreSQL, there is no performance difference between `VARCHAR(N)` and `TEXT`. Both are stored in the same way. The only difference is that `VARCHAR(N)` enf...

Expert Postgres Solution
In PostgreSQL, there is no performance difference between `VARCHAR(N)` and `TEXT`. Both are stored in the same way. The only difference is that `VARCHAR(N)` enforces a character limit.
Intermediate
45
What is 'hstore'?
Intermediate

`hstore` is an extension that provides a data type for storing sets of (key, value) pairs within a single value. It is useful for semi-structured data, though `...

Expert Postgres Solution
`hstore` is an extension that provides a data type for storing sets of (key, value) pairs within a single value. It is useful for semi-structured data, though `JSONB` is now generally preferred.
Intermediate
46
How do you handle character encoding in PostgreSQL?
Intermediate

PostgreSQL uses **UTF-8** by default. You can set the encoding at the database level when creating it.

Expert Postgres Solution
PostgreSQL uses **UTF-8** by default. You can set the encoding at the database level when creating it.
SQL Query
CREATE DATABASE mydb WITH ENCODING 'UTF8';
Intermediate
47
What is the 'DISTINCT ON' clause?
Intermediate

`DISTINCT ON (field)` is a PostgreSQL extension that allows you to keep only the first row for each distinct set of values in the target fields. It is usually c...

Expert Postgres Solution
`DISTINCT ON (field)` is a PostgreSQL extension that allows you to keep only the first row for each distinct set of values in the target fields. It is usually combined with an `ORDER BY` clause.
SQL Query
SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, order_date DESC;
Intermediate
48
What is a TRIGGER in PostgreSQL?
Intermediate

A trigger is a specification that the database should automatically execute a particular function whenever a certain type of operation is performed (e.g., `BEFO...

Expert Postgres Solution
A trigger is a specification that the database should automatically execute a particular function whenever a certain type of operation is performed (e.g., `BEFORE INSERT`, `AFTER UPDATE`).
Intermediate
49
Explain 'CAST' and the '::' shorthand.
Intermediate

Both are used for type conversion. `CAST(val AS type)` is standard SQL, while `val::type` is a PostgreSQL shorthand.

Expert Postgres Solution
Both are used for type conversion. `CAST(val AS type)` is standard SQL, while `val::type` is a PostgreSQL shorthand.
SQL Query
SELECT '100'::INTEGER;
Intermediate
50
What is the 'pg_stat_activity' view?
Intermediate

`pg_stat_activity` is a system view that shows information about currently active database processes, including the user, query, and start time.

Expert Postgres Solution
`pg_stat_activity` is a system view that shows information about currently active database processes, including the user, query, and start time.
Intermediate
51
Explain PostgreSQL Partitioning.
Advanced

Partitioning is the split of one large logical table into several smaller physical pieces. PostgreSQL support Declarative Partitioning by Range, List, or Hash. ...

Expert Postgres Solution
Partitioning is the split of one large logical table into several smaller physical pieces. PostgreSQL support Declarative Partitioning by Range, List, or Hash. This improves performance for extremely large tables by allowing the optimizer to only scan relevant partitions.
Advanced
52
What is BRIN (Block Range Index)?
Advanced

BRIN indexes store the minimum and maximum values for a block of pages. They are much smaller than B-tree indexes and are ideal for very large tables where data...

Expert Postgres Solution
BRIN indexes store the minimum and maximum values for a block of pages. They are much smaller than B-tree indexes and are ideal for very large tables where data is physically sorted by the indexed column (e.g., timestamps).
Advanced
53
Explain GIST (Generalized Search Tree) vs GIN.
Advanced

- **GIST**: Good for spatial data, full text search, and nearest neighbor searches. Slower to query than GIN but faster to update. - **GIN**: Best for multi-val...

Expert Postgres Solution
- **GIST**: Good for spatial data, full text search, and nearest neighbor searches. Slower to query than GIN but faster to update. - **GIN**: Best for multi-value data (arrays, JSONB). Faster for searches but slower for updates due to its inverted structure.
Advanced
54
What is Table Inheritance?
Advanced

Table inheritance allows a table to inherit the columns and constraints of a parent table. While powerful, it has been largely superseded by Declarative Partiti...

Expert Postgres Solution
Table inheritance allows a table to inherit the columns and constraints of a parent table. While powerful, it has been largely superseded by Declarative Partitioning for performance-oriented use cases.
Advanced
55
What are Logical and Physical Replication?
Advanced

- **Physical Replication**: Copies the entire data directory byte-for-byte. Used for high availability and read-only standbys. - **Logical Replication**: Copies...

Expert Postgres Solution
- **Physical Replication**: Copies the entire data directory byte-for-byte. Used for high availability and read-only standbys. - **Logical Replication**: Copies individual data changes (rows). Allows replicating specific tables and replicating across different major versions or platforms.
Advanced
56
Explain 'Vacuum Full' vs 'Vacuum'.
Advanced

- **VACUUM**: Marks old rows as reusable but doesn't return space to the OS (except at the end of the file). - **VACUUM FULL**: Compacts the table and returns a...

Expert Postgres Solution
- **VACUUM**: Marks old rows as reusable but doesn't return space to the OS (except at the end of the file). - **VACUUM FULL**: Compacts the table and returns all free space to the OS. It requires an EXCLUSIVE lock, blocking all other access while running.
Advanced
57
What are Foreign Data Wrappers (FDW)?
Advanced

FDW allows PostgreSQL to connect to and query external data sources (like other Postgres servers, MySQL, MongoDB, or even Redis) as if they were local tables.

Expert Postgres Solution
FDW allows PostgreSQL to connect to and query external data sources (like other Postgres servers, MySQL, MongoDB, or even Redis) as if they were local tables.
SQL Query
CREATE EXTENSION postgres_fdw;
Advanced
58
Explain the 'WAL' (Write-Ahead Logging).
Advanced

WAL ensures that no data is lost if the system crashes. Changes are written to a log file on disk before they are applied to the data files, ensuring that the d...

Expert Postgres Solution
WAL ensures that no data is lost if the system crashes. Changes are written to a log file on disk before they are applied to the data files, ensuring that the database can recover by replaying the log.
Advanced
59
What is an Advisory Lock?
Advanced

Advisory locks are application-defined locks that have no inherent meaning to the database. They provide a way for applications to coordinate actions using the ...

Expert Postgres Solution
Advisory locks are application-defined locks that have no inherent meaning to the database. They provide a way for applications to coordinate actions using the database as a lock manager without blocking table or row access.
Advanced
60
What is JIT (Just-In-Time) compilation in Postgres?
Advanced

Since version 11, PostgreSQL can use LLVM to compile parts of complex queries into machine code at runtime. This can significantly speed up CPU-bound queries th...

Expert Postgres Solution
Since version 11, PostgreSQL can use LLVM to compile parts of complex queries into machine code at runtime. This can significantly speed up CPU-bound queries that involve many expressions and aggregates.
Advanced
61
How do you handle Deadlocks in PostgreSQL?
Advanced

PostgreSQL automatically detects deadlocks and aborts one of the transactions involved to resolve the conflict. Developers should handle these retries in their ...

Expert Postgres Solution
PostgreSQL automatically detects deadlocks and aborts one of the transactions involved to resolve the conflict. Developers should handle these retries in their application code.
Advanced
62
What is 'Streaming Replication'?
Advanced

Streaming replication allows a standby server to stay up-to-date with a primary server by continuously receiving WAL logs over a network connection, providing a...

Expert Postgres Solution
Streaming replication allows a standby server to stay up-to-date with a primary server by continuously receiving WAL logs over a network connection, providing a real-time hot standby for disaster recovery.
Advanced
63
Explain 'Work Mem' and 'Maintenance Work Mem'.
Advanced

- **work_mem**: The amount of memory used for internal sort operations and hash tables. High values speed up complex queries but use more RAM. - **maintenance_w...

Expert Postgres Solution
- **work_mem**: The amount of memory used for internal sort operations and hash tables. High values speed up complex queries but use more RAM. - **maintenance_work_mem**: The memory used for maintenance tasks like `VACUUM` and `CREATE INDEX`.
Advanced
64
What is a Bloom Index?
Advanced

A Bloom index is based on Bloom filters. It is useful for tables where you have many columns and any subset of them might be used in a query. It is much smaller...

Expert Postgres Solution
A Bloom index is based on Bloom filters. It is useful for tables where you have many columns and any subset of them might be used in a query. It is much smaller than multiple B-tree indexes.
Advanced
65
Explain 'HOT' (Heap Only Tuple) updates.
Advanced

HOT updates allow PostgreSQL to update a row without updating its indexes, provided the change fits on the same disk page and no indexed columns were modified. ...

Expert Postgres Solution
HOT updates allow PostgreSQL to update a row without updating its indexes, provided the change fits on the same disk page and no indexed columns were modified. This significantly reduces VACUUM overhead.
Advanced
66
What is 'pg_dump' vs 'pg_dumpall'?
Advanced

- **pg_dump**: Backs up a single database. - **pg_dumpall**: Backs up all databases in a cluster, including global objects like roles and groups.

Expert Postgres Solution
- **pg_dump**: Backs up a single database. - **pg_dumpall**: Backs up all databases in a cluster, including global objects like roles and groups.
Advanced
67
How to find slow queries in PostgreSQL?
Advanced

Enable the `pg_stat_statements` extension. It tracks execution statistics for all SQL statements executed on the server, allowing you to find the queries that t...

Expert Postgres Solution
Enable the `pg_stat_statements` extension. It tracks execution statistics for all SQL statements executed on the server, allowing you to find the queries that take the most cumulative time.
Advanced
68
What is 'Postgis'?
Advanced

PostGIS is an extension that adds support for geographic objects to PostgreSQL, allowing it to be used as a spatial database for Geographic Information Systems ...

Expert Postgres Solution
PostGIS is an extension that adds support for geographic objects to PostgreSQL, allowing it to be used as a spatial database for Geographic Information Systems (GIS).
Advanced
69
Explain 'Declarative Partitioning'.
Advanced

Introduced in Postgres 10, it allows you to define partitions directly using `PARTITION BY` in the table definition, eliminating the need for complex triggers a...

Expert Postgres Solution
Introduced in Postgres 10, it allows you to define partitions directly using `PARTITION BY` in the table definition, eliminating the need for complex triggers and management code.
Advanced
70
What is 'Index Scan' vs 'Bitmap Index Scan' vs 'Sequential Scan'?
Advanced

- **Sequential Scan**: Reads every row in the table (Slow for large datasets). - **Index Scan**: Follows the index directly to the row (Fast for small row count...

Expert Postgres Solution
- **Sequential Scan**: Reads every row in the table (Slow for large datasets). - **Index Scan**: Follows the index directly to the row (Fast for small row counts). - **Bitmap Index Scan**: Creates a bitmap of pages that contain matches, then visits those pages. Efficient for larger subsets of data.
Advanced
71
What is 'Checkpointer' process?
Advanced

The checkpointer periodically flushes 'dirty' data pages (changes made in RAM) to the disk. This ensures that the WAL logs can be reused and keeps the recovery ...

Expert Postgres Solution
The checkpointer periodically flushes 'dirty' data pages (changes made in RAM) to the disk. This ensures that the WAL logs can be reused and keeps the recovery time short.
Advanced
72
What is 'Schema Search Path'?
Advanced

The search path is a list of schemas that PostgreSQL looks through when a table is referenced without a schema name. It usually defaults to `"$user", public`.

Expert Postgres Solution
The search path is a list of schemas that PostgreSQL looks through when a table is referenced without a schema name. It usually defaults to `"$user", public`.
Advanced
73
How to optimize queries with JSONB data?
Advanced

1. Use GIN indexes for general containment queries. 2. Use expression indexes for specific nested fields. 3. Use the containment operator `@>` for best index pe...

Expert Postgres Solution
1. Use GIN indexes for general containment queries. 2. Use expression indexes for specific nested fields. 3. Use the containment operator `@>` for best index performance.
Advanced
74
Explain 'LISTEN' and 'NOTIFY'.
Advanced

This is a simple messaging system within PostgreSQL. A client can `LISTEN` to a channel, and another client can `NOTIFY` that channel with a message, which is d...

Expert Postgres Solution
This is a simple messaging system within PostgreSQL. A client can `LISTEN` to a channel, and another client can `NOTIFY` that channel with a message, which is delivered to all listeners asynchronously.
Advanced
75
What is 'Parallel Query' execution?
Advanced

Postgres can use multiple CPU cores to execute a single query. It splits the work (e.g., table scans, joins) across multiple background workers to speed up exec...

Expert Postgres Solution
Postgres can use multiple CPU cores to execute a single query. It splits the work (e.g., table scans, joins) across multiple background workers to speed up execution time on large data sets.
Advanced
76
Scenario: How to find the second highest salary without using LIMIT?
Scenario

Use a subquery with the `MAX()` function.

Expert Postgres Solution
Use a subquery with the `MAX()` function.
SQL Query
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
Scenario
77
Scenario: How to delete duplicate rows from a table while keeping the one with the lowest ID?
Scenario

Use a subquery with `MIN(id)` and a `GROUP BY` clause.

Expert Postgres Solution
Use a subquery with `MIN(id)` and a `GROUP BY` clause.
SQL Query
DELETE FROM employees WHERE id NOT IN (
  SELECT MIN(id) FROM employees GROUP BY email
);
Scenario
78
Scenario: How to find the average salary by department, and only show departments with an average > 50000?
Scenario

Use `GROUP BY` and `HAVING`.

Expert Postgres Solution
Use `GROUP BY` and `HAVING`.
SQL Query
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 50000;
Scenario
79
Scenario: How to perform a case-insensitive search for a username?
Scenario

Use the `ILIKE` operator or the `LOWER()` function.

Expert Postgres Solution
Use the `ILIKE` operator or the `LOWER()` function.
SQL Query
SELECT * FROM users WHERE username ILIKE 'john%';
-- OR
SELECT * FROM users WHERE LOWER(username) = 'john';
Scenario
80
Scenario: How to query a JSONB column to find rows where a specific key exists?
Scenario

Use the `?` operator.

Expert Postgres Solution
Use the `?` operator.
SQL Query
SELECT * FROM logs WHERE data ? 'error_code';
Scenario
81
Scenario: How to query a JSONB column to find rows where a key has a specific value?
Scenario

Use the `->>` operator or the containment operator `@>`.

Expert Postgres Solution
Use the `->>` operator or the containment operator `@>`.
SQL Query
SELECT * FROM orders WHERE info ->> 'status' = 'shipped';
-- OR
SELECT * FROM orders WHERE info @> '{"status": "shipped"}';
Scenario
82
Scenario: How to combine first_name and last_name with a space in between?
Scenario

Use the `||` operator or the `CONCAT()` function.

Expert Postgres Solution
Use the `||` operator or the `CONCAT()` function.
SQL Query
SELECT first_name || ' ' || last_name AS full_name FROM users;
Scenario
83
Scenario: How to get the first 5 characters of a string?
Scenario

Use the `LEFT()` or `SUBSTRING()` function.

Expert Postgres Solution
Use the `LEFT()` or `SUBSTRING()` function.
SQL Query
SELECT LEFT(description, 5) FROM products;
Scenario
84
Scenario: How to prevent a division by zero error in a query?
Scenario

Use the `NULLIF()` function.

Expert Postgres Solution
Use the `NULLIF()` function.
SQL Query
SELECT amount / NULLIF(quantity, 0) FROM sales;
Scenario
85
Scenario: How to find the nth most recent login for each user?
Scenario

Use the `ROW_NUMBER()` window function within a CTE.

Expert Postgres Solution
Use the `ROW_NUMBER()` window function within a CTE.
SQL Query
WITH RankedLogins AS (
  SELECT user_id, login_date, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date DESC) as rn
  FROM logins
)
SELECT * FROM RankedLogins WHERE rn = 2; -- 2nd most recent
Scenario
86
Scenario: How to update multiple rows with different values in a single query?
Scenario

Use the `UPDATE ... FROM` syntax with a values list or a temporary table.

Expert Postgres Solution
Use the `UPDATE ... FROM` syntax with a values list or a temporary table.
SQL Query
UPDATE employees AS e SET salary = v.new_salary
FROM (VALUES (1, 60000), (2, 70000)) AS v(id, new_salary)
WHERE e.id = v.id;
Scenario
87
Scenario: How to copy only the structure of a table without any data?
Scenario

Use `CREATE TABLE ... AS` with a `WHERE false` condition.

Expert Postgres Solution
Use `CREATE TABLE ... AS` with a `WHERE false` condition.
SQL Query
CREATE TABLE employees_backup AS SELECT * FROM employees WHERE false;
Scenario
88
Scenario: How to find rows where a column's value is between 10 and 20 (inclusive)?
Scenario

Use the `BETWEEN` operator.

Expert Postgres Solution
Use the `BETWEEN` operator.
SQL Query
SELECT * FROM products WHERE price BETWEEN 10 AND 20;
Scenario
89
Scenario: How to handle auto-incrementing IDs for a table created from a CSV with existing IDs?
Scenario

After inserting, you must manually sync the sequence associated with the SERIAL column.

Expert Postgres Solution
After inserting, you must manually sync the sequence associated with the SERIAL column.
SQL Query
SELECT setval(pg_get_serial_sequence('employees', 'id'), MAX(id)) FROM employees;
Scenario
90
Scenario: How to find the current database name?
Scenario

Use the `current_database()` function.

Expert Postgres Solution
Use the `current_database()` function.
SQL Query
SELECT current_database();
Scenario
91
Scenario: How to get the size of a database?
Scenario

Use the `pg_database_size()` function combined with `pg_size_pretty()` for readability.

Expert Postgres Solution
Use the `pg_database_size()` function combined with `pg_size_pretty()` for readability.
SQL Query
SELECT pg_size_pretty(pg_database_size('mydb'));
Scenario
92
Scenario: How to find which processes are currently blocking a specific table?
Scenario

Query the `pg_locks` and `pg_stat_activity` views.

Expert Postgres Solution
Query the `pg_locks` and `pg_stat_activity` views.
SQL Query
SELECT pid, usename, query FROM pg_stat_activity 
WHERE pid IN (SELECT pid FROM pg_locks WHERE relation = 'employees'::regclass);
Scenario
93
Scenario: How to kill a slow-running query process?
Scenario

Use the `pg_cancel_backend(pid)` or `pg_terminate_backend(pid)` functions.

Expert Postgres Solution
Use the `pg_cancel_backend(pid)` or `pg_terminate_backend(pid)` functions.
SQL Query
SELECT pg_terminate_backend(1234); -- pid 1234
Scenario
94
Scenario: How to generate a range of numbers (1 to 10)?
Scenario

Use the `generate_series()` function.

Expert Postgres Solution
Use the `generate_series()` function.
SQL Query
SELECT generate_series(1, 10);
Scenario
95
Scenario: How to convert a comma-separated string into rows?
Scenario

Use `string_to_array()` and `unnest()`.

Expert Postgres Solution
Use `string_to_array()` and `unnest()`.
SQL Query
SELECT unnest(string_to_array('apple,banana,cherry', ','));
Scenario
96
Scenario: How to get the difference between two timestamps in hours?
Scenario

Subtract the timestamps to get an interval, then use `EXTRACT(EPOCH ...)` / 3600.

Expert Postgres Solution
Subtract the timestamps to get an interval, then use `EXTRACT(EPOCH ...)` / 3600.
SQL Query
SELECT EXTRACT(EPOCH FROM (end_time - start_time)) / 3600 FROM tasks;
Scenario
97
Scenario: How to find all columns in a specific table using SQL?
Scenario

Query the `information_schema.columns` view.

Expert Postgres Solution
Query the `information_schema.columns` view.
SQL Query
SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'employees';
Scenario
98
Scenario: How to find the running total of sales over time?
Scenario

Use a window function with `SUM()`.

Expert Postgres Solution
Use a window function with `SUM()`.
SQL Query
SELECT sale_date, amount, SUM(amount) OVER (ORDER BY sale_date) as running_total FROM sales;
Scenario
99
Scenario: You need to store multiple IP addresses in a single column and query them efficiently. Solution?
Scenario

Use the `INET` or `CIDR` data types and create a GIST index. These types provide built-in validation and allow for efficient network overlap queries.

Expert Postgres Solution
Use the `INET` or `CIDR` data types and create a GIST index. These types provide built-in validation and allow for efficient network overlap queries.
Scenario
100
How to export a table to a CSV file?
Scenario

Use the `COPY` command (requires server-side access) or the `\copy` meta-command in `psql` (client-side).

Expert Postgres Solution
Use the `COPY` command (requires server-side access) or the `\copy` meta-command in `psql` (client-side).
SQL Query
\copy employees TO 'employees.csv' CSV HEADER;
Scenario
Postgres Pro Newsletter

Scale Your Knowledge!

Join 42,000+ developers receiving advanced tips on PostgreSQL performance tuning, vacuum management, and new feature deep-dives. Delivered weekly.