SQL Interview Questions for AWS Cloud Engineers: Transactions, Isolation Levels, EXPLAIN Tuning and SQL on RDS, Aurora, Redshift and DynamoDB PartiQL (50 Questions)
This page has 50 SQL interview questions for cloud and AWS engineers on transactions, isolation levels, query tuning with EXPLAIN, and how SQL behaves on Amazon RDS, Aurora, Redshift and DynamoDB (PartiQL). The previous page covered queries, joins and indexes.
1. An everyday example: a bank counter
Why are transactions and tuning asked so often?
Most serious production bugs with databases are about two things: data that becomes wrong when many users act at once, and queries that become slow as data grows. Interviewers want to know you can prevent the first and fix the second.
Think of a bank counter. A transaction is one customer's full request, such as "move 5,000 rupees from savings to current". It must happen completely or not at all, even if the power fails halfway. Isolation decides what other customers can see while that request is in progress. Tuning is making the queue move faster without making mistakes.
How to use this page
- Open two psql or mysql sessions side by side to try the isolation and locking examples.
- Use a test RDS instance or a local database, never production.
- All data is made up.
2. Fresher level questions
Start here if you are a fresher or have less than two years of experience. Try to answer each question aloud first. Then open it and compare.
Q1. What does ACID mean? Explain it with a money transfer. Fresher
Transfer 5,000 from account A to account B:
- Atomicity: both the debit and the credit happen, or neither does.
- Consistency: rules stay true, for example a balance cannot go below zero if a constraint says so.
- Isolation: other transactions do not see the half-done state (A debited, B not yet credited).
- Durability: once committed, the transfer survives a crash or failover.
Relational databases on RDS and Aurora provide ACID transactions. Many NoSQL and analytics systems provide weaker or different guarantees.
Q2. How do you run a transaction by hand in psql, and what happens on ROLLBACK? Fresher
Output:
BEGIN;
UPDATE accounts SET balance = balance - 5000 WHERE id = 'A';
UPDATE accounts SET balance = balance + 5000 WHERE id = 'B';
SELECT id, balance FROM accounts WHERE id IN ('A','B');
ROLLBACK;Inside the transaction you see the new balances, but after ROLLBACK both changes are undone, as if nothing happened. COMMIT would make them permanent.
Other sessions never saw the changed balances, because they were not committed.
Q3. What is autocommit, and how can it surprise you? Fresher
In autocommit mode (the default in psql, the mysql client and most drivers), every statement is its own transaction and is committed immediately.
Surprises:
- An UPDATE without WHERE is committed at once; there is no undo.
- Some tools or drivers turn autocommit off, so your changes are never committed and they disappear when you disconnect, or they hold locks until you commit.
For manual production changes, start with BEGIN, check the row count, and only then COMMIT.
Q4. What is normalization? Explain 1NF, 2NF and 3NF simply. Fresher
Normalization organises tables so each fact is stored once, which avoids update mistakes.
- 1NF: each column holds one value (no "phone1, phone2" lists in one field) and rows are unique.
- 2NF: in a table with a composite key, every column depends on the whole key, not part of it (product_name belongs in products, not in order_items keyed by order and product).
- 3NF: non-key columns depend only on the key, not on other non-key columns (city_name belongs with city_id in a cities table, not repeated in every customer row).
Result: changing a product name means updating one row, not thousands.
Q5. What is denormalization, and when is it the right choice on AWS? Fresher
Denormalization means storing some data more than once on purpose to make reads faster or simpler.
Right choice when:
- Reporting and analytics in Redshift or Athena, where wide tables and star schemas avoid expensive joins.
- DynamoDB, where you design items around access patterns and copy data into items or indexes because there are no joins.
- Read-heavy OLTP screens, using a summary column or table (for example order_count on customers).
Cost: extra storage and the need to keep copies in sync. Keep the source of truth normalized.
Q6. What does EXPLAIN show? Read a simple example. Fresher
EXPLAIN shows the plan the database will use, without running the query.
Output:
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
Seq Scan on orders (cost=0.00..412000.00 rows=95 width=64)
Filter: (customer_id = 42)PostgreSQL plans to read the whole table (Seq Scan) to find about 95 rows. After CREATE INDEX on orders(customer_id), the plan becomes "Index Scan using idx_orders_customer" with a much lower cost.
Cost numbers are estimates in internal units, not milliseconds.
Q7. What is the difference between EXPLAIN and EXPLAIN ANALYZE, and what is the danger? Fresher
- EXPLAIN only plans the query.
- EXPLAIN ANALYZE runs the query and shows actual times and row counts next to the estimates.
Danger: EXPLAIN ANALYZE on an UPDATE or DELETE really changes data. Wrap it:
Output:
BEGIN;
EXPLAIN ANALYZE DELETE FROM sessions WHERE expires_at < now();
ROLLBACK;It also runs the full query, so a 10-minute query takes 10 minutes. Use it on a clone or replica for very heavy queries.
Q8. What is a deadlock? What does the error look like? Fresher
A deadlock happens when two transactions each hold a lock the other needs, so neither can continue. The database detects it and cancels one of them.
Output:
ERROR: deadlock detected
DETAIL: Process 4121 waits for ShareLock on transaction 99812; blocked by process 4377.
Process 4377 waits for ShareLock on transaction 99811; blocked by process 4121.One transaction was rolled back so the other could finish. The application should retry the failed transaction. MySQL shows "Deadlock found when trying to get lock; try restarting transaction".
Q9. What are the four standard isolation levels, and what are the defaults in PostgreSQL and MySQL? Fresher
From weakest to strongest:
- READ UNCOMMITTED
- READ COMMITTED
- REPEATABLE READ
- SERIALIZABLE
Defaults: PostgreSQL uses READ COMMITTED; MySQL InnoDB uses REPEATABLE READ. Aurora follows its engine's defaults.
Note: PostgreSQL treats READ UNCOMMITTED like READ COMMITTED, so it never shows dirty reads.
Q10. What are dirty reads, non-repeatable reads and phantom reads? Fresher
- Dirty read: you read another transaction's change before it commits; if it rolls back, you used data that never existed.
- Non-repeatable read: you read a row twice in one transaction and get different values, because someone committed an update in between.
- Phantom read: you run the same range query twice and new rows appear, because someone inserted matching rows.
Stronger isolation levels prevent more of these, at the cost of more locking, waiting or retries.
Q11. How do you check and change the isolation level for a session? Fresher
PostgreSQL:
Output:
SHOW transaction_isolation;
read committed
BEGIN ISOLATION LEVEL REPEATABLE READ;MySQL:
Output:
SELECT @@transaction_isolation;
REPEATABLE-READ
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;You can change it per transaction or session. To change the default for the whole RDS instance, set the parameter in the DB parameter group (default_transaction_isolation in PostgreSQL, transaction_isolation in MySQL).
Q12. What is a savepoint? Fresher
A savepoint is a marker inside a transaction that you can roll back to without undoing the whole transaction.
Output:
BEGIN;
INSERT INTO orders VALUES (501, 42, 1999);
SAVEPOINT before_items;
INSERT INTO order_items VALUES (501, 'SKU-BAD', 1); -- fails
ROLLBACK TO SAVEPOINT before_items;
COMMIT;The order is kept, and only the failed item insert is undone. In PostgreSQL, after an error the transaction is aborted until you roll back to a savepoint or roll back fully.
Q13. Why is DynamoDB not a relational database, even though PartiQL looks like SQL? Fresher
- No joins between tables, and no foreign keys.
- No fixed schema for non-key attributes; each item can have different attributes.
- Data is accessed by key: partition key (and sort key) or a secondary index. Queries that are not based on keys become scans.
- Transactions exist but with limits (a set number of items, in one Region's table set).
- You design the table from access patterns first, not from entities first.
PartiQL is only a SQL-like way to call the same Get, Put, Query and Scan operations.
Q14. How do you read one item from DynamoDB with PartiQL from the CLI? Fresher
aws dynamodb execute-statement --statement "SELECT order_id, status FROM \"Orders\" WHERE customer_id = ? AND order_id = ?" --parameters '[{"S":"C-42"},{"S":"O-501"}]'Output:
{"Items": [{"order_id": {"S": "O-501"}, "status": {"S": "SHIPPED"}}]}Because the WHERE clause gives the full primary key, DynamoDB does a direct lookup. Use parameters (?) instead of building the string yourself, both for safety and for correct typing.
Q15. How do you turn on the slow query log on RDS for MySQL and see it in CloudWatch? Fresher
- In a custom DB parameter group set slow_query_log = 1, long_query_time = 1 (seconds) and log_output = FILE.
- Attach the parameter group to the instance (these are dynamic parameters, no reboot needed).
- Turn on log export:
aws rds modify-db-instance --db-instance-identifier shop-mysql --cloudwatch-logs-export-configuration '{"EnableLogTypes":["slowquery"]}'queries slower than 1 second are written to the slow log and appear in CloudWatch Logs, where you can search them with Logs Insights. For PostgreSQL, the similar setting is log_min_duration_statement.
Q16. What are stored procedures and triggers, and why do many cloud teams use them sparingly? Fresher
- A stored procedure is code saved in the database and called with CALL.
- A trigger runs automatically when rows are inserted, updated or deleted.
Why sparingly:
- Logic is hidden from application developers and harder to test and version.
- Triggers add work to every write and can cause surprises during bulk loads and migrations.
- Moving between engines (for example Oracle to PostgreSQL) is harder.
Good uses: small, data-close rules such as audit columns or keeping a summary row in sync.
Q17. What are table statistics, and why does running ANALYZE sometimes fix a slow query? Fresher
The query planner uses statistics (row counts, common values, value spread) to estimate how many rows each step returns, and chooses scans and join methods from those estimates.
If statistics are old (for example after a big data load), the planner may think a filter returns 10 rows when it returns 2 million, and choose a bad plan.
Output:
ANALYZE orders;statistics are refreshed, and the next plan is based on current data. Autovacuum normally does this in PostgreSQL, but after large loads or major version upgrades, run ANALYZE yourself.
3. Mid level questions
These questions check how you use the service in real projects. Interviewers expect the why, the how and one real example.
Q18. Show the difference between READ COMMITTED and REPEATABLE READ with two sessions. Mid level
Session 1 (READ COMMITTED):
Output:
BEGIN; SELECT price FROM products WHERE id = 7; -- 100Session 2:
Output:
UPDATE products SET price = 120 WHERE id = 7; COMMIT;Session 1:
Output:
SELECT price FROM products WHERE id = 7; -- 120 (changed inside the same transaction)With REPEATABLE READ in session 1, the second SELECT still returns 100, because the transaction reads from one snapshot taken at its first query.
Use REPEATABLE READ when a transaction must see one consistent view, such as a report that reads several tables.
Q19. What happens at the SERIALIZABLE level in PostgreSQL, and what must the application do? Mid level
SERIALIZABLE makes concurrent transactions behave as if they ran one after another. PostgreSQL does this by watching for dangerous patterns and cancelling one transaction:
Output:
ERROR: could not serialize access due to read/write dependencies among transactionsYour transaction was rolled back to keep the data correct. The application must retry the whole transaction (with a limit and a small backoff).
Use it for complex rules that are hard to protect with simple locks, such as "no more than 3 doctors on call", and keep those transactions short.
Q20. How do you reserve the last seat safely with SELECT ... FOR UPDATE? Mid level
Output:
BEGIN;
SELECT seats_left FROM shows WHERE show_id = 9 FOR UPDATE;
-- if seats_left > 0:
UPDATE shows SET seats_left = seats_left - 1 WHERE show_id = 9;
INSERT INTO bookings (show_id, user_id) VALUES (9, 'U-77');
COMMIT;FOR UPDATE locks the show row, so a second buyer's transaction waits until the first commits, then sees the new count. Without it, both could read 1 and both book the last seat.
A simpler option for counters: one atomic statement, UPDATE shows SET seats_left = seats_left - 1 WHERE show_id = 9 AND seats_left > 0, and check that 1 row was updated.
Q21. How can many workers take jobs from a database table without fighting over the same rows? Mid level
Use FOR UPDATE SKIP LOCKED:
Output:
BEGIN;
SELECT job_id FROM jobs WHERE status = 'READY' ORDER BY created_at LIMIT 10 FOR UPDATE SKIP LOCKED;
UPDATE jobs SET status = 'RUNNING', worker = 'w3' WHERE job_id IN (...);
COMMIT;Each worker locks up to 10 ready jobs and skips rows other workers have already locked, so there is no waiting and no double processing.
Works in PostgreSQL and MySQL 8. For high volume, a real queue such as SQS is usually better than a table.
Q22. How do you read EXPLAIN ANALYZE output to find the real problem? Mid level
Output:
Nested Loop (actual time=0.05..48211.30 rows=1850000 loops=1)
-> Seq Scan on order_items (rows=1850000) (estimated rows=1200)
-> Index Scan using products_pkey on products (loops=1850000)What to look for:
- Estimated vs actual rows: 1,200 estimated vs 1,850,000 actual means bad statistics or a hard-to-estimate filter; the planner picked a nested loop for a small input.
- loops: the inner index scan ran 1.85 million times.
- Where the time goes: the node with the largest actual time.
- Sorts or hashes spilling to disk ("external merge").
Fix the estimate first (ANALYZE, better filters, extended statistics), then indexes or query shape.
Q23. How do you find the queries that use the most database time on RDS PostgreSQL? Mid level
Use the pg_stat_statements extension (it is usually preloaded on RDS; check shared_preload_libraries in the parameter group, then run CREATE EXTENSION pg_stat_statements).
Output:
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time,1) AS mean_ms, left(query, 60)
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;
1820455 | 9112330 | 5.0 | SELECT * FROM carts WHERE session_id = $1A 5 ms query called 1.8 million times uses more total time than one slow report. Fix by total time, not only by the slowest query. CloudWatch Database Insights shows the same picture as database load by SQL and wait event.
Q24. What problems does a session left "idle in transaction" cause in PostgreSQL? Mid level
Output:
SELECT pid, state, now() - xact_start AS age, left(query, 40) FROM pg_stat_activity WHERE state = 'idle in transaction' ORDER BY age DESC;
30122 | idle in transaction | 03:12:44 | UPDATE carts SET ...A session opened a transaction 3 hours ago and never committed.
Problems: it holds row locks (blocking others), and it stops vacuum from removing dead rows, so tables bloat.
Fix: find the application bug (missing commit, exception path), and set idle_in_transaction_session_timeout (for example 5 minutes) in the parameter group for app users.
Q25. How do you find which session is blocking others? Mid level
PostgreSQL:
Output:
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, left(query, 50)
FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;
4410 | {3981} | Lock | UPDATE orders SET status = ...session 4410 waits for a lock held by session 3981. Look at 3981's query and transaction age.
MySQL 8: query sys.innodb_lock_waits for the waiting and blocking threads.
Then decide: wait, fix the application, or cancel the blocker (see the next question).
Q26. How do you cancel a runaway query on RDS, where you have no superuser? Mid level
PostgreSQL (rds_superuser or the master user can do this):
Output:
SELECT pg_cancel_backend(3981); -- cancels the current query
SELECT pg_terminate_backend(3981); -- ends the whole sessionMySQL on RDS (KILL on other users' threads is replaced by procedures):
Output:
CALL mysql.rds_kill_query(3981);
CALL mysql.rds_kill(3981);try cancelling the query first; terminate only if needed, because the session's open transaction is rolled back, which can itself take time for big changes.
Q27. What is table bloat in PostgreSQL, and how do you check it on RDS? Mid level
PostgreSQL keeps old row versions after UPDATE and DELETE (MVCC). Vacuum marks that space for reuse. If vacuum cannot keep up, tables and indexes grow with dead rows: this is bloat, and it makes scans and caching worse.
Output:
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 5;
sessions | 2100000 | 9800000 | 2026-11-12 03:10sessions has many more dead rows than live ones and has not been vacuumed for a week.
Fix: tune autovacuum for that table (lower scale factor), remove long-running transactions, and consider pg_repack (supported on RDS) for heavy bloat.
Q28. How do you read the "type" column in MySQL EXPLAIN? Mid level
From best to worst (common values):
- const / eq_ref: one row by primary key or unique key.
- ref: rows found by a non-unique index value.
- range: an index range, such as a BETWEEN on an indexed column.
- index: a full scan of an index.
- ALL: a full table scan.
Output:
EXPLAIN SELECT * FROM orders WHERE status = 'PENDING';
type: ALL possible_keys: NULL rows: 18233900 Extra: Using whereNo usable index, so MySQL reads 18 million rows. Also watch Extra for "Using filesort" and "Using temporary".
Q29. What is a lost update, and how do you prevent it? Mid level
Two users read stock = 10, both subtract 1 in application code and write 9. One update is lost; stock should be 8.
Prevent it with:
- Atomic updates: UPDATE products SET stock = stock - 1 WHERE id = 7 AND stock > 0.
- Row locks: SELECT ... FOR UPDATE before changing.
- Version checks: UPDATE ... SET stock = 9, version = 6 WHERE id = 7 AND version = 5, and retry if 0 rows changed.
- A stricter isolation level that detects the conflict.
The atomic update is simplest when the change can be written as one statement.
Q30. After writing a row to Aurora, the app reads it from a reader and it is missing. Why, and how do you design around it? Mid level
Aurora readers share storage with the writer, but each reader applies changes from the writer with a small delay (replica lag, usually tens of milliseconds, sometimes more under load). Reading right after writing can see old data.
Designs:
- Read-your-writes: send reads that follow a user's own write to the writer (cluster endpoint), for example for a few seconds or within the same request.
- Use readers for data that can be slightly stale (lists, search, reports).
- Monitor AuroraReplicaLag.
- For Aurora MySQL, read-after-write consistency settings for write forwarding exist; for others, route in the application or a proxy.
Q31. Redshift accepted duplicate rows even though the table has a PRIMARY KEY. Why? Mid level
Redshift does not enforce primary key, unique or foreign key constraints. They are informational: the planner uses them to optimise queries, assuming they are true.
So duplicate loads (for example running a COPY twice) create duplicate rows, and the planner's assumption can even give wrong results for some queries.
Fix:
- Make loads idempotent: load into a staging table, then MERGE (or delete-then-insert in one transaction) into the target.
- Check duplicates after loads with GROUP BY key HAVING COUNT(*) > 1.
Q32. How do you upsert a day's changes into a Redshift table? Mid level
Load the changes into a staging table with COPY, then:
Output:
MERGE INTO sales USING sales_stage s
ON sales.sale_id = s.sale_id
WHEN MATCHED THEN UPDATE SET amount = s.amount, status = s.status
WHEN NOT MATCHED THEN INSERT VALUES (s.sale_id, s.amount, s.status, s.sale_date);existing sales are updated and new ones inserted in one statement.
Avoid row-by-row INSERT and UPDATE from an application in Redshift: it is a columnar warehouse built for bulk operations, and single-row changes are slow and leave deleted rows to clean up.
Q33. How do you run several DynamoDB writes as one PartiQL transaction? Mid level
aws dynamodb execute-transaction --transact-statements file://order-tx.jsonorder-tx.json holds two statements with parameters:
Output:
UPDATE "Inventory" SET stock = stock - 1 WHERE sku = ? AND stock > 0 (SKU-9)
INSERT INTO "Orders" VALUE {'order_id': ?, 'sku': ?} (O-77, SKU-9)The stock decrease and the new order succeed together or fail together. If stock is 0, the condition fails and the order is not created.
For many independent reads or writes without all-or-nothing, use batch-execute-statement instead.
Q34. What is a star schema, and why is it used in Redshift? Mid level
A star schema has one large fact table (events you measure, such as sales lines with amount and quantity) surrounded by dimension tables (who, what, where, when: customers, products, stores, dates).
Why in Redshift:
- Simple joins from the fact to each dimension.
- Small dimensions can be copied to every node (DISTSTYLE ALL), and the fact table can be distributed and sorted for common filters like date.
- Business users understand it easily.
Your OLTP database stays normalized; the warehouse uses a star schema built from it.
Q47. Why is SELECT COUNT(*) on a huge PostgreSQL table slow, and what can you use instead? Mid level
PostgreSQL must check each row's visibility for your transaction (MVCC), so an exact COUNT(*) reads the whole table or a whole index.
Options:
- If an estimate is fine (dashboards, admin pages):
Output:
SELECT reltuples::bigint AS approx_rows FROM pg_class WHERE relname = 'orders';- Count a filtered, indexed subset instead of everything.
- Keep a counter or summary table updated by the application or in batches.
- For analytics, count in the warehouse.
Ask the business whether "about 52 million" is good enough before building something complex.
4. Senior level and scenario questions
These questions check design thinking and troubleshooting. Think aloud. Say what you check first, what you change, and how you prevent it next time.
Q35. Design a money transfer between two wallets that cannot double-spend or deadlock. Senior
- One transaction for the debit, the credit and a ledger insert.
- Lock both wallet rows in a fixed order (for example lower wallet ID first) with SELECT ... FOR UPDATE, so two opposite transfers cannot deadlock each other.
- Check balance after locking; reject if insufficient.
- Idempotency key from the client stored with a unique constraint, so a retried request does not transfer twice.
- Append-only ledger table as the source of truth; balances can be rebuilt from it.
- Retry on deadlock or serialization errors with a limit.
Q36. After a release, deadlocks jump from zero to hundreds per hour. How do you investigate? Senior
- Get the details: PostgreSQL logs "deadlock detected" with both queries (set log_lock_waits = on too); MySQL: SHOW ENGINE INNODB STATUS shows the latest deadlock, or turn on innodb_print_all_deadlocks to log every one.
- Compare the two statements: usually the new code updates the same tables or rows in a different order than old code, or a new index or foreign key changed which rows get locked.
- Fix: same order of row and table access everywhere, smaller transactions, avoid locking ranges unnecessarily, add indexes so updates lock fewer rows.
- Keep retry logic, but do not hide the root cause with retries alone.
Q37. A query takes 50 ms in staging and 40 seconds in production. What could be different? Senior
- Data volume and distribution: one tenant in production has 100 times more rows, so the plan that is good for small tenants is bad for it.
- Statistics: production stats are stale after a large load.
- Different indexes or parameter group settings (work_mem, random_page_cost).
- Prepared statements: a generic plan chosen for all parameter values.
- Locks or contention that do not exist in staging.
- Smaller instance class or exhausted storage IOPS or burst balance in production.
Compare EXPLAIN ANALYZE in both with the exact same parameters, and test against a production clone.
Q38. RDS PostgreSQL CPU is at 100%. How do you find the cause and bring it down? Senior
- Database Insights / Performance Insights view: database load by top SQL and wait events. CPU waits point to queries doing too much work.
- pg_stat_statements ordered by total time: often one frequent query with a missing index, or a new query from the latest release.
- EXPLAIN ANALYZE that query; look for sequential scans and bad estimates.
- Quick relief: cancel runaway queries, scale up the instance or add a read replica for read traffic.
- Real fix: index or query change, caching, or batching.
- Then alarm on CPU and on database load relative to vCPU count.
Q39. RDS PostgreSQL logs warn about transaction ID wraparound. What does it mean and what do you do? Senior
PostgreSQL uses 32-bit transaction IDs. Old rows must be "frozen" by vacuum before the counter wraps around. If vacuum cannot freeze them, PostgreSQL eventually stops accepting writes to protect data.
Output:
SELECT datname, age(datfrozenxid) FROM pg_database ORDER BY 2 DESC;Steps:
- Find what blocks vacuum: very long transactions, abandoned replication slots, prepared transactions.
- Remove the blocker, then let autovacuum run (or run VACUUM (FREEZE) on the oldest tables).
- Tune autovacuum workers and cost limits, and monitor MaximumUsedTransactionIDs in CloudWatch.
Treat it as urgent; it is a slow-moving outage.
Q40. A long report on an RDS PostgreSQL read replica fails with "canceling statement due to conflict with recovery". Why, and what are the options? Senior
The replica is applying changes from the primary. Vacuum on the primary removed row versions that the long query on the replica still needs, so PostgreSQL cancels the query to keep replication moving.
Options:
- hot_standby_feedback = on on the replica: the primary keeps those rows longer (cost: more bloat on the primary).
- Increase max_standby_streaming_delay (cost: the replica falls behind while the query runs).
- Make the report faster, or split it.
- Use a dedicated reporting copy (an Aurora clone, an export to S3 or Redshift) for very long analytics.
Q41. How do you load 50 million rows from S3 into RDS PostgreSQL quickly? Senior
- Use COPY, not INSERTs. On RDS and Aurora PostgreSQL, the aws_s3 extension can load directly:
Output:
SELECT aws_s3.table_import_from_s3('orders_stage', '', '(format csv, header true)', aws_commons.create_s3_uri('shop-loads-111122223333', 'orders/2026-11.csv', 'ap-south-1'));- The instance needs an IAM role with s3:GetObject on the bucket.
- Load into a staging table without indexes, then create indexes and constraints after the load.
- Split into several files and load in parallel sessions.
- Run ANALYZE afterwards.
- Watch storage, IOPS and WAL growth during the load; temporarily scaling up can be cheaper than a long load.
Q42. After a PostgreSQL major version upgrade on RDS, several queries became slow. What do you check first? Senior
- Statistics: run ANALYZE on all databases. In most PostgreSQL versions, optimizer statistics are not carried over by the upgrade, so plans are poor until they are rebuilt.
- Extensions: update them (ALTER EXTENSION ... UPDATE) to versions that match the new engine.
- Parameter group: the new version uses a new parameter group family; custom settings may not have been copied.
- Planner changes: compare plans for the slow queries with EXPLAIN on the old version (a snapshot restore) and the new one.
Prevention: rehearse with a blue/green deployment or a restored snapshot and replay key queries before the real upgrade.
Q43. A 2 TB orders table in PostgreSQL is slow to query and hard to clean up. When and how do you partition it? Senior
Partition when queries usually filter by one column (for example order date) and old data is removed by age.
Output:
CREATE TABLE orders (order_id bigint, created_at timestamptz, ...) PARTITION BY RANGE (created_at);
CREATE TABLE orders_2026_11 PARTITION OF orders FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');Benefits: partition pruning (queries for November read only that partition), and removing a year of data is a quick DROP or DETACH instead of a huge DELETE.
Care: queries without the partition key scan every partition; unique keys must include the partition key; create future partitions automatically (for example with pg_partman, supported on RDS).
Q44. A team wants to move from RDS to DynamoDB and use PartiQL "so we do not have to rewrite our SQL". What do you tell them? Senior
PartiQL does not remove the redesign work:
- Their joins, GROUP BY reports and ad-hoc filters do not exist in DynamoDB; filters on non-key attributes become scans that are slow and expensive.
- They need to list access patterns first, then design keys, sort keys and GSIs around them, often copying data across items.
- Reports should move to an analytics path (DynamoDB export to S3 with Athena, or zero-ETL to Redshift or OpenSearch).
- Transactions have item limits and cost more.
Recommend DynamoDB if access patterns are known and scale needs it; otherwise Aurora may be a better fit.
Q45. One row (a global counter) is updated thousands of times per second on Aurora MySQL, and everything slows down. How do you fix the hot row? Senior
Every update must lock the same row, so transactions queue behind each other.
Options:
- Sharded counters: split into N rows (counter_id, shard), update a random shard, and SUM them when reading.
- Batch in the application or a queue: add up increments for a second and write once.
- Move the counter to a store built for it (ElastiCache Redis INCR, or a DynamoDB atomic counter) and sync to Aurora periodically.
- Keep transactions short, so the lock is held for less time.
Q46. You must keep a full history of every change to the orders table for auditors. What options do you compare? Senior
| Option | How it works | Trade-off |
|---|---|---|
| Triggers into an audit table | Database writes a history row on every change | Simple, but adds write cost and lives in the same database |
| Application writes history | Code records old and new values | Easy to miss paths such as manual fixes |
| Change data capture | DMS or logical replication streams changes to S3, Kinesis or another database | No extra load in the transaction path; more moving parts |
| Database activity streams | Aurora streams database activity for security monitoring | For auditing who ran what, not a business history |
For auditors, CDC to S3 with Object Lock is a strong pattern; capture who made the change in the row itself (updated_by).
Q48. How do you choose the isolation approach for an online inventory system that must never oversell? Senior
Do not rely only on a higher isolation level; protect the exact rule:
- Atomic conditional update: UPDATE stock SET qty = qty - 1 WHERE sku = ? AND qty >= 1, and treat 0 rows updated as "out of stock".
- Keep READ COMMITTED (or the engine default) for the rest of the workload, which keeps throughput high.
- For multi-item carts, lock rows in a fixed order (by SKU) inside one short transaction, or use reservations with expiry.
- Add a CHECK (qty >= 0) constraint as the last safety net.
- For flash sales, put a queue in front so requests are processed at a controlled rate.
Q49. An interviewer asks you to prove a non-repeatable read happens at READ COMMITTED. How do you demonstrate it live? Senior
Open two sessions on a test PostgreSQL database:
Output:
S1: BEGIN; SELECT balance FROM accounts WHERE id = 'A'; -- 10000
S2: UPDATE accounts SET balance = 7000 WHERE id = 'A'; -- autocommit
S1: SELECT balance FROM accounts WHERE id = 'A'; -- 7000
S1: COMMIT;within one transaction, the same query returned two different values.
Repeat with S1: BEGIN ISOLATION LEVEL REPEATABLE READ; the second read returns 10000. Explaining with a live demo like this shows real understanding, not memorised definitions.
Q50. A dashboard needs exact order counts per status across 100 million rows, refreshed every minute. How do you design it? Senior
Running GROUP BY over 100 million rows every minute wastes the database. Options:
- Summary table updated incrementally: a job every minute aggregates only new or changed rows (by updated_at) and adds the differences.
- Update counts in the same transaction as the status change (exact, but adds a hot row per status; use sharded counters if writes are heavy).
- A materialized view refreshed on a schedule (simple, but a full refresh is heavy; refresh concurrently in PostgreSQL with a unique index).
- Stream changes (CDC) into a store or warehouse built for counts.
Pick based on how exact and how fresh the business really needs it.
5. Frequently asked questions
Which isolation level should I say is "best"?
None is best for everything. Explain the trade-off: stronger isolation prevents more anomalies but causes more waiting or retries. Then say which you would choose for the scenario and why.
Do cloud engineers need to read execution plans?
Yes, at least the basics: scan types, estimated vs actual rows, and where the time goes. It is one of the most useful skills when an RDS instance hits 100% CPU.
Is PartiQL the same as SQL on DynamoDB?
It looks like SQL, but it does not make DynamoDB relational. There are no joins, and access still depends on keys and indexes.
6. Quick revision
- PostgreSQL defaults to READ COMMITTED; MySQL InnoDB defaults to REPEATABLE READ.
- SELECT ... FOR UPDATE locks rows; SKIP LOCKED lets many workers take different rows.
- EXPLAIN ANALYZE runs the query; wrap writes in a transaction you roll back.
- pg_stat_statements and Database Insights show which queries use the most time.
- Redshift does not enforce primary key or unique constraints.
7. Related chapters
- Amazon RDS Interview Questions and Answers: Backups, Multi-AZ, Read Replicas, Encryption and Troubleshooting (50 Questions)
- AWS Database Interview Questions and Answers: RDS, Aurora, DynamoDB and ElastiCache (50 Questions)
- 1000 AWS Interview Questions and Answers for Freshers and Experienced (Complete Set)
This page is one part of the complete AWS interview question set. Open the full list here: All 2052 AWS interview questions.