Unit 5: Introduction to PostgreSQL - Practice Quiz
1 What type of database model does PostgreSQL primarily use?
2 The acronym ACID describes properties that guarantee transaction reliability. What does the 'C' in ACID stand for?
3 Which of the following best describes PostgreSQL?
4 The name "PostgreSQL" is a successor to which earlier database project?
5 What is the default network port number that PostgreSQL listens on for client connections?
6 During a standard installation of PostgreSQL, what is the default superuser account name that is created?
7 Which command-line tool is the native, interactive terminal for working with PostgreSQL?
8
On a Debian/Ubuntu system, which apt command is used to install the PostgreSQL server package?
9 Which SQL keyword is used to retrieve data from a database table?
10
What is the purpose of the CREATE TABLE statement in SQL?
11
In a SELECT statement, which clause is used to filter the results based on a specific condition?
12
What character is used to terminate most SQL statements in tools like psql?
13 Which SQL command corresponds to the 'Create' operation in CRUD?
14 Which SQL command corresponds to the 'Read' operation in CRUD?
15 Which SQL command corresponds to the 'Update' operation in CRUD?
16 Which SQL command corresponds to the 'Delete' operation in CRUD?
17 What is the primary role of Prisma in a Node.js application?
18 In a Prisma project, what is the standard name of the file where you define your database schema models?
19 Which Prisma CLI command is used to apply pending schema changes to the database by creating a new migration?
20
After changing your schema.prisma file, what command must you run to update the type-safe Prisma Client?
21 In the context of PostgreSQL's concurrency control, what is a primary advantage of using Multi-Version Concurrency Control (MVCC) over traditional read/write locking mechanisms?
22 You are designing a multi-tenant application where each tenant's data must be logically separated but reside within the same PostgreSQL database. What is the most appropriate PostgreSQL feature to achieve this namespace-level separation?
tenant_id column.
23 After installing PostgreSQL, you are unable to connect to the database server from a remote machine. Which configuration file is most likely responsible for controlling which hosts are allowed to connect, and what parameter needs to be adjusted?
pg_ident.conf by mapping the remote user to a local user.
postgresql.conf by setting the allow_remote_connections parameter.
environment file by setting the PGHOST variable.
pg_hba.conf by adding a rule for the remote host's IP address.
24
What is the primary responsibility of the initdb command in the PostgreSQL setup process?
25
You need to find the employee with the highest salary in each department from an employees table. Which query structure is most appropriate for this task?
WHERE clause to find the global maximum salary.
GROUP BY clause with a MAX() aggregate function on the salary.
ORDER BY clause on salary with a LIMIT 1 clause.
RANK() or ROW_NUMBER() partitioned by department.
26
What is a key difference in behavior between TRUNCATE TABLE users; and DELETE FROM users; in PostgreSQL?
TRUNCATE can be used with a WHERE clause for selective deletion.
TRUNCATE is non-transactional and cannot be rolled back, while DELETE can.
TRUNCATE does not fire ON DELETE triggers, while DELETE does.
DELETE is always faster as it logs less information to the WAL.
27 You need to perform a multi-step query: first, aggregate daily sales, and then, using that result, calculate the 7-day moving average. Which SQL feature is best suited for structuring such a query for readability and performance?
FROM clause.
HAVING clause to perform the second-step calculation.
WITH clause to define a Common Table Expression (CTE).
VIEW for the daily sales.
28
You want to insert a new user with email = 'test@example.com', but if a user with that email already exists, you want to do nothing and avoid an error. Which PostgreSQL-specific query achieves this?
INSERT INTO users (email) VALUES ('test@example.com') ON DUPLICATE KEY IGNORE;INSERT INTO users (email) VALUES ('test@example.com') ON CONFLICT (email) DO NOTHING;INSERT INTO users (email) VALUES ('test@example.com') WHERE email != 'test@example.com';IF NOT EXISTS (SELECT 1 FROM users WHERE email = 'test@example.com') THEN
INSERT INTO users (email) VALUES ('test@example.com');
END IF;
29
Which SQL statement correctly updates the price of a product and returns its new price and name in a single, atomic operation in PostgreSQL?
UPDATE products SET price = 150.00 WHERE id = 42;
SELECT name, price FROM products WHERE id = 42;UPDATE products SET price = 150.00 WHERE id = 42 OUTPUT updated.name, updated.price;UPDATE products SET price = 150.00 WHERE id = 42 RETURNING name, price;BEGIN;
UPDATE products SET price = 150.00 WHERE id = 42;
SELECT name, price FROM products WHERE id = 42;
COMMIT;
30
An orders table has a product_id foreign key referencing the products table with the ON DELETE RESTRICT action. What is the outcome if you attempt to delete a product that is referenced by at least one order?
product_id in the orders table is set to NULL.
product_id in orders is set to its default value.
31
How would you write a query to select all tasks and order them by their priority (High, Medium, Low) and then by their creation_date in descending order?
ORDER BY priority, creation_dateORDER BY FIELD(priority, 'High', 'Medium', 'Low'), creation_date DESCORDER BY creation_date DESC, priority ASCORDER BY
CASE priority
WHEN 'High' THEN 1
WHEN 'Medium' THEN 2
WHEN 'Low' THEN 3
END,
creation_date DESC
32
In a Prisma schema, how do you define a one-to-many relationship where a User can have multiple Post records?
UserPosts with relations to both User and Post.
userId Int to the User model and posts Post[] @relation(fields: [userId], references: [id]).
posts Post[] to the User model and author User @relation(fields: [authorId], references: [id]) and authorId Int to the Post model.
posts Post[] to the User model and author User to the Post model, letting Prisma handle the foreign key implicitly.
33
You have updated your schema.prisma file. What is the primary purpose of running the prisma migrate dev command?
34 Using the Prisma Client in a TypeScript application, which query finds a unique user by their email and includes their 10 most recent posts, sorted by creation date?
await prisma.user.findUnique({
where: { email },
include: {
posts: {
orderBy: { createdAt: 'desc' },
take: 10
}
}
});await prisma.user.findMany({
where: { email },
include: { posts: { limit: 10 } }
});await prisma.user.findUnique({
where: { email },
select: {
posts: { take: 10, sort: 'createdAt' }
}
});await prisma.user.findUnique({
where: { email },
include: { posts: true }
});
35
What is the purpose of the prisma db pull command in a Prisma workflow?
schema.prisma file to match.
36 You need to create a new user and a new profile for that user in a single, atomic database transaction. Which Prisma Client feature is designed for this purpose?
prisma.$queryRaw() method.
create call.
await calls sequentially for user.create and profile.create.
prisma.$executeRaw() method with transaction control statements.
37
You have a products table with a tags column of type jsonb. The tags are stored as an array of strings, e.g., ["electronics", "mobile"]. Which query correctly finds all products that have the tag 'electronics'?
SELECT * FROM products WHERE tags LIKE '%electronics%';SELECT * FROM products WHERE tags @> '"electronics"';SELECT * FROM products WHERE 'electronics' IN tags;SELECT * FROM products WHERE tags->>'electronics' IS NOT NULL;
38
Which of the following statements best describes the purpose of the template1 database in a PostgreSQL cluster?
39 From the command line on a Linux server, which utility is most commonly used to connect to a PostgreSQL database, execute SQL queries interactively, and view the results?
psql
createdb
pg_dump
pg_ctl
40
You need to sort a list of products by their last_updated timestamp in descending order, but products that have never been updated (NULL timestamp) should appear at the very beginning of the list. Which ORDER BY clause accomplishes this?
ORDER BY last_updated DESC NULLS LAST
ORDER BY last_updated DESC NULLS FIRST
ORDER BY last_updated DESC
ORDER BY last_updated ASC NULLS FIRST
41
A transaction T1 is running at the REPEATABLE READ isolation level. It executes SELECT COUNT(*) FROM products WHERE category = 'electronics'. Before T1 commits, another transaction T2 commits after successfully inserting a new product with category = 'electronics'. If T1 re-runs the same SELECT query, what will be the result, and why?
T1 will be aborted with a serialization failure error when it tries to re-run the query.
REPEATABLE READ as defined by the SQL standard does not prevent phantom reads.
REPEATABLE READ in PostgreSQL uses an MVCC snapshot taken at the start of the transaction, which prevents phantom reads.
42
In a high-traffic PostgreSQL database with frequent UPDATE and DELETE operations, what is the most critical, system-halting consequence of autovacuum failing to run or being unable to keep up with the rate of change for an extended period?
WRITE operations due to the risk of transaction ID (XID) wraparound failure.
43 Which statement most accurately describes the relationship between a Checkpoint and the Write-Ahead Log (WAL) in PostgreSQL's recovery mechanism?
COMMIT operations are durable.
44 PostgreSQL uses a multi-process architecture where the main 'postmaster' process forks a new backend process for each client connection. In contrast, many other databases use a multi-threaded model. What is a key architectural trade-off of PostgreSQL's approach?
45
You are tuning a PostgreSQL server for a data warehouse workload characterized by a few, very large, complex queries running concurrently. These queries perform large joins, aggregations, and sorting. You observe significant temporary file I/O. Which two parameters in postgresql.conf are most crucial to adjust to optimize for this specific workload?
work_mem and shared_buffers
max_connections and wal_buffers
shared_buffers and effective_cache_size
work_mem and maintenance_work_mem
46
A pg_hba.conf file contains the following entries in this specific order:
# TYPE DATABASE USER ADDRESS METHOD
host all all 192.168.1.0/24 scram-sha-256
host all admin 192.168.1.50/32 reject
A user 'admin' attempts to connect from the IP address 192.168.1.50 to the sales database. What will be the outcome of the connection attempt?
/32) always takes precedence over a less specific CIDR range (/24).
scram-sha-256 authentication.
47
To mitigate I/O spikes during checkpoints, a DBA sets checkpoint_completion_target = 0.9. How does this setting interact with checkpoint_timeout and max_wal_size?
checkpoint_timeout) or WAL size (max_wal_size).
checkpoint_timeout interval, leaving the last 10% of the time as an I/O-free buffer.
checkpoint_timeout) and only applies to checkpoints triggered by max_wal_size.
48
You are configuring a PostgreSQL server that will be accessed by an application running inside a Docker container on the same host machine. For maximum performance and security, what is the recommended host type to use in pg_hba.conf for this connection?
host with address ::1/128
host with the Docker bridge network's CIDR address (e.g., 172.17.0.0/16)
host with address 127.0.0.1/32
local
49
Given a table page_views with user_id and view_timestamp, you want to calculate the average time between consecutive page views for each user. A single SELECT statement is required. Which combination of SQL features is best suited for this?
LATERAL JOIN to find the previous page view for each row.
LAG() window function to get the timestamp of the previous view, followed by aggregation on the calculated time difference.
page_views with the condition t1.view_timestamp > t2.view_timestamp and GROUP BY t1.user_id.
50
You have a table employees (id, name, department, salary). You need to write a query that returns each employee's name, department, and their salary's rank within their department, but also their salary's rank across the entire company, both in separate columns. Which query correctly achieves this?
SELECT name, department,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) as dept_rank,
RANK() OVER (ORDER BY salary DESC) as overall_rank
FROM employees;SELECT name, department,
RANK() OVER (ORDER BY department, salary DESC) as dept_rank,
RANK() OVER (ORDER BY salary DESC) as overall_rank
FROM employees;SELECT name, department,
(SELECT COUNT(*) + 1 FROM employees e2 WHERE e2.department = e1.department AND e2.salary > e1.salary) as dept_rank,
(SELECT COUNT(*) + 1 FROM employees e2 WHERE e2.salary > e1.salary) as overall_rank
FROM employees e1;WITH dept_rank AS (
SELECT id, RANK() OVER (PARTITION BY department ORDER BY salary DESC) r FROM employees
), overall_rank AS (
SELECT id, RANK() OVER (ORDER BY salary DESC) r FROM employees
)
SELECT e.name, e.department, dr.r, or.r
FROM employees e JOIN dept_rank dr ON e.id = dr.id JOIN overall_rank or ON e.id = or.id;
51
What is the primary difference in behavior between ROW_NUMBER(), RANK(), and DENSE_RANK() when used as window functions on a set of rows with duplicate values in the ORDER BY clause?
PARTITION BY clause is also used.
ROW_NUMBER and DENSE_RANK are identical, but RANK leaves gaps for ties.
RANK and DENSE_RANK are identical, but ROW_NUMBER assigns a random number to break ties.
ROW_NUMBER assigns unique numbers, RANK leaves gaps after ties, DENSE_RANK does not leave gaps after ties.
52
You have a products table and a product_tags table (product_id, tag). You need to find all products that have the tag 'new' AND the tag 'sale', but NOT the tag 'clearance'. Which query is the most efficient and accurate way to express this complex set-based condition?
SELECT p.* FROM products p
JOIN product_tags t1 ON p.id = t1.product_id AND t1.tag = 'new'
JOIN product_tags t2 ON p.id = t2.product_id AND t2.tag = 'sale'
LEFT JOIN product_tags t3 ON p.id = t3.product_id AND t3.tag = 'clearance'
WHERE t3.product_id IS NULL;SELECT p.* FROM products p WHERE
EXISTS (SELECT 1 FROM product_tags WHERE product_id = p.id AND tag = 'new') AND
EXISTS (SELECT 1 FROM product_tags WHERE product_id = p.id AND tag = 'sale') AND
NOT EXISTS (SELECT 1 FROM product_tags WHERE product_id = p.id AND tag = 'clearance');SELECT product_id FROM product_tags
GROUP BY product_id
HAVING ARRAY_AGG(tag) @> ARRAY['new', 'sale']
AND NOT (ARRAY_AGG(tag) && ARRAY['clearance']);SELECT product_id FROM product_tags WHERE tag = 'new'
INTERSECT
SELECT product_id FROM product_tags WHERE tag = 'sale'
EXCEPT
SELECT product_id FROM product_tags WHERE tag = 'clearance';
53
You have a counters table with a name (unique) and value column. You need an atomic operation to increment a counter by 1. If the counter does not exist, it should be inserted with an initial value of 1. Which SQL statement correctly performs this "upsert-increment" operation?
INSERT INTO counters (name, value) VALUES ('page_views', 1)
ON CONFLICT (name) DO UPDATE SET value = counters.value + 1;UPDATE counters SET value = value + 1 WHERE name = 'page_views';
IF NOT FOUND THEN
INSERT INTO counters (name, value) VALUES ('page_views', 1);
END IF;INSERT INTO counters (name, value) VALUES ('page_views', 1)
ON CONFLICT (name) DO UPDATE SET value = counters.value + EXCLUDED.value;INSERT INTO counters (name, value) VALUES ('page_views', 1)
ON CONFLICT (name) DO UPDATE SET value = value + 1;
54
You are implementing a 'soft delete' pattern by updating a deleted_at timestamp on a table. To prevent race conditions where two processes try to soft-delete the same record, you want to ensure the UPDATE only affects the row if it hasn't been deleted already. You also need to get the id of the row that was successfully updated. Which query is the most robust?
UPDATE products SET deleted_at = NOW()
WHERE id = 123 AND deleted_at IS NULL
RETURNING id;UPDATE products SET deleted_at = NOW() WHERE id = 123;
SELECT id FROM products WHERE id = 123 AND deleted_at IS NOT NULL;WITH updated AS (
UPDATE products SET deleted_at = NOW() WHERE id = 123
)
SELECT id FROM products WHERE id = 123 AND deleted_at IS NOT NULL;BEGIN;
SELECT id FROM products WHERE id = 123 AND deleted_at IS NULL FOR UPDATE;
-- (check in application logic if a row was returned)
UPDATE products SET deleted_at = NOW() WHERE id = 123;
COMMIT;
SELECT id FROM products WHERE id = 123;55 What is a data-modifying Common Table Expression (CTE) in PostgreSQL, and what is a key advantage of using one for a task like moving rows from one table to another?
SELECT statements to modify data in memory without writing to disk, improving performance for read-heavy workloads.
UPDATE statements to be run directly against the view definition.
UPDATE, INSERT, or DELETE statement. Its key advantage is that the entire operation, including the data modification and any subsequent use of the modified data (e.g., in an INSERT), occurs within a single atomic statement.
56
Consider a DELETE statement with a USING clause: DELETE FROM employees_staging es USING employees_production ep WHERE es.employee_id = ep.employee_id;. What does this statement do?
employees_production that have a matching employee_id in employees_staging.
employees_staging, but will fail because the alias es is not referenced in the WHERE clause.
employees_staging that have a matching employee_id in employees_production.
employees_staging and employees_production where the employee_id matches.
57
You have a Prisma schema with a many-to-many relationship between Post and Tag using an explicit join table. How do you write a Prisma Client query to find all Posts that have at least one Tag with a name starting with 'tech' and are also written by a User whose email contains '@example.com'?
prisma.post.findMany({
where: {
tags: { every: { tag: { name: { startsWith: 'tech' } } } },
author: { email: { contains: '@example.com' } }
}
});prisma.post.findMany({
where: {
tags: { some: { tag: { name: { startsWith: 'tech' } } } },
author: { email: { contains: '@example.com' } }
}
});prisma.post.findMany({
where: {
AND: [
{ tags: { some: { tag: { name: { startsWith: 'tech' } } } } },
{ author: { email: { contains: '@example.com' } } }
]
}
});prisma.post.findMany({
include: { tags: true, author: true },
where: {
tags: { name: { startsWith: 'tech' } },
author: { email: { contains: '@example.com' } }
}
});58 You need to perform a complex, multi-step operation: 1. Read a user's profile. 2. Based on their country, calculate a shipping cost. 3. Create a new order for that user with the calculated cost. 4. Decrement the stock of the ordered product. This entire sequence must be atomic. Which Prisma feature is specifically designed for such interdependent read-then-write operations within a single transaction?
prisma.$transaction([ ... ]) with an array of Prisma client operations.
await, relying on the database's default transaction handling.
prisma.$executeRawUnsafe() to manually write a PL/pgSQL function that encapsulates the logic.
prisma.$transaction(async (tx) => { ... }) with an interactive transaction callback.
59
What is the primary purpose of the 'shadow database' used by Prisma Migrate during development (prisma migrate dev)?
schema.prisma file's state, allowing for version control of the schema.
60
In a Prisma schema, you define a one-to-many relation between User and Post. What is the functional difference between defining the relation field on the User model as posts Post[] versus omitting it entirely?
posts Post[] field is purely for documentation and is ignored by the Prisma Client.
posts Post[]) makes the relation uni-directional from the Post's perspective. You can still query from Post to User, but you cannot easily query from User to their Posts via the Prisma Client's fluent API.
Post records associated with a User.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →