SQL Interview Questions for AWS Cloud Engineers: Queries, Joins, Window Functions and Indexes on RDS (50 Questions)
This page has 50 SQL interview questions written for cloud and AWS engineers, with full answers and examples you can run on Amazon RDS for PostgreSQL or MySQL. It covers how to write correct queries and how indexes make them fast. Transactions, tuning and SQL on Aurora and Redshift are on the next page.
1. An everyday example: a library catalogue
Why do cloud engineers get SQL questions?
Cloud engineers run RDS and Aurora, debug slow applications, and write reports. Many interviews include a few SQL questions, even for DevOps and cloud roles, because most production problems end up near a database.
A relational database is like a library. Tables are shelves of the same kind of thing (books, members, loans). Keys are the card numbers that connect a loan to a book and a member. An index is the catalogue at the front: instead of walking every shelf, you look up the title and go straight to the right place.
How to use this page
- Practise on a small RDS PostgreSQL or MySQL instance (or a local database) with sample tables: customers, orders, order_items and products.
- The examples use PostgreSQL syntax unless they say MySQL.
- All data here 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 makes a database "relational", and how is that different from dumping JSON files in S3? Fresher
A relational database stores data in tables with a fixed set of columns, and connects tables using keys. It enforces rules (data types, NOT NULL, unique, foreign keys) and supports SQL queries with joins and transactions.
JSON files in S3 have no enforced structure, no relationships, and no transactions. You can query them with Athena, but nothing stops a bad record from being written.
Choose relational when data is connected (customers, orders, payments) and must stay correct; choose S3 files for large, append-only data like logs and analytics.
Q2. What do primary key and foreign key constraints actually stop you from doing? Fresher
- Primary key: stops duplicate or NULL values in the key column, so every row can be found uniquely.
- Foreign key: stops a child row pointing to a parent that does not exist.
Output:
INSERT INTO orders (order_id, customer_id) VALUES (501, 9999);
ERROR: insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL: Key (customer_id)=(9999) is not present in table "customers".There is no customer 9999, so the database refuses the order. Without the constraint, you would get "orphan" orders that break reports later.
Q3. How do you connect to an RDS PostgreSQL database from an EC2 instance and run a first query? Fresher
psql "host=shop-db.abc123xyz.ap-south-1.rds.amazonaws.com port=5432 dbname=shop user=app_ro sslmode=require"Output:
shop=> SELECT version();
PostgreSQL 16.4 on aarch64-unknown-linux-gnu ...You are connected over TLS and the server is PostgreSQL 16.
If it hangs, check the security group (port 5432 from the EC2 instance's security group) and the subnet routing; if it says "password authentication failed", check the user and password (or IAM authentication token). For MySQL, use the mysql client on port 3306.
Q4. How do you see a table's columns, indexes and constraints in PostgreSQL and MySQL? Fresher
PostgreSQL (psql):
Output:
shop=> \d orders
Column | Type | Nullable
order_id | bigint | not null
customer_id | bigint | not null
created_at | timestamptz | not null
Indexes: "orders_pkey" PRIMARY KEY, btree (order_id)MySQL:
Output:
SHOW CREATE TABLE orders\GYou get the full definition, including indexes and foreign keys. Always check this before writing queries or adding indexes, so you do not create a duplicate index.
Q5. How do you find customers who have never placed an order? Fresher
Two common ways:
Output:
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
SELECT c.customer_id, c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);Both return customers with no matching order. This pattern is called an anti-join. Avoid NOT IN (SELECT customer_id FROM orders) if that column can contain NULL, because then it returns no rows at all.
Q6. What does a FULL OUTER JOIN return, and when is it useful? Fresher
A FULL OUTER JOIN returns all rows from both tables. Where there is a match, the columns are combined; where there is no match on one side, that side's columns are NULL.
Useful for reconciliation, for example comparing payments recorded by your app with the payment provider's report:
Output:
SELECT a.payment_id, a.amount AS app_amount, p.amount AS provider_amount
FROM app_payments a FULL OUTER JOIN provider_payments p ON p.payment_id = a.payment_id
WHERE a.payment_id IS NULL OR p.payment_id IS NULL OR a.amount <> p.amount;You see payments missing on either side or with different amounts. MySQL has no FULL OUTER JOIN; combine a LEFT JOIN and a RIGHT JOIN with UNION.
Q7. What is a self join? Give an example. Fresher
A self join joins a table to itself, using two aliases.
Example: an employees table where each row has a manager_id that points to another employee.
Output:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.employee_id = e.manager_id;Each employee is shown with their manager's name. LEFT JOIN keeps the top boss, who has no manager.
Q8. What is a CROSS JOIN, and how does it happen by accident? Fresher
A CROSS JOIN returns every combination of rows from two tables. 1,000 rows times 1,000 rows gives 1,000,000 rows.
It is useful on purpose, for example to combine every store with every date for a calendar report.
It happens by accident when you forget the join condition, for example "FROM orders, customers" without a WHERE linking them, or a wrong ON clause. Signs: a huge row count, a slow query and wrong totals. Always write explicit JOIN ... ON.
Q9. What is the difference between UNION and UNION ALL? Fresher
Both stack the results of two queries with the same columns.
- UNION removes duplicate rows, which needs a sort or hash step and is slower.
- UNION ALL keeps all rows, including duplicates, and is faster.
Use UNION ALL by default when you know the two sets do not overlap (for example orders_2025 and orders_2026 tables). Use UNION only when you really need duplicates removed.
Q10. What is a correlated subquery? Fresher
A correlated subquery uses a value from the outer query, so it is logically run once for each outer row.
Output:
SELECT o.order_id, o.amount
FROM orders o
WHERE o.amount > (SELECT AVG(o2.amount) FROM orders o2 WHERE o2.customer_id = o.customer_id);show orders bigger than that customer's own average order.
It is easy to read, but on large tables it can be slow unless the optimiser rewrites it or an index exists on orders(customer_id). A window function (AVG() OVER (PARTITION BY customer_id)) is often faster.
Q11. What is a CTE (WITH clause), and why do people use it? Fresher
A CTE is a named temporary result you define at the start of a query and use like a table.
Output:
WITH monthly AS (
SELECT customer_id, date_trunc('month', created_at) AS month, SUM(amount) AS total
FROM orders GROUP BY 1, 2)
SELECT * FROM monthly WHERE total > 10000;Why: it breaks a long query into readable steps, and you can refer to the same step more than once. It does not make queries faster by itself.
Q12. How do you find the second highest order amount? Fresher
Output:
SELECT MAX(amount) FROM orders WHERE amount < (SELECT MAX(amount) FROM orders);or, more generally (Nth highest, handling ties):
Output:
SELECT amount FROM (
SELECT amount, DENSE_RANK() OVER (ORDER BY amount DESC) AS rnk FROM orders) t
WHERE rnk = 2 LIMIT 1;DENSE_RANK gives equal amounts the same rank, so "second highest" means the second distinct value. Interviewers often ask how you would change it for the Nth value: change 2 to N.
Q13. What is a window function? Give a simple example. Fresher
A window function calculates a value across a set of related rows but, unlike GROUP BY, keeps every row in the output.
Output:
SELECT order_id, customer_id, amount,
SUM(amount) OVER (PARTITION BY customer_id) AS customer_total
FROM orders;Each order row also shows that customer's total spend.
Common ones: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, SUM/AVG OVER, and running totals with ORDER BY in the window.
Q14. What is a database view, and when would you use one on RDS? Fresher
A view is a saved query that looks like a table. It does not store data (a materialized view does).
Uses:
- Hide complex joins behind a simple name for reports.
- Give a reporting user access to only some columns (for example no email or phone) by granting SELECT on the view, not on the table.
- Keep a stable interface while the underlying tables change.
Performance is the same as running the query itself.
Q15. How does an index make a query faster? Fresher
Without an index, the database reads every row (a full table scan) to find matches. A B-tree index keeps the column values sorted with pointers to the rows, so the database can jump to the matching values, like a book's index.
Example: on a 20-million-row orders table, WHERE customer_id = 42 might read all rows without an index, but only a few pages with an index on customer_id.
Cost: indexes use storage and slow down INSERT, UPDATE and DELETE, because each index must also be updated.
Q16. What is the difference between a unique constraint and a normal index? Fresher
- A unique constraint (usually implemented with a unique index) guarantees no two rows have the same value, for example one account per email. The database rejects duplicates.
- A normal index only speeds up lookups and allows duplicates.
Use a unique constraint for business rules ("email must be unique"), not just application checks, because two requests arriving at the same time can both pass an application check and insert duplicates.
Q17. What is the difference between a schema and a database in PostgreSQL and MySQL? Fresher
- PostgreSQL: one server (RDS instance) holds databases; each database holds schemas (namespaces such as public, sales); each schema holds tables. You cannot join tables across databases directly, but you can across schemas.
- MySQL: "schema" and "database" mean the same thing, and you can join across databases on the same server.
This matters for multi-tenant designs and permissions: in PostgreSQL you can grant access per schema.
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. Why does the column order in a composite index matter? Mid level
A B-tree composite index on (customer_id, created_at) is sorted by customer_id first, then by created_at within each customer.
- WHERE customer_id = 42 AND created_at > '2026-11-01': uses the index fully.
- WHERE customer_id = 42: uses the index (leading column).
- WHERE created_at > '2026-11-01' alone: usually cannot use it efficiently, because dates are spread across all customers.
Rule of thumb: put equality-filter columns first, then the range or sort column. Design indexes from your real queries.
Q19. What is a covering index, and what is an index-only scan? Mid level
A covering index contains every column a query needs, so the database can answer from the index alone without visiting the table rows.
Output:
CREATE INDEX idx_orders_cust_cover ON orders (customer_id, created_at) INCLUDE (amount, status);
EXPLAIN SELECT created_at, amount, status FROM orders WHERE customer_id = 42;
Index Only Scan using idx_orders_cust_cover on ordersPostgreSQL reads only the index. In PostgreSQL, index-only scans work best when the table is well vacuumed (visibility map up to date). In MySQL InnoDB, secondary indexes always include the primary key, which helps covering.
Q20. Why can wrapping an indexed column in a function stop the index from being used? Mid level
The index stores the raw column values. If the query filters on a function of the column, the database cannot search the index directly.
Slow:
Output:
WHERE DATE(created_at) = '2026-11-20'
WHERE LOWER(email) = 'asha@example.com'Better:
Output:
WHERE created_at >= '2026-11-20' AND created_at < '2026-11-21'or create an expression index:
Output:
CREATE INDEX idx_users_lower_email ON users (LOWER(email));Queries written so the index can be used are called "sargable".
Q21. How do you delete duplicate rows but keep one of each? Mid level
Use ROW_NUMBER to number the copies and delete all but the first:
Output:
WITH ranked AS (
SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at) AS rn
FROM subscribers)
DELETE FROM subscribers WHERE id IN (SELECT id FROM ranked WHERE rn > 1);For each email, the oldest row is kept and newer copies are deleted.
On production: first run the SELECT to count rows, take a snapshot, delete in batches, then add a unique constraint so duplicates cannot come back.
Q22. How do you calculate a running total of daily sales? Mid level
Output:
SELECT sale_date, daily_total,
SUM(daily_total) OVER (ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM daily_sales;Each row shows the total from the first day up to that day.
Add PARTITION BY store_id to restart the running total for each store. Writing the frame (ROWS BETWEEN ...) explicitly avoids surprises with duplicate dates, where the default frame (RANGE) includes all rows with the same date.
Q23. What is the difference between ROW_NUMBER, RANK and DENSE_RANK? Mid level
For amounts 900, 800, 800, 700 ordered descending:
| Amount | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 900 | 1 | 1 | 1 |
| 800 | 2 | 2 | 2 |
| 800 | 3 | 2 | 2 |
| 700 | 4 | 4 | 3 |
- ROW_NUMBER: always unique, ties broken arbitrarily (add a tie-breaker column).
- RANK: ties share a rank, then it skips numbers.
- DENSE_RANK: ties share a rank, no gaps.
Q24. How do you get the latest order for each customer? Mid level
Output:
SELECT * FROM (
SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC, order_id DESC) AS rn
FROM orders o) t
WHERE rn = 1;PostgreSQL also has DISTINCT ON:
Output:
SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, created_at DESC;One row per customer, the most recent. An index on (customer_id, created_at DESC) makes this fast. Change rn = 1 to rn <= 3 for the top 3 per group.
Q25. Why can NOT IN return no rows when you expect many? Mid level
If the subquery returns even one NULL, "x NOT IN (..., NULL)" is never true, because comparing with NULL gives "unknown".
Output:
SELECT * FROM customers WHERE customer_id NOT IN (SELECT referred_by FROM customers);If referred_by has any NULL, this returns 0 rows.
Fix: use NOT EXISTS, or filter NULLs inside the subquery (WHERE referred_by IS NOT NULL). NOT EXISTS is the safer habit.
Q26. What is a partial index, and when is it a good idea? Mid level
A partial index (PostgreSQL) only indexes rows that match a condition.
Output:
CREATE INDEX idx_orders_pending ON orders (created_at) WHERE status = 'PENDING';If only 1% of 50 million orders are pending, the index is tiny and fast, and queries like "pending orders older than 1 hour" use it.
It also enables rules such as a unique constraint only on active rows (see the soft delete question). MySQL does not support partial indexes; use a generated column or a separate table instead.
Q27. When does adding another index make things worse? Mid level
- Every write must update every index, so heavy-write tables slow down.
- More storage and more memory needed to keep indexes cached; useful pages get pushed out of memory.
- Redundant indexes: an index on (a) is usually not needed if (a, b) exists.
- The planner may pick a poor index in some cases.
- Longer vacuum (PostgreSQL) and longer backups and restores.
Add indexes for real, frequent queries, and remove unused ones.
Q28. How do you find unused indexes in PostgreSQL? Mid level
Output:
SELECT relname AS table, indexrelname AS index, idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0 ORDER BY pg_relation_size(indexrelid) DESC;
orders | idx_orders_old_status | 0 | 3412 MBThis 3.4 GB index has not been used since statistics were last reset.
Before dropping: check that stats cover a long enough period (including month-end jobs), check read replicas too (stats are per instance), and keep indexes that back unique or foreign key constraints.
Q29. How do you add an index to a large, busy production table without blocking writes? Mid level
PostgreSQL:
Output:
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);The index is built without holding a lock that blocks inserts and updates. It takes longer, cannot run inside a transaction, and if it fails it leaves an INVALID index that you must drop and retry.
MySQL (InnoDB): many index builds are online:
Output:
ALTER TABLE orders ADD INDEX idx_customer (customer_id), ALGORITHM=INPLACE, LOCK=NONE;Run it at a quiet time, watch replica lag and storage, and test on a clone first.
Q30. How do you query a tree, such as categories with parent categories, in SQL? Mid level
Use a recursive CTE:
Output:
WITH RECURSIVE tree AS (
SELECT category_id, name, parent_id, 1 AS depth FROM categories WHERE category_id = 10
UNION ALL
SELECT c.category_id, c.name, c.parent_id, t.depth + 1
FROM categories c JOIN tree t ON c.parent_id = t.category_id)
SELECT * FROM tree;You get category 10 and all its sub-categories at every level, with their depth.
Protect against loops in bad data with a depth limit (WHERE t.depth < 20). MySQL 8 and PostgreSQL both support this.
Q31. How do you turn rows into columns (a pivot) in SQL? Mid level
Use conditional aggregation:
Output:
SELECT store_id,
SUM(CASE WHEN status = 'PAID' THEN amount ELSE 0 END) AS paid,
SUM(CASE WHEN status = 'REFUNDED' THEN amount ELSE 0 END) AS refunded,
COUNT(*) FILTER (WHERE status = 'CANCELLED') AS cancelled_count
FROM orders GROUP BY store_id;One row per store with separate columns for each status. FILTER is PostgreSQL syntax; CASE works everywhere.
Q32. When should you store JSON in a PostgreSQL jsonb column, and how do you index it? Mid level
Good for: flexible attributes that differ per row (product specs, event payloads) and are not the main way you filter or join.
Output:
CREATE INDEX idx_products_attrs ON products USING GIN (attrs);
SELECT * FROM products WHERE attrs @> '{"color": "red"}';The GIN index helps containment queries on the JSON.
Not good for: fields you filter, join or constrain on all the time, such as customer_id or price. Put those in normal columns with types and constraints. Too much JSON turns a relational database into an unvalidated document store.
Q33. Why should foreign key columns usually have an index? Mid level
The database indexes the parent's primary key, but not always the child's foreign key column (PostgreSQL does not create it automatically; MySQL InnoDB does).
Without an index on orders.customer_id:
- Joins from customers to orders scan the orders table.
- Deleting or updating a customer must scan orders to check for children, which can be slow and hold locks for a long time.
Create the index unless the table is tiny or the relationship is never queried.
Q34. How does the database execute a join: nested loop, hash join or merge join? Mid level
- Nested loop: for each row in one table, look up matches in the other (fast with an index on the inner table and few outer rows).
- Hash join: build a hash table from the smaller input, then probe it with the larger one (good for large, unsorted inputs and equality joins; needs memory).
- Merge join: both inputs sorted on the join key, then walked together (good when data is already sorted or indexed).
The optimiser chooses based on statistics. A bad estimate (for example it thinks 10 rows but gets 1 million) can pick a nested loop that runs for minutes; EXPLAIN ANALYZE shows this.
Q48. What do LAG and LEAD do? Give a practical example. Mid level
LAG reads a value from the previous row and LEAD from the next row, in the window's order, without a self join.
Output:
SELECT day, revenue,
revenue - LAG(revenue) OVER (ORDER BY day) AS change_vs_yesterday
FROM daily_revenue;Each day shows how much revenue went up or down compared with the day before. The first row has NULL, because there is no previous day.
Other uses: time between a user's sessions, finding the next status change of an order, spotting gaps in sequence numbers.
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 the index for this query: WHERE tenant_id = ? AND status = ? ORDER BY created_at DESC LIMIT 20. Senior
Output:
CREATE INDEX idx_orders_tenant_status_created ON orders (tenant_id, status, created_at DESC);Why:
- Equality columns first (tenant_id, status), so the database jumps to exactly that tenant and status.
- Then created_at in the same order as the ORDER BY, so rows come out already sorted and the database can stop after 20 rows. No sort step.
Check with EXPLAIN that there is no Sort node and that rows read are close to 20. If most queries do not filter by status, consider (tenant_id, created_at) instead and test both on real data.
Q36. For a multi-tenant SaaS on RDS, how do you choose between a shared table, a schema per tenant and a database per tenant? Senior
| Model | Strength | Weakness |
|---|---|---|
| Shared tables with tenant_id | Simple, cheapest, easy to add tenants | Every query must filter by tenant; noisy neighbours |
| Schema per tenant | Better isolation, per-tenant restore is easier | Thousands of schemas make migrations slow |
| Database or instance per tenant | Strong isolation, per-tenant tuning | Highest cost and operational work |
Common choice: shared tables for small tenants (with PostgreSQL row-level security as a safety net) and a dedicated database for large or regulated customers.
Q37. You use soft deletes (deleted_at column). How do you keep "email must be unique" working? Senior
A normal unique index on email blocks a user from signing up again after their old account was soft-deleted, because the deleted row still has the email.
PostgreSQL: use a partial unique index on active rows only:
Output:
CREATE UNIQUE INDEX uq_users_email_active ON users (LOWER(email)) WHERE deleted_at IS NULL;MySQL: use a generated column that is NULL for deleted rows and put the unique index on it (unique indexes allow many NULLs).
Also remember that every query must exclude deleted rows; a view helps.
Q38. Why can random UUIDs as the primary key hurt MySQL InnoDB performance, and what do you use instead? Senior
InnoDB stores the table in primary key order (a clustered index). Random UUIDs (v4) insert rows at random places in the B-tree, causing page splits, fragmentation, more disk I/O and a larger buffer pool need. Secondary indexes also store the primary key, so a 36-character string key makes every index bigger.
Options:
- BIGINT auto-increment or sequences when IDs can be guessed safely.
- Time-ordered IDs (UUIDv7 or ULID), stored as BINARY(16), which insert near the end like auto-increment.
PostgreSQL is less affected (heap tables), but index size and locality still matter.
Q39. An hourly analytics query with six joins runs on the production primary and hurts checkout. What do you do? Senior
Short term:
- Move it to a read replica (or an Aurora reader with a custom endpoint for reporting).
- Set a statement timeout for the reporting user so it cannot run forever.
Medium term:
- Check EXPLAIN for missing indexes or bad join estimates.
- Pre-aggregate: a summary table refreshed incrementally, or a materialized view.
Long term:
- Send the data to a warehouse (Redshift, or zero-ETL integrations from Aurora) and run analytics there.
The goal: transactional and analytical workloads should not compete for the same database.
Q40. How do you find users who logged in on 5 or more consecutive days? Senior
This is a "gaps and islands" problem. Subtract a row number from the date; consecutive dates get the same group value.
Output:
WITH d AS (SELECT DISTINCT user_id, login_at::date AS day FROM logins),
g AS (SELECT user_id, day,
day - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day))::int AS grp FROM d)
SELECT user_id, MIN(day) AS start_day, COUNT(*) AS days
FROM g GROUP BY user_id, grp HAVING COUNT(*) >= 5;Each group is one unbroken run of days. Interviewers like this question because it tests window functions and thinking, not memory.
Q41. The application sends a query with an IN list of 20,000 IDs. What are the problems and better options? Senior
Problems: a huge SQL string, long parse and plan time, possible limits on statement size or bind parameters, and a different plan for each list length (no plan reuse).
Better options:
- PostgreSQL: pass one array parameter: WHERE id = ANY($1).
- Load the IDs into a temporary table (or a staging table) and JOIN.
- Rethink the access pattern: why does the app need 20,000 IDs? Often a join on a shared attribute (batch_id, tenant) replaces the list.
- Batch the work into chunks of a few hundred to a few thousand IDs.
Q42. An API endpoint makes 201 database queries to show one page. What is happening and how do you fix it? Senior
This is the N+1 query problem, usually from an ORM: one query loads 200 orders, then one more query per order loads its customer.
Find it: database logs or Performance/Database Insights show the same small query running hundreds of times per request; APM traces show many short database calls.
Fix:
- Eager loading in the ORM (a join or one "WHERE customer_id IN (...)" query).
- Return only needed columns.
- Add a test that counts queries per endpoint, so it does not come back.
Q43. How do you change a column type on a 500 GB table in production without downtime? Senior
Use the expand and contract pattern:
1. Add a new column with the new type (fast, no table rewrite).
2. Make the application write to both columns.
3. Backfill old rows in small batches, watching replica lag and load.
4. Switch reads to the new column, and verify.
5. Stop writing the old column, then drop it later.
A direct ALTER COLUMN TYPE often rewrites the whole table and locks it. For MySQL, online schema change tools (such as gh-ost or pt-online-schema-change) or Aurora/RDS blue/green deployments are other options. Always rehearse on a clone.
Q44. How do you make sure a user can have only one active subscription, even with concurrent requests? Senior
Enforce it in the database, not only in code:
Output:
CREATE UNIQUE INDEX uq_active_sub ON subscriptions (user_id) WHERE status = 'ACTIVE';A second ACTIVE row for the same user is rejected, even if two requests run at the same moment.
The application then catches the unique violation error and returns a clear message. Code-only checks ("SELECT, then INSERT if none") have a race condition, because both requests can see "none" before either inserts.
Q45. The app runs in India, RDS runs in UTC, and reports show orders on the wrong day. How do you store and query times correctly? Senior
- Store moments in time as UTC with a time-zone-aware type: timestamptz in PostgreSQL (MySQL: store UTC in DATETIME or TIMESTAMP and be consistent).
- Convert to the user's zone only when displaying or grouping:
Output:
SELECT (created_at AT TIME ZONE 'Asia/Kolkata')::date AS ist_day, COUNT(*) FROM orders GROUP BY 1;- Do not rely on the server or session time zone; set it explicitly in the application connection.
An order at 01:00 IST on 21 November is 19:30 UTC on 20 November; grouping by UTC date puts it on the wrong day for Indian reports.
Q46. Events can arrive twice from a queue. How do you make database inserts idempotent? Senior
Give each event a unique ID from the producer and enforce uniqueness:
Output:
INSERT INTO payments_events (event_id, order_id, amount)
VALUES ('evt-7f3a', 501, 1999)
ON CONFLICT (event_id) DO NOTHING;MySQL: INSERT IGNORE or INSERT ... ON DUPLICATE KEY UPDATE.
The second copy of the same event does nothing, so totals are not doubled. Combine the insert and its side effects (such as updating the order balance) in one transaction, so a retry either does everything or nothing.
Q47. How would you store hierarchical data such as an org chart, and what are the trade-offs? Senior
| Model | Reads | Writes |
|---|---|---|
| Adjacency list (parent_id) | Needs recursive CTE for subtrees | Simple moves |
| Materialized path ('/1/4/9/') | Fast subtree by prefix match | Moving a subtree updates many rows |
| Closure table (ancestor, descendant pairs) | Very fast ancestor and descendant queries | Extra table, more writes |
PostgreSQL also has the ltree extension for paths. For most apps, start with an adjacency list plus recursive CTEs, and move to a closure table only if subtree queries become hot.
Q49. A report query uses SELECT DISTINCT to "fix" duplicate rows. Why is that a warning sign? Senior
DISTINCT often hides a join problem instead of fixing it. If a customer appears twice, it is usually because the query joins to a one-to-many table (orders, addresses) and multiplies rows.
Risks:
- Sums and counts computed before or alongside the DISTINCT are still wrong.
- DISTINCT adds a sort or hash step on large results.
Better: understand the grain of each table, aggregate the many-side first in a subquery or CTE (one row per customer), then join; or use EXISTS when you only need to know a match exists.
Q50. How do you safely run a large UPDATE that touches 30 million rows on an RDS production database? Senior
- Never do it as one huge statement: it holds locks for a long time, creates a huge transaction (undo/WAL), and can lag replicas or fill storage.
- Update in batches of a few thousand rows by primary key range, committing each batch:
Output:
UPDATE orders SET region = 'south' WHERE order_id BETWEEN 1000001 AND 1005000 AND region IS NULL;- Sleep briefly between batches, and watch replica lag, CPU, free storage and lock waits.
- Make it restartable (the WHERE clause skips rows already done).
- Take a snapshot first, and test on a clone to measure the time.
5. Frequently asked questions
Which database should I practise on for AWS interviews?
PostgreSQL or MySQL, because they are the most common engines on RDS and Aurora. The SQL is almost the same; the tools and some syntax differ.
Do I need to memorise window function syntax?
Know ROW_NUMBER, RANK, SUM OVER and PARTITION BY well enough to write them on a whiteboard. The rest you can look up.
What is the best way to learn indexing?
Create a table with a few million rows, run a query, add an index, and compare the EXPLAIN output and timing before and after.
6. Quick revision
- LEFT JOIN plus IS NULL, or NOT EXISTS, finds rows with no match. Beware NOT IN with NULLs.
- ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) solves "latest per group" and "remove duplicates".
- A composite index helps queries that filter on its leading columns.
- A function on an indexed column (like DATE(created_at)) can stop the index from being used.
- Build indexes on busy tables with CREATE INDEX CONCURRENTLY (PostgreSQL) or online DDL (MySQL).
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.