PostgreSQL Interview Questions
Master the most commonly asked interview questions with comprehensive, expert-crafted answers designed to help you succeed.
What Is PostgreSQL, And How Does It Differ From Other SQL Databases?
What Are The Key Features Of PostgreSQL?
- ACID Compliance: Ensures atomicity, consistency, isolation, and durability in transactions.
- Support for relational features: Foreign keys, joins, views, triggers, and stored procedures.
- Full-text search: Allows efficient searching within text data.
- Advanced data types: Supports arrays, hstore, and JSONB for flexible data storage.
- Extensibility: Users can create their own functions, operators, and data types.
- MVCC (Multi-Version Concurrency Control): Enables concurrent transaction handling without locking issues.
How to Create a New Database In PostgreSQL?
CREATE DATABASE
command followed by the desired database name.
Example:
CREATE DATABASE mydatabase;
mydatabase
.
---
How to Create a New Table In PostgreSQL?
After creating a database, you often need to create tables to store your data. Use theCREATE TABLE
command with the table name and column definitions.
Example:
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
name VARCHAR(100),
position VARCHAR(100),
salary NUMERIC,
hire_date DATE
);
employees
with columns for employee ID, name, position, salary, and hire date.
What is a Primary Key in PostgreSQL?
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
name VARCHAR(100)
);
How to Query Data From a Table in PostgreSQL?
SELECT
statement. It allows you to specify which columns to fetch or use *
to select all columns.
Example:
SELECT * FROM employees;
employees
table.
What is a Foreign Key in PostgreSQL?
CREATE TABLE departments (
department_id SERIAL PRIMARY KEY,
department_name VARCHAR(100)
);
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
name VARCHAR(100),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
How to Update Data in a Table in PostgreSQL?
UPDATE
statement. You specify the table, set new values for columns, and use a WHERE
clause to target specific rows.
Example:
UPDATE employees
SET salary = 85000
WHERE name = 'John Doe';
How to Delete Data From a Table in PostgreSQL?
DELETE
statement. By specifying conditions with the WHERE
clause, you control which records get deleted.
Example:
DELETE FROM employees
WHERE name = 'John Doe';
What is a View in PostgreSQL?
CREATE VIEW high_salary_employees AS
SELECT name, salary
FROM employees
WHERE salary > 80000;
How to Create an Index in PostgreSQL?
CREATE INDEX
statement to create an index on one or more columns of a table.
Example:
CREATE INDEX idx_employee_name ON employees(name);
idx_employee_name
on the name
column of the employees
table to improve search performance on employee names.
What Is A Transaction In PostgreSQL?
BEGIN
command. Once all operations are done successfully, you finalize the transaction with COMMIT
.
If something goes wrong, you can undo all changes made during the transaction by issuing a ROLLBACK
.
Example:
BEGIN;
UPDATE employees SET salary = 90000 WHERE name = 'John Doe';
COMMIT;
What is MVCC in PostgreSQL?
- Readers do not block writers.
- Writers do not block readers.
- Transactions see a consistent snapshot of the data as of the start of the transaction.
How to Handle Backup and Restore in PostgreSQL?
pg_dump
tool is used to create a backup by exporting the database contents into a file. To restore the database, the psql
command is used to execute the backup file and recreate the data.
Example to back up a database:
pg_dump mydatabase > mydatabase_backup.sql
psql mydatabase < mydatabase_backup.sql
What are Triggers in PostgreSQL, and How to Create Them?
Triggers in PostgreSQL are special procedures that automatically execute when certain events occur on a table (such as INSERT
, UPDATE
, or DELETE
).
Example – Creating a Trigger:
CREATE FUNCTION update_timestamp() RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER update_timestamp
BEFORE UPDATE ON employees
FOR EACH ROW
EXECUTE FUNCTION update_timestamp();
How to Implement Foreign Keys in PostgreSQL?
Foreign keys establish a relationship between two tables and ensure referential integrity. The foreign key value in one table must match a value in another table.
Example – Creating Foreign Keys:
CREATE TABLE departments (
department_id SERIAL PRIMARY KEY,
department_name VARCHAR(100)
);
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
name VARCHAR(100),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
What is a View in PostgreSQL, and How to Create One?
A view in PostgreSQL is a virtual table based on the result of a SELECT
query. It encapsulates complex queries and allows them to be reused as if they were tables.
Example – Creating a View:
CREATE VIEW high_salary_employees AS
SELECT name, salary
FROM employees
WHERE salary > 80000;
How to Handle Exceptions in PL/pgSQL?
Exceptions in PL/pgSQL can be handled using the EXCEPTION
block. This allows you to catch and manage errors in your stored procedures or functions.
Example – Handling a Duplicate Key Error:
DO $$
BEGIN
INSERT INTO employees (employee_id, name) VALUES (1, 'John Doe');
EXCEPTION
WHEN unique_violation THEN
RAISE NOTICE 'Duplicate key error!';
END;
$$;
What are CTEs (Common Table Expressions) in PostgreSQL?
Common Table Expressions (CTEs) are temporary result sets that can be referenced within a SELECT
, INSERT
, UPDATE
, or DELETE
statement. They make queries easier to read and maintain.
Example – Using a CTE:
WITH employee_salaries AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT * FROM employee_salaries;
How to Use Window Functions in PostgreSQL?
Window functions perform calculations across a set of table rows related to the current row, often used for ranking, running totals, and moving averages.
Example – Ranking Employees by Salary:
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;
Explain the Concept of JSON Data Types in PostgreSQL.
PostgreSQL supports JSON
and JSONB
data types for storing and querying JSON data. JSONB
is a binary format that is more efficient for indexing and searching.
Example – Creating a Table with JSONB:
CREATE TABLE products (
id SERIAL PRIMARY KEY,
details JSONB
);
INSERT INTO products (details)
VALUES ('{"name": "Laptop", "price": 1200}');
What are some of the different operators in PostgreSQL?
PostgreSQL supports a variety of operators for performing operations on data. These include:
- Arithmetic Operators: For mathematical calculations such as addition (+), subtraction (-), multiplication (*), division (/).
- Comparison Operators: For comparing values, including =, !=, <, >, <=, >=.
- Logical Operators: For combining conditions, such as AND, OR, and NOT.
- Bitwise Operators: For performing bit-level operations such as &, |, #, ~, <<, >>.
How can you delete a PostgreSQL database?
You can delete a PostgreSQL database in two ways:
- Using the SQL command
DROP DATABASE database_name;
- Using the command-line utility
dropdb database_name
What are indexes used for?
Indexes in PostgreSQL are used to speed up data retrieval operations. They act like a lookup table for the database, allowing the query engine to find rows faster without scanning the entire table.
What is the purpose of a Cluster index?
A Cluster index sorts the table's data rows based on the index key values, physically ordering them to improve performance for certain queries.
What are database callback functions and how do they help?
Database callback functions in PostgreSQL are known as triggers. They are automatically executed when a specified database event occurs (such as INSERT, UPDATE, or DELETE), enabling automated actions like logging, validation, or data synchronization.
What are the benefits of specifying data types in columns while creating a table?
Specifying data types for table columns provides several benefits:
- Consistency: Ensures all data in a column follows the same format.
- Compactness: Optimizes storage by using appropriate data types.
- Validation: Prevents invalid data from being inserted.
- Performance: Allows the database engine to optimize queries based on data type.
How do you update statistics in PostgreSQL?
To update statistics in PostgreSQL, use the VACUUM ANALYZE
command or the ANALYZE
command. These update optimizer statistics, helping PostgreSQL make better query planning decisions.
What is the disadvantage of the DROP TABLE command?
The disadvantage of the DROP TABLE
command is that it permanently removes both the table data and the table structure from the database. To store data again, the table must be re-created.
What purpose does the CTIDs field serve?
The CTID
field identifies the specific physical location of a row in a table by indicating the block and offset positions.
Which commands are used to control transactions in PostgreSQL?
The main commands for controlling transactions in PostgreSQL are:
BEGIN TRANSACTION
– Starts a transaction block.COMMIT
– Saves all changes made during the transaction.ROLLBACK
– Reverts all changes made during the transaction.
What are the main differences between SQL and PostgreSQL?
Some key differences between SQL and PostgreSQL include:
- In PostgreSQL, views are not updatable by default, unlike in SQL Server.
- SQL Server supports computed columns, whereas PostgreSQL does not.
- PostgreSQL allows dynamic actions without needing DLL creation, unlike SQL Server.
- PostgreSQL supports more advanced dynamic operations.
How is security ensured in PostgreSQL?
PostgreSQL ensures security by supporting SSL connections to encrypt client-server communication, protecting data from eavesdropping and tampering.
What is the function of the Atomicity property in PostgreSQL?
Atomicity ensures that all operations in a transaction are completed successfully. If any operation fails, the entire transaction is rolled back, maintaining database integrity.
What are some advantages of using PostgreSQL?
Advantages of PostgreSQL include:
- Open-source and free to use.
- Strong community support.
- ACID compliance.
- Advanced indexing techniques.
- Full-text search support.
- Various replication methods.
- Extensibility through custom functions and data types.
How does Write-Ahead Logging help?
Write-Ahead Logging (WAL) enhances reliability by recording changes to a log before applying them to the database. This ensures that changes can be recovered in case of a crash.
What are some important PostgreSQL administration tools?
Some key administration tools for PostgreSQL are:
- psql – Command-line tool for SQL queries and database management.
- pgAdmin – Graphical interface for managing PostgreSQL databases.
- phpPgAdmin – Web-based PostgreSQL administration tool.
Why Choose Our Question Bank?
Get access to expertly crafted answers and comprehensive preparation materials
Complete Collection
Access all 36 carefully curated questions covering every aspect of PostgreSQL interviews
Expert Answers
Get detailed, professional answers crafted by industry experts with real-world experience
Instant Access
Start preparing immediately with instant access to all questions and answers after sign-up