Make a table 1NF compliant

Easy
2 views 23 Jan 2026
You have a table StudentContacts(student_id, name, phones) where phones stores values like '9999,8888'. Convert it to 1NF by designing tables and writing SQL DDL....

Identify partial dependency (2NF)

Easy
2 views 23 Jan 2026
Table Marks(student_id, subject_id, student_name, subject_name, marks) with PK(student_id, subject_id). Explain what is wrong and show a 2NF decomposition using SQL tables....

Remove transitive dependency (3NF)

Easy
2 views 23 Jan 2026
Employees(emp_id, emp_name, dept_id, dept_name). Show 3NF decomposition....

Candidate keys list (simple)

Easy
2 views 23 Jan 2026
Table Booking(pnr, passport_no, email). Any one of these can uniquely identify a booking. Write SQL to enforce this with UNIQUE constraints....

Find repeating groups (concept)

Easy
4 views 23 Jan 2026
Given a table OrdersRaw(order_id, items, quantities) where items are stored like '10|12|14' and quantities '1|2|1', explain why it breaks 1NF in description and give normalized tables in SQL....

Convert an address table to 3NF

Medium
3 views 23 Jan 2026
CustomerProfile(customer_id, name, city, state, state_code). state_code depends on state. Show 3NF tables....

Handle many-to-many properly

Medium
2 views 23 Jan 2026
You have Movie(movie_id, title, actor_names) as a comma list. Convert to normalized design....

BCNF check with decomposition

Medium
3 views 23 Jan 2026
Table Teaching(teacher, subject, room). Rule: each subject is taught in exactly one room, but a teacher can teach many subjects. Show BCNF decomposition in SQL....

Avoid update anomaly

Medium
2 views 23 Jan 2026
Table ProductSupply(product_id, supplier_name, supplier_phone, supply_price). Decompose to reduce update anomaly....

Normalization with composite attribute

Medium
2 views 23 Jan 2026
Table Employees(emp_id, name, address) where address stores 'house,street,city'. Normalize it into separate columns and keep it 1NF....

Design for historical salary (slowly changing)

Hard
2 views 23 Jan 2026
You need employee salary history. Design normalized tables to store salary changes with effective_from date....

Functional dependency driven design

Hard
3 views 23 Jan 2026
Table Shipment(order_id, courier, courier_phone). courier determines courier_phone. Show normalized tables....

Prevent insert anomaly in raw table

Hard
2 views 23 Jan 2026
In raw InvoiceRaw(invoice_id, customer_name, customer_city, line_items). Show a normalized design that allows storing customer even without invoices....

Normalize for reporting and performance

Hard
2 views 23 Jan 2026
OrdersReport(order_id, customer_city, product_category, qty, amount). Explain in description that this is a report table and show base normalized tables in SQL....

Simple stored procedure with input

Easy
3 views 23 Jan 2026
Create a stored procedure sp_add_department(p_id, p_name) that inserts into Departments....

Procedure to update salary

Easy
3 views 23 Jan 2026
Create procedure sp_hike_salary(p_emp_id, p_percent) that increases salary for that employee....

Procedure with output parameter

Easy
3 views 23 Jan 2026
Create sp_order_total(p_order_id, OUT p_total) that returns sum(qty*price) from OrderItems....

Procedure to clean old logs

Easy
3 views 23 Jan 2026
Create sp_delete_old_logs(p_days) that deletes from LoginLogs older than p_days....

Call a procedure

Easy
3 views 23 Jan 2026
Show how to call sp_order_total for order 7001....

Procedure with transaction inside

Medium
4 views 23 Jan 2026
Create sp_transfer_funds(p_from, p_to, p_amt) to transfer money between two accounts. If the sender does not have enough balance, rollback the transaction so nothing changes....

Procedure with cursor-like loop (simple)

Medium
2 views 23 Jan 2026
Create sp_mark_low_stock(p_limit) that sets Products.low_stock=1 when qty_on_hand < p_limit....

Procedure returning result set

Medium
2 views 23 Jan 2026
Create sp_top_customers(p_n) that returns top N customers by total spend....

Procedure with input validation

Medium
4 views 23 Jan 2026
Create sp_add_coupon(code, discount) that validates discount first. If discount is not in 1..80, raise an error; otherwise insert the coupon....

Procedure to rebuild summary table

Medium
2 views 23 Jan 2026
Create sp_refresh_daily_sales that truncates DailySales and re-inserts aggregated totals from Orders....

Idempotent procedure behavior

Hard
5 views 23 Jan 2026
Make sp_add_department safe if dept_id already exists: update name instead of failing....

Procedure for batch price update with audit

Hard
2 views 23 Jan 2026
Create sp_discount_category(p_category, p_percent) that updates product prices and writes an audit row per product into PriceAudit(product_id, old_price, new_price, changed_at)....

Procedure to detect and return duplicates

Hard
3 views 23 Jan 2026
Create sp_find_duplicate_emails that returns emails appearing more than once in Users....

Procedure with retry logic idea

Hard
2 views 23 Jan 2026
When inserting into Payments, deadlock may happen. Write a stored procedure outline that retries 3 times (simple loop)....

Scalar subquery for comparison

Easy
3 views 23 Jan 2026
Find employees whose salary is above the company average salary....

IN subquery filter

Easy
2 views 23 Jan 2026
List customers who have placed at least one order....

EXISTS for faster membership

Easy
2 views 23 Jan 2026
Find products that have at least one order item....

Subquery in FROM (derived table)

Easy
2 views 23 Jan 2026
Get department-wise average salary, then list departments where avg salary > 50000....

Correlated subquery for per-row condition

Easy
2 views 23 Jan 2026
List employees who earn more than the average salary of their own department....

Find latest order per customer using subquery

Medium
3 views 23 Jan 2026
Return orders that are the latest order for each customer....

Second highest salary using subquery

Medium
3 views 23 Jan 2026
Return the second highest distinct salary from Employees....

Find customers with more than N orders

Medium
2 views 23 Jan 2026
Write a query using subquery that returns customers who placed more than 3 orders....

NOT IN pitfall with nulls (safe version)

Medium
3 views 23 Jan 2026
Find customers who did not place any order. Use NOT EXISTS (safer than NOT IN)....

Update with correlated subquery

Medium
3 views 23 Jan 2026
Update Employees set salary to department average salary for employees who have salary NULL....

Find products priced above category average

Hard
4 views 23 Jan 2026
Return products where price is greater than average price of their category....

Detect customers who always pay late

Hard
3 views 23 Jan 2026
Payments(order_id, due_date, paid_at). Find customers where for every payment, paid_at > due_date....

Correlated delete using subquery

Hard
2 views 23 Jan 2026
Delete Products that were created more than 365 days ago and never appeared in OrderItems. Use NOT EXISTS to avoid NULL issues....

Subquery for top category by revenue

Hard
2 views 23 Jan 2026
Find the product category with the highest revenue. Revenue = SUM(qty * price) from OrderItems joined with Products....

Savepoint and rollback partially

Easy
3 views 23 Jan 2026
You are inserting an order and items. If one item insert fails, rollback only item inserts but keep the order row. Use SAVEPOINT....

Commit after successful update

Easy
3 views 23 Jan 2026
Update status of an order and commit....

Rollback on mistake

Easy
2 views 23 Jan 2026
You accidentally updated all employees salary. Rollback the transaction....

Create a savepoint before risky delete

Easy
1 views 23 Jan 2026
Before deleting old logs, create a savepoint. If you feel too many rows got deleted, rollback to the savepoint; otherwise commit....

Use transaction block for multiple steps

Easy
2 views 23 Jan 2026
Insert a customer and an order in one transaction....

Release a savepoint (if supported)

Medium
2 views 23 Jan 2026
Show how to release a savepoint after you are sure you will not rollback to it....

Nested savepoints for batch job

Medium
2 views 23 Jan 2026
During a batch insert, you want to rollback only the last 100 rows if something goes wrong. Show the savepoint pattern....

Autocommit off workflow

Medium
2 views 23 Jan 2026
Write a simple script that turns autocommit off, runs two updates, then commits....

Transaction with error handling idea

Medium
2 views 23 Jan 2026
Show a generic pattern: begin, do steps, if any step fails then rollback, else commit....

Mix DDL and TCL safely

Medium
3 views 23 Jan 2026
You need to create a table and then insert rows. Write a script with commit. Mention in description that some DBs auto-commit DDL....

Undo part of a long transaction

Hard
3 views 23 Jan 2026
In a long transaction you updated 3 tables. Rollback only the last table updates using savepoint....

Consistency check before commit

Hard
5 views 23 Jan 2026
Before commit, run a validation query. If it returns rows, rollback. Show the idea in one script....

Build a safe retry around deadlocks

Hard
3 views 23 Jan 2026
Write a transaction script outline that retries after rollback (concept). Provide a simple loop-like pseudo SQL....

Two-phase style steps (concept + SQL)

Hard
2 views 23 Jan 2026
You want to do: reserve stock, then charge payment. Show savepoint usage so payment failure restores stock....

Basic transaction for money transfer

Easy
2 views 23 Jan 2026
Transfer 500 from account 1 to account 2 using a transaction....

Read consistency example

Easy
3 views 23 Jan 2026
Inside one transaction, read the same row twice. Show the basic idea using SELECT statements....

Avoid dirty writes

Easy
2 views 23 Jan 2026
Show that you should lock a row before updating by using SELECT ... FOR UPDATE....

Set isolation level

Easy
2 views 23 Jan 2026
Set transaction isolation level to READ COMMITTED for a transaction....

Handle lost update (pattern)

Easy
2 views 23 Jan 2026
Two sessions update same row. Show a safe pattern using a version column and conditional update....

Detect and prevent phantom reads (concept + SQL)

Medium
4 views 23 Jan 2026
Write a transaction that counts active orders, then inserts a new active order. Mention isolation needed in description and show SERIALIZABLE statement....

Use savepoint in a business transaction

Medium
2 views 23 Jan 2026
While placing an order, keep a savepoint after reserving stock. If payment fails, rollback to savepoint....

Explain deadlock with small example

Medium
2 views 23 Jan 2026
Two transactions lock resources in opposite order. Provide two scripts in sample_solution separated by a pipe symbol....

Row-level locking for order processing

Medium
2 views 23 Jan 2026
When processing an order, lock it so two workers do not process it together. Write a safe SELECT FOR UPDATE pattern....

Atomic decrement with check

Medium
4 views 23 Jan 2026
Decrease Inventory.qty by requested amount only if enough stock. Make it atomic in one statement and run inside a transaction....

Serializable queue pop (advanced)

Hard
2 views 23 Jan 2026
Implement a safe job-queue pop: pick one NEW job, lock it so others can't pick it, mark it IN_PROGRESS, and return the picked job_id. Use FOR UPDATE SKIP LOCKED if available....

Double-spend prevention in wallet

Hard
4 views 23 Jan 2026
Wallet(user_id, balance). Two payments at same time should not allow negative balance. Write a safe transaction with check....

Snapshot reporting without blocking writes

Hard
3 views 23 Jan 2026
You need a consistent report while inserts keep happening in parallel. Start a transaction in REPEATABLE READ and run your report query inside it....

Detect and handle write skew (concept)

Hard
2 views 23 Jan 2026
Two doctors on call table. Each transaction sees at least one on call and turns itself off, resulting none on call. Use SERIALIZABLE to prevent....

Before insert trigger to clean data

Easy
0 views 23 Jan 2026
In Customers, automatically trim and lowercase email before insert....

After insert audit trigger

Easy
0 views 23 Jan 2026
After inserting into Orders, insert a row into AuditLog(table_name, row_id, action)....

Prevent negative price

Easy
0 views 23 Jan 2026
Stop INSERT and UPDATE if Products.price ...

Auto-update updated_at column

Easy
0 views 23 Jan 2026
On update of Orders, set updated_at to current timestamp automatically....

Maintain stock on order item insert

Easy
0 views 23 Jan 2026
When a new OrderItems row is inserted, decrement Inventory.qty....

Prevent deleting paid orders

Medium
0 views 23 Jan 2026
Block deleting an order if any payment exists for that order. Use a BEFORE DELETE trigger on Orders and check Payments....

Audit updates with old and new values

Medium
0 views 23 Jan 2026
On Employees salary update, insert into SalaryAudit(emp_id, old_salary, new_salary, changed_at)....

Auto-create customer code

Medium
0 views 23 Jan 2026
Customers(customer_id, code). On insert, if code is null, set it as 'C' + customer_id....

Keep summary table in sync

Medium
0 views 23 Jan 2026
Maintain DailySales(day, amount). After insert into Orders, update DailySales for that date....

Stop duplicate active coupon

Medium
0 views 23 Jan 2026
Coupons(code, is_active). Before INSERT, if the same code already exists with is_active=1, then block the insert....

Complex trigger with transaction-safe stock check

Hard
0 views 23 Jan 2026
Before inserting OrderItems, ensure Inventory has enough qty for that product. If stock is not enough, raise an error to stop the insert....

Handle update of qty in order items

Hard
0 views 23 Jan 2026
On update of OrderItems.qty, adjust Inventory by the difference....

Prevent salary decrease beyond 20%

Hard
0 views 23 Jan 2026
Before updating Employees.salary, block the update if the new salary is less than 80% of the old salary....

Soft delete via trigger

Hard
0 views 23 Jan 2026
Instead of physically deleting a customer, do a soft delete: set is_active=0 and stop the DELETE. Use a BEFORE DELETE trigger to enforce this rule....

Create a simple view

Easy
0 views 23 Jan 2026
Create view v_customer_basic showing customer_id, name, city....

Query a view

Easy
0 views 23 Jan 2026
Write a query that reads from v_customer_basic for city='Pune'....

View for active products

Easy
0 views 23 Jan 2026
Create view v_active_products that filters Products where is_active=1....

Replace a view

Easy
0 views 23 Jan 2026
Update v_active_products to include category as well....

Drop a view

Easy
0 views 23 Jan 2026
Drop view v_customer_basic if it exists....

View with join for reporting

Medium
0 views 23 Jan 2026
Create v_order_summary showing order_id, customer_name, total_amount, order_date....

View to hide sensitive columns

Medium
0 views 23 Jan 2026
Payroll(emp_id, salary, bank_account). Create view exposing emp_id and salary only....

Updatable view idea

Medium
0 views 23 Jan 2026
Create a view v_new_orders that selects Orders where status='NEW'. Show an update statement that updates through the view....

View with aggregation

Medium
0 views 23 Jan 2026
Create view v_daily_sales that returns day and total_sales from Orders....

Materialized view style (concept)

Medium
0 views 23 Jan 2026
Assume your database supports materialized views. Create one materialized view that stores monthly revenue from Orders....

View with security filter by city

Hard
0 views 23 Jan 2026
Create v_my_city_customers that only returns customers for city='Delhi'....

View for duplicate detection

Hard
0 views 23 Jan 2026
Create view v_duplicate_emails that lists emails appearing more than once in Users....

View combining latest order per customer

Hard
0 views 23 Jan 2026
Create view v_customer_latest_order that shows each customer with their latest order_id and date....

View for category revenue

Hard
0 views 23 Jan 2026
Create view v_category_revenue that returns category and revenue using OrderItems and Products....

Grant column-level access (hard)

Hard
3 views 23 Jan 2026
You want user support_viewer to see only customer_id and name from Customers, not email/phone. Grant SELECT on only these columns (column-level privilege)....

Create table from query with constraints afterward

Hard
2 views 23 Jan 2026
Create a new table TopCustomers from Orders that stores customer_id and spend, then add a primary key on customer_id....

Merge stage data into master table

Hard
2 views 23 Jan 2026
You have ProductsStage(product_id, name, price). Update existing Products and insert new ones in one MERGE statement....

Customers with 3 consecutive buying months

Hard
14 views 23 Jan 2026
Find customers who placed at least one order in 3 consecutive months (any year). Return customer_id only. Hint: convert to month buckets, then use a window row_number trick....

Calculate age in years from DOB

Hard
2 views 23 Jan 2026
Customers(dob). Return customer_id and age_years as integer (approx)....

Functional index for case-insensitive search

Hard
2 views 23 Jan 2026
Create an index to speed up WHERE LOWER(name)=LOWER(?) on Customers....

Find pairs with same salary in same department

Hard
4 views 23 Jan 2026
List employee pairs in the same department who have exactly the same salary (show both emp names)....

Design for a multi-valued dependency (4NF flavor)

Hard
2 views 23 Jan 2026
You have StudentSkillLang(student_id, skill, language) where skills and languages are independent lists per student. Decompose to avoid mixed combinations....

Procedure to place an order with items table variable

Hard
2 views 23 Jan 2026
Create sp_place_order(p_customer_id, p_order_id) that inserts an order, then inserts all rows from TempOrderItems into OrderItems for that order in one go....

Customers whose every order is fully paid

Hard
2 views 23 Jan 2026
Return customers for which there is no order with unpaid balance. Unpaid means Orders.total_amount > sum(Payments.amount)....

Chunked updates with savepoint per batch

Hard
2 views 23 Jan 2026
You are fixing city names in Customers in batches. Show a pattern: create savepoint, run update for a batch, rollback to savepoint if something looks wrong, else continue and finally commit....

Lock timeout and safe retry idea

Hard
2 views 23 Jan 2026
While processing orders, sometimes you get stuck waiting on locks. Set a short lock timeout, pick one NEW order with a row lock, update it to PROCESSING, then commit....

Archive deleted rows using trigger

Hard
0 views 23 Jan 2026
When a customer row is deleted, copy it into DeletedCustomers(customer_id, name, deleted_at) before deletion....

View for customer spend rank

Hard
0 views 23 Jan 2026
Create view v_customer_spend_rank that shows customer_id, spend, and rank by spend (highest rank 1)....

Add NOT NULL and DEFAULT to a column

Easy
5 views 23 Jan 2026
You have a table Employees(emp_id, name, dept_id, salary, hire_date). Make dept_id mandatory and set default salary as 30000 for new rows....

Create a UNIQUE constraint for email

Easy
5 views 23 Jan 2026
Create table Users(user_id, email, phone). Ensure email is unique and not null....

Add a CHECK constraint for rating

Easy
5 views 23 Jan 2026
In table Reviews(review_id, rating, comment), rating must be between 1 and 5....

Composite primary key for enrollment

Easy
4 views 23 Jan 2026
Create Enrollment(student_id, course_id, enrolled_on). One student can enroll once per course. Make (student_id, course_id) the primary key....

Foreign key with basic reference

Easy
8 views 23 Jan 2026
Create Departments(dept_id, dept_name) and Employees(emp_id, name, dept_id). Add FK so employee dept_id must exist in Departments....

Prevent deleting parent rows when children exist

Medium
7 views 23 Jan 2026
In Orders(order_id) and Payments(payment_id, order_id), enforce that an order cannot be deleted if it has payments....

Auto-delete child rows on parent delete

Medium
6 views 23 Jan 2026
In Customers(customer_id) and Orders(order_id, customer_id), make it so when a customer is deleted, all their orders are deleted too....

Add a conditional CHECK using two columns

Medium
3 views 23 Jan 2026
In Coupons(code, discount_percent, max_discount), discount_percent must be 0 to 80, and max_discount must be at least 100 if discount_percent > 50....

Enforce case-insensitive uniqueness (pattern approach)

Medium
5 views 23 Jan 2026
In Users(email), you want emails to be unique even if case differs (A@x.com vs a@x.com). Write one practical approach using a stored generated column lower_email and a UNIQUE constraint on it....

Deferred constraint idea using transaction (concept + SQL)

Medium
4 views 23 Jan 2026
You are inserting parent and child rows in one transaction. Write a safe sequence so the FK does not fail when you insert child first....

Find rows violating a constraint rule

Hard
3 views 23 Jan 2026
In Products(product_id, price), price should be > 0 but table has old bad data. Write a query to find all invalid rows before adding a CHECK constraint....

Simulate a conditional unique rule

Hard
5 views 23 Jan 2026
In Seats(bus_id, seat_no, status), seat_no should be unique per bus only for active seats (status='ACTIVE'). Write a SQL approach that enforces it using a separate table ActiveSeats and FK/PK....

Protect against orphan data during bulk load

Hard
6 views 23 Jan 2026
You are loading Orders first, then Customers later. How will you prevent orphan customer_id in Orders? Write a staging-table approach....

Create a strong candidate key with multiple columns

Hard
4 views 23 Jan 2026
In table StudentMarks(student_id, exam_date, subject, marks), a student can have only one record per subject per exam_date. Add the right constraint....

Exactly one payment reference (XOR check)

Hard
7 views 23 Jan 2026
In Payments(payment_id, order_id, card_txn_id, upi_txn_id), a payment can be done either by card or by UPI. Enforce rule: exactly one of card_txn_id and upi_txn_id must be filled (not both, not none)....

Grant SELECT on a single table

Easy
2 views 23 Jan 2026
Create a user analyst and grant only SELECT on Orders table....

Revoke a privilege

Easy
3 views 23 Jan 2026
User intern was given INSERT on Customers by mistake. Remove it....

Create a role and assign it

Easy
2 views 23 Jan 2026
Create a role report_reader with SELECT on Customers and Orders, then grant the role to user rohit....

Grant execute on a procedure

Easy
2 views 23 Jan 2026
Procedure sp_monthly_sales exists. Give user accountant permission to execute it....

Show current grants (basic)

Easy
2 views 23 Jan 2026
User analyst already exists. Write the SQL to check what privileges/grants are currently given to this user....

Read-only user for a whole schema

Medium
2 views 23 Jan 2026
Create user readonly_user, then give only SELECT access on all tables under schema sales_db. Keep it least-privilege (no insert/update/delete)....

Grant with grant option (careful)

Medium
2 views 23 Jan 2026
Give team_lead SELECT on Employees with grant option, then explain the risk in one line inside description....

Revoke role from a user

Medium
2 views 23 Jan 2026
User rohit should no longer have role report_reader. Write the revoke statement....

Limit DML but allow SELECT

Medium
2 views 23 Jan 2026
User data_entry should be able to SELECT and INSERT into Orders but cannot UPDATE or DELETE. Write grants....

Privilege for view but not base tables

Medium
2 views 23 Jan 2026
Create a view v_public_customers that exposes only customer_id and name. Then grant SELECT on the view to public_user without granting base table access....

Audit-friendly approach for sensitive tables

Hard
2 views 23 Jan 2026
You want to allow SELECT on Payroll only through a view, not directly on the base table. Create a view that hides salary and bank_account, then grant SELECT on the view to user auditor....

Remove all privileges safely

Hard
3 views 23 Jan 2026
You are deactivating contractor_user. Revoke all granted permissions first, then lock/disable the account (write generic SQL steps)....

Least privilege for stored procedures

Hard
2 views 23 Jan 2026
User app_user should not query base tables directly but can call procedures sp_place_order and sp_pay_order. Write grants only for procedures....

Transfer ownership idea (concept + SQL)

Hard
2 views 23 Jan 2026
If a user owns objects and you want to drop the user, what should you do first? Write a safe sequence in SQL terms....

Create a database and a table

Easy
2 views 23 Jan 2026
Write SQL to create database shop_db and a Products table with id, name, price....

Add a new column

Easy
2 views 23 Jan 2026
Add column status to Orders table, default 'NEW'....

Rename a column

Easy
2 views 23 Jan 2026
In Customers table, rename column full_name to name....

Drop a table safely

Easy
2 views 23 Jan 2026
Drop table TempUpload if it exists....

Create table with timestamps

Easy
2 views 23 Jan 2026
Create LoginLogs(log_id, user_id, logged_at default current timestamp, ip_address)....

Add an index via DDL

Medium
2 views 23 Jan 2026
Create an index on Orders(order_date) to speed up date range filters....

Add a foreign key after table creation

Medium
4 views 23 Jan 2026
Departments exists. Employees exists without FK. Add FK on Employees.dept_id referencing Departments.dept_id....

Change column type with caution

Medium
2 views 23 Jan 2026
In Customers table, phone is stored as INT but you want to keep leading zeros and '+' sign. Change phone column to VARCHAR(20)....

Create a view as part of DDL

Medium
2 views 23 Jan 2026
Create a view v_active_orders that shows only orders with status='ACTIVE'....

Add a CHECK constraint using ALTER

Medium
3 views 23 Jan 2026
In Products, price must be >= 1. Add a CHECK constraint....

Rebuild a table to remove a column (portable approach)

Hard
2 views 23 Jan 2026
Some DBs cannot drop a column easily. Show a safe 3-step approach to remove column temp_flag from Orders....

Add a computed column for search

Hard
2 views 23 Jan 2026
Add a column searchable_name in Customers that stores lower(name) for case-insensitive search, then index it....

Partition idea (high level DDL)

Hard
3 views 23 Jan 2026
Orders table is huge. Create a monthly partitioned table outline for order_date....

Create an audit table for triggers later

Hard
3 views 23 Jan 2026
Create AuditLog(audit_id, table_name, row_id, action, changed_at)....

Insert one row into Customers

Easy
2 views 23 Jan 2026
Insert a customer with id=101, name='Amit', city='Pune'....

Insert multiple rows at once

Easy
3 views 23 Jan 2026
Insert 3 departments in one statement....

Update a single row

Easy
3 views 23 Jan 2026
Update customer city to 'Delhi' where customer_id=101....

Delete using a condition

Easy
2 views 23 Jan 2026
Delete orders where status='CANCELLED' and the order_date is older than 90 days from today....

Insert using SELECT

Easy
3 views 23 Jan 2026
Create a backup table OrdersBackup and copy only last month's orders into it (full rows)....

Update using a join

Medium
2 views 23 Jan 2026
Give 10% hike to Employees in department 'Tech'. Departments table has dept_name....

Delete duplicates keeping the latest

Medium
3 views 23 Jan 2026
In LoginLogs(user_id, logged_at, ip_address), remove duplicates where same user_id and ip_address appear multiple times on same day; keep the latest logged_at....

Upsert order status

Medium
2 views 23 Jan 2026
If an order exists update its status, otherwise insert it. Write an upsert pattern....

Insert into two tables with transaction

Medium
2 views 23 Jan 2026
Place an order and its order items together. If item insert fails, order should not be created....

Update based on subquery aggregate

Hard
2 views 23 Jan 2026
Give a 5% discount on Products that have not sold in the last 180 days. Use Orders + OrderItems to find what sold recently....

Soft delete pattern

Hard
3 views 23 Jan 2026
Instead of deleting customers, keep the row and mark it inactive. Add is_active (default 1) and set is_active=0 for customers who have no orders in the last 2 years....

Fix data using CASE

Hard
2 views 23 Jan 2026
In Employees, if salary is null set to 25000, if salary < 15000 set to 15000, else keep as is. Write one update statement....

Delete with correlated EXISTS

Hard
2 views 23 Jan 2026
Delete orders that have no order items (orphan orders)....

Bulk insert from CSV-like staging

Hard
2 views 23 Jan 2026
You loaded ProductsStage. Insert only valid rows (price>0 and name not null) into Products....

Basic SELECT with filter

Easy
3 views 23 Jan 2026
You have Customers(customer_id, name, city). Write a query to show only customer_id and name for customers living in 'Mumbai'. Keep it simple: one WHERE condition....

Sort results

Easy
3 views 23 Jan 2026
From Orders(order_id, order_date), show the latest 10 orders. Sort by order_date (newest first). If dates are same, you can sort by order_id too....

Count rows per group

Easy
2 views 23 Jan 2026
You need a small city-wise report. From Customers(city), return city and how many customers are in that city....

Use HAVING for group filter

Easy
3 views 23 Jan 2026
From Employees and Departments, show only those departments where employee count is more than 5. Display dept_name and the count....

Distinct values

Easy
2 views 23 Jan 2026
From Orders(status), list all different statuses available. You should not repeat the same status in output....

Top customer by total spend

Medium
2 views 23 Jan 2026
From Orders(customer_id, total_amount), find the customer who spent the most overall. First do SUM per customer, then pick the highest one....

Daily sales report

Medium
2 views 23 Jan 2026
Make a simple daily sales report for the last 7 days. From Orders(order_date, total_amount), show order_date and total sales per day....

Customers with zero orders

Medium
4 views 23 Jan 2026
List customers who never placed any order. You can solve using LEFT JOIN + NULL check (or NOT EXISTS)....

Find gaps in order ids

Medium
2 views 23 Jan 2026
Assume order_id should be continuous. Using a helper Numbers(n) table, list the missing order_id between MIN(order_id) and MAX(order_id)....

Second highest salary per department

Medium
2 views 23 Jan 2026
For each department, return employee(s) who have the second highest salary. Use DENSE_RANK so ties are handled nicely....

3-month rolling revenue

Hard
3 views 23 Jan 2026
Create month-wise revenue and also show a rolling 3-month total. First aggregate by month, then apply a window sum over the last 3 months....

Detect customers with suspicious refunds

Hard
2 views 23 Jan 2026
Assume Payments.amount is negative for refunds. Find customers where total refund is more than 30% of total paid amount. Use conditional SUM....

Find first purchase date and latest purchase date

Hard
2 views 23 Jan 2026
For each customer, show the first time they ordered and the most recent order date. This is a clean use of MIN and MAX....

Market basket: products bought together

Hard
2 views 23 Jan 2026
From OrderItems(order_id, product_id), count how often two products are bought in the same order. Return top 10 pairs by count....

Uppercase and trim names

Easy
2 views 23 Jan 2026
Return customer names trimmed and in uppercase....

Extract year from a date

Easy
2 views 23 Jan 2026
From Orders, return order_id and order_year....

Round price to 2 decimals

Easy
2 views 23 Jan 2026
Show product_id and rounded price....

COALESCE for missing phone

Easy
2 views 23 Jan 2026
Show customer_id and phone, but display 'NA' when phone is null....

String length check

Easy
2 views 23 Jan 2026
List products where name length is more than 20 characters....

Format a date column

Medium
5 views 23 Jan 2026
Show Orders with a formatted date string like YYYY-MM-DD....

Bucket customers by spend

Medium
2 views 23 Jan 2026
Create spend_bucket as LOW (20000) using CASE on total spend....

Top 3 orders per customer

Medium
2 views 23 Jan 2026
Return top 3 orders by total_amount for each customer....

Lead/lag for day-to-day change

Medium
3 views 23 Jan 2026
For daily sales, show today_sales and change_from_yesterday....

Generate a running total

Medium
2 views 23 Jan 2026
For Orders sorted by order_date, show running sum of total_amount....

Detect outliers using percentile

Hard
3 views 23 Jan 2026
Find employees whose salary is above the 90th percentile in their department....

Normalize text for search

Hard
3 views 23 Jan 2026
Create a query that removes spaces and lowercases product names for matching a user input....

Sessionize events

Hard
2 views 23 Jan 2026
In LoginLogs(user_id, logged_at), start a new session if gap > 30 minutes. Assign session_number per user....

Find median order value

Hard
3 views 23 Jan 2026
Compute the median of Orders.total_amount....

Index a frequently filtered column

Easy
3 views 23 Jan 2026
Orders table is filtered by status a lot. Create an index on status....

Composite index for search

Easy
2 views 23 Jan 2026
Customers are searched by (city, name). Create a composite index....

Unique index example

Easy
2 views 23 Jan 2026
Prevent duplicate SKU in Products using a unique index....

Drop an index

Easy
2 views 23 Jan 2026
Drop index idx_orders_status....

Index for date range queries

Easy
3 views 23 Jan 2026
Create an index for faster queries on Orders(order_date)....

Choose the right index for a query

Medium
2 views 23 Jan 2026
Query: SELECT * FROM Orders WHERE customer_id=? AND order_date BETWEEN ? AND ?. Suggest an index and write it....

Covering index idea

Medium
2 views 23 Jan 2026
Query needs only (order_date, total_amount) for reports. Create an index that helps covering these columns....

Index for joins

Medium
2 views 23 Jan 2026
Orders joins OrderItems on order_id. Write index statements to support this join....

When not to index

Medium
2 views 23 Jan 2026
You have a column gender with only 2 values. Should you index it? Provide a practical answer in description, and give no index statement....

Partial index workaround using helper column

Medium
2 views 23 Jan 2026
You want index only on active rows (status='ACTIVE'). Create a helper column active_flag and index it with customer_id....

Find unused indexes (query)

Hard
4 views 23 Jan 2026
Write a query idea to list indexes that are not used often. Keep it simple and generic....

Design index for prefix search

Hard
2 views 23 Jan 2026
Customers are searched by name starting with 'ra'. Write an index and a matching query....

Avoid duplicate indexes

Hard
3 views 23 Jan 2026
You already have index on (city, name). Someone wants another on city only. How do you decide? Put reasoning in description and leave sample_solution as a metadata check query....

Rebuild index after heavy deletes

Hard
5 views 23 Jan 2026
After deleting millions of rows, you want to rebuild an index. Provide a generic rebuild statement....

Basic inner join report

Easy
5 views 23 Jan 2026
List employee name with department name....

Left join to find missing match

Easy
2 views 23 Jan 2026
List all customers and their latest order_id if any. Customers without orders should still show....

Join three tables

Easy
2 views 23 Jan 2026
Show order_id, customer name, and total_amount....

Self join for manager relationship

Easy
2 views 23 Jan 2026
Employees(emp_id, name, manager_id). Show employee name and manager name....

Cross join for combinations

Easy
2 views 23 Jan 2026
Create all combinations of Sizes(s) and Colors(c) to generate SKU options....

Anti-join pattern

Medium
3 views 23 Jan 2026
Find products that never appear in OrderItems....

Join with date filter and aggregation

Medium
2 views 23 Jan 2026
For each customer, show total paid amount in the last 30 days. Join Orders with Payments and group by customer....

Full outer join style reconciliation

Medium
3 views 23 Jan 2026
You have table A_ids(id) and B_ids(id). Show ids that are missing on either side....

Many-to-many join with bridge table

Medium
2 views 23 Jan 2026
Students and Courses are many-to-many via Enrollment. Show student_name and course_name....

Join to pick latest row per group

Medium
2 views 23 Jan 2026
For each customer, show details of their latest order (not just id)....

Revenue by category with multi-join

Hard
2 views 23 Jan 2026
Orders, OrderItems, Products. Show category-wise revenue for shipped orders only....

Find customers who bought from every category

Hard
5 views 23 Jan 2026
Customers who have at least one purchase in each product category....

Detect overlapping shifts using self join

Hard
3 views 23 Jan 2026
Shifts(emp_id, start_time, end_time). Find employees whose shifts overlap on same day....

Top 2 products per city

Hard
3 views 23 Jan 2026
Customers(city), Orders, OrderItems. For each city, find top 2 products by quantity sold....