Basic Queries:
Retrieve all columns from a table.
SELECT * FROM employees;
Select specific columns from a table.
SELECT first_name, last_name FROM employees;
Filter records using WHERE.
SELECT * FROM employees WHERE department = 'Sales';
Use ORDER BY to sort data.
SELECT * FROM employees ORDER BY salary DESC;
Limit results to top N records.
SELECT * FROM employees ORDER BY salary DESC LIMIT 5;
Aggregation Queries:
Find the total number of employees.
SELECT COUNT(*) FROM employees;
Calculate the average salary of employees.
SELECT AVG(salary) FROM employees;
Find the highest and lowest salary.
SELECT MAX(salary) AS max_salary, MIN(salary) AS min_salary FROM employees;
Find the total salary paid in each department.
SELECT department, SUM(salary) FROM employees GROUP BY department;
Count employees per department, sorted in descending order.
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
ORDER BY employee_count DESC;
Filter aggregated results using HAVING.
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
Joins Queries:
Retrieve employees with their department names (INNER JOIN).
SELECT e.first_name, e.last_name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;
List all departments, even those without employees (LEFT JOIN).
SELECT d.department_name, e.first_name, e.last_name
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id;
Find employees without an assigned department (RIGHT JOIN).
SELECT e.first_name, e.last_name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id
WHERE e.employee_id IS NULL;
Retrieve all employees and their managers (Self Join).
SELECT e1.first_name AS employee, e2.first_name AS manager
FROM employees e1
LEFT JOIN employees e2 ON e1.manager_id = e2.employee_id;
Find employees who have the same salary as someone else (Self Join).
SELECT e1.first_name, e1.salary
FROM employees e1
JOIN employees e2 ON e1.salary = e2.salary AND e1.employee_id <> e2.employee_id;
Guess the three fastest cars among 25 cars, grouping only 5 at a time
sql
CopyEdit
SELECT * FROM cars ORDER BY speed DESC LIMIT 3;
✔ Sorts cars by speed in descending order and selects the top 3.
If you can only group 5 cars at a time, then:
sql
CopyEdit
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY speed DESC) AS rank FROM cars
) AS ranked_cars
WHERE rank <= 3;
✔ Ranks the fastest 3 cars while checking only 5 at a time.
3⃣ Managing Elevator Waiting Time in a 50-Story Building
Solution:
Use priority scheduling for peak hours (morning/evening).
Design an express elevator for floors 25–50.
Use AI-based optimization to group people based on destination floors.
Implement idle positioning to distribute elevators e iciently.
4⃣ Calculate the total number of left fingers for 5 billion people
✔ Each person has 5 fingers per hand.
✔ There are 2 hands, so one left hand per person has 5 fingers.
Solution:
Total left fingers=5×5,000,000,000=25,000,000,000\text{Total left fingers} = 5 \times
5,000,000,000 = 25,000,000,000Total left fingers=5×5,000,000,000=25,000,000,000
✔ Answer: 25 billion left fingers
5⃣ Planting 10 trees in 5 rows with 4 trees per row
✔ Solution: Arrange trees in a star (pentagram) shape so that each tree belongs to
multiple rows.
6⃣ Mislabelled Candy Box Problem
There are 3 boxes:
1. Candies A
2. Candies B
3. Mixed
All labels are incorrect.
Pick one candy from the "Mixed" box → it will tell you which type is actually inside.
Swap labels accordingly.
7⃣ Guesstimate: Find ATM Transactions at XYZ Station
✔ Approach:
1. Estimate footfall: Assume 50,000 people pass through the station daily.
2. ATM Usage Rate: Assume 10% use ATMs.
3. Average Transactions per User: Assume 1.5 transactions per person.
50,000×0.1×1.5=7,50050,000 \times 0.1 \times 1.5 = 7,50050,000×0.1×1.5=7,500
✔ Answer: 7,500 ATM transactions per day (approx.)
Betting Question
A wins 3 matches.
B has $5 initially.
For every match won, they earn $1.
Find total bets.
✔ Total matches played = 3 + X (B’s wins)
✔ Since B still has $5, this means they lost as many as they won.
✔ X = 3, so they fought 6 matches total.
Find the next number in the sequence: 3, 10, 101, ?
✔ Pattern:
3 → 10 (3² + 1 = 10)
10 → 101 (10² + 1 = 101)
101 → ? (101² + 1 = 10202)
✔ Answer: 10202
1. Fetch the Second-Highest Salary from an Employee Table
sql
CopyEdit
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
Explanation:
ORDER BY salary DESC: Sorts salaries in descending order.
LIMIT 1 OFFSET 1: Skips the highest salary (OFFSET 1) and fetches the second
highest.
Alternatively:
sql
CopyEdit
SELECT MAX(salary)
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee);
The subquery gets the highest salary.
The outer query finds the maximum salary that is lower than the highest.
2. Fetch the Nth Highest Salary
sql
CopyEdit
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET N-1; -- Replace N with the required rank
3. Find Employees with the Highest Salary
sql
CopyEdit
SELECT *
FROM Employee
WHERE salary = (SELECT MAX(salary) FROM Employee);
4. Find the Department with the Highest Average Salary
sql
CopyEdit
SELECT department_id, AVG(salary) AS avg_salary
FROM Employee
GROUP BY department_id
ORDER BY avg_salary DESC
LIMIT 1;
5. Find Employees Earning More Than the Average Salary
sql
CopyEdit
SELECT *
FROM Employee
WHERE salary > (SELECT AVG(salary) FROM Employee);
6. Fetch Duplicate Records Based on Salary
sql
CopyEdit
SELECT salary, COUNT(*)
FROM Employee
GROUP BY salary
HAVING COUNT(*) > 1;
7. Find Employees Without a Manager (Self-Join)
sql
CopyEdit
SELECT e.*
FROM Employee e
LEFT JOIN Employee m ON e.manager_id = m.id
WHERE m.id IS NULL;
Would you like queries for any specific SQL concepts like joins, ranking, or window
functions?
You said:
question were given to solve it was easy level...student and their marks were given and
have to find out highest lowest rank
ChatGPT said:
Here are some SQL queries to solve the problem of ranking students based on their marks:
1. Creating the Sample Table
sql
CopyEdit
CREATE TABLE Students (
id INT PRIMARY KEY,
name VARCHAR(50),
marks INT
);
INSERT INTO Students (id, name, marks) VALUES
(1, 'Alice', 85),
(2, 'Bob', 92),
(3, 'Charlie', 78),
(4, 'David', 95),
(5, 'Eve', 88);
2. Find the Student with the Highest Marks
sql
CopyEdit
SELECT name, marks
FROM Students
ORDER BY marks DESC
LIMIT 1;
3. Find the Student with the Lowest Marks
sql
CopyEdit
SELECT name, marks
FROM Students
ORDER BY marks ASC
LIMIT 1;
4. Rank Students by Marks (Using RANK())
sql
CopyEdit
SELECT name, marks, RANK() OVER (ORDER BY marks DESC) AS rank
FROM Students;
This assigns a rank based on marks, with ties getting the same rank.
5. Rank Students Without Gaps (Using DENSE_RANK())
sql
CopyEdit
SELECT name, marks, DENSE_RANK() OVER (ORDER BY marks DESC) AS rank
FROM Students;
Unlike RANK(), this ensures no gaps in ranking.
6. Find the Student with the 2nd Highest Marks
sql
CopyEdit
SELECT name, marks
FROM Students
ORDER BY marks DESC
LIMIT 1 OFFSET 1;
Fetch Nth Highest Salary
Using LIMIT, OFFSET
sql
CopyEdit
SELECT salary
FROM employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1; -- Fetch 2nd highest salary (0-based index)
Using DISTINCT and LIMIT
sql
CopyEdit
SELECT DISTINCT salary
FROM employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
Using RANK()
sql
CopyEdit
SELECT salary
FROM (
SELECT salary, RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employee
) ranked
WHERE rnk = 2; -- 2nd highest salary
2. Retrieve Highest & Lowest Marks of Students
Highest Marks
sql
CopyEdit
SELECT student_name, marks
FROM students
ORDER BY marks DESC
LIMIT 1;
Lowest Marks
sql
CopyEdit
SELECT student_name, marks
FROM students
ORDER BY marks ASC
LIMIT 1;
Using MAX() & MIN()
sql
CopyEdit
SELECT MAX(marks) AS highest_marks, MIN(marks) AS lowest_marks
FROM students;
3. Rank Students Based on Marks
Using RANK()
sql
CopyEdit
SELECT student_name, marks,
RANK() OVER (ORDER BY marks DESC) AS rank
FROM students;
Using DENSE_RANK()
sql
CopyEdit
SELECT student_name, marks,
DENSE_RANK() OVER (ORDER BY marks DESC) AS dense_rank
FROM students;
Using ROW_NUMBER()
sql
CopyEdit
SELECT student_name, marks,
ROW_NUMBER() OVER (ORDER BY marks DESC) AS row_number
FROM students;
4. Fetch Duplicate Records
sql
CopyEdit
SELECT name, COUNT(*)
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;
5. Employees Earning More Than Their Manager
sql
CopyEdit
SELECT e.name AS employee_name, e.salary, m.name AS manager_name, m.salary AS
manager_salary
FROM employee e
JOIN employee m ON e.manager_id = m.id
WHERE e.salary > m.salary;
6. Fetch Top 3 Selling Products
sql
CopyEdit
SELECT product_id, SUM(quantity) AS total_sold
FROM sales
GROUP BY product_id
ORDER BY total_sold DESC
LIMIT 3;
7. Find Continuous Login Streaks
sql
CopyEdit
SELECT user_id, login_date,
DATEDIFF(login_date, LAG(login_date) OVER (PARTITION BY user_id ORDER BY
login_date)) AS streak
FROM user_logins;
8. Identify Employees Without a Manager
sql
CopyEdit
SELECT name
FROM employees
WHERE manager_id IS NULL;
9. Fetch the Most Recent Order for Each Customer
sql
CopyEdit
SELECT customer_id, order_id, order_date
FROM (
SELECT customer_id, order_id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS
rn
FROM orders
) ranked
WHERE rn = 1;
Would you like more queries on a specific topic?
You said:
Syntax for SQL basics, joins, aggregate functions and subqueries
ChatGPT said:
Here’s a detailed syntax guide for SQL basics, joins, aggregate functions, and
subqueries:
1. SQL Basics
Create Table
sql
CopyEdit
CREATE TABLE table_name (
column1 datatype PRIMARY KEY,
column2 datatype NOT NULL,
column3 datatype DEFAULT value
);
Insert Data
sql
CopyEdit
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);
Update Data
sql
CopyEdit
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
Delete Data
sql
CopyEdit
DELETE FROM table_name
WHERE condition;
Select Data
sql
CopyEdit
SELECT column1, column2
FROM table_name
WHERE condition
ORDER BY column1 ASC;
Filter with WHERE and AND/OR
sql
CopyEdit
SELECT * FROM employees
WHERE department = 'IT' AND salary > 50000;
Using BETWEEN, IN, LIKE, IS NULL
sql
CopyEdit
SELECT * FROM employees WHERE salary BETWEEN 50000 AND 100000;
SELECT * FROM employees WHERE department IN ('IT', 'HR', 'Finance');
SELECT * FROM employees WHERE name LIKE 'J%';
SELECT * FROM employees WHERE manager_id IS NULL;
2. SQL Joins
Inner Join
sql
CopyEdit
SELECT e.name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.id;
Left Join
sql
CopyEdit
SELECT e.name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.id;
Right Join
sql
CopyEdit
SELECT e.name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.department_id = d.id;
Full Outer Join (Not supported in MySQL)
sql
CopyEdit
SELECT e.name, d.department_name
FROM employees e
FULL OUTER JOIN departments d ON e.department_id = d.id;
Self Join
sql
CopyEdit
SELECT e1.name AS employee, e2.name AS manager
FROM employees e1
JOIN employees e2 ON e1.manager_id = e2.id;
3. Aggregate Functions
Count Total Employees
sql
CopyEdit
SELECT COUNT(*) AS total_employees FROM employees;
Find Average Salary
sql
CopyEdit
SELECT AVG(salary) AS avg_salary FROM employees;
Find Maximum & Minimum Salary
sql
CopyEdit
SELECT MAX(salary) AS highest_salary, MIN(salary) AS lowest_salary FROM employees;
Sum of Salaries in Each Department
sql
CopyEdit
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;
Count Employees in Each Department
sql
CopyEdit
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;
Using HAVING (Filtering After Aggregation)
sql
CopyEdit
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
4. SQL Subqueries
Subquery in WHERE
sql
CopyEdit
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Subquery in SELECT
sql
CopyEdit
SELECT name,
(SELECT department_name FROM departments WHERE id = e.department_id) AS
department
FROM employees e;
Subquery in FROM (Derived Table)
sql
CopyEdit
SELECT department, avg_salary
FROM (SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY
department) AS dept_avg
WHERE avg_salary > 50000;
Using EXISTS
sql
CopyEdit
SELECT name
FROM employees e
WHERE EXISTS (SELECT 1 FROM departments d WHERE d.id = e.department_id);
Using IN
sql
CopyEdit
SELECT name FROM employees
WHERE department_id IN (SELECT id FROM departments WHERE location = 'New York');
It looks like you're preparing for SQL, RCA (Root Cause Analysis), guesstimates, product
management, and puzzle-based interviews, possibly for data analytics or product
management roles. Here’s a structured way to prepare for each of these topics:
1. SQL Queries (Joins, Metrics, Modifications, and Deep Dives)
Joining 4 Tables Example
SELECT e.name, d.department_name, p.project_name, s.salary
FROM employees e
JOIN departments d ON e.department_id = d.id
JOIN projects p ON e.project_id = p.id
JOIN salaries s ON e.id = s.employee_id;
Find the 3rd Highest Salary
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
SQL Query Modification Questions
Be ready for “What will be the output?” type of questions where they modify a
query.
Understand GROUP BY, HAVING, WINDOW FUNCTIONS like RANK() and
DENSE_RANK().
2. Root Cause Analysis (RCA) and Business Metrics Questions
These focus on identifying problems and forming hypotheses.
Example RCA: YouTube Views Dropped by 25%
Possible causes:
Internal factors: Algorithm changes, UI redesign, video recommendation changes.
External factors: Seasonality, competition (TikTok, Instagram Reels), platform issues.
Data Issues: Tracking errors, filtering changes, bot removal.
Business Impact: Revenue drop, engagement decline, ad performance.
Relevant Metrics for Swiggy CX-Level Dashboard
Order Volume & Growth
Repeat Customer Rate
Delivery Time & Success Rate
Cancellation Rate & Refunds
Customer Satisfaction Score (CSAT), Net Promoter Score (NPS)
Peak Hour Performance
3. Optimization & Strategy Questions
Optimizing CPC (Cost Per Click) for a Website
Improve Ad Quality Score (CTR, Landing Page Experience, Ad Relevance).
Target High-Intent Keywords (reduce wasted spend).
Use Negative Keywords (exclude irrelevant tra ic).
A/B Testing Ads (improve conversion rate).
Geo & Device Targeting (optimize bids per user segment).
Optimizing 4 Lifts in a 40-Story Building
Algorithm-based lift allocation (AI/ML predictive scheduling).
Zoning Strategy (assign specific floors to lifts).
Peak Hour Optimization (morning = up-heavy, evening = down-heavy).
Smart Scheduling (anticipate demand, reduce wait times).
4. Web Technologies & System Design
DNS, HTTP, Session, Cookies (Basics)
DNS (Domain Name System): Converts domain names into IP addresses.
HTTP vs HTTPS: HTTPS is encrypted, uses SSL/TLS.
Sessions vs Cookies: Sessions are stored on the server, cookies on the client.
Proxy vs VPN
Proxy: Hides your IP, but doesn’t encrypt data.
VPN: Encrypts data + hides IP, ensuring privacy.
5. Puzzles (Logical & Probability)
Mislabeled Jars Puzzle
Approach: Pick a fruit from the "Mixed" jar (since all jars are mislabeled).
Example: If you get an apple, that jar must be "Apples", then relabel others
accordingly.
Car with 4 Tires + 1 Spare (Max Distance)
Solution: Rotate all tires evenly to maximize usage.
Formula: (Total Tire Lifespan * 5) / 4.
Two Ropes Measuring Time
First Rope: Burn from both ends (30 mins).
Second Rope: Start after 30 mins from both ends (15 mins).
Total = 45 mins.
6. Business & Product Strategy Questions
Netflix View per User Drop Case Study
Hypotheses:
UI/UX changes a ecting navigation.
Competitor content pulling users away.
Subscription price increase reducing engagement.
Technical issues (slow streaming, bugs).
Recommendation algorithm changes.
Amazon vs Flipkart Subscription Analysis
Compare user retention, benefits (Prime vs Flipkart Plus), logistics, discounts,
and market share impact.
Uber Driver & Passenger Improvements
Driver: Better incentives, dynamic pricing, fuel cost optimization.
Passenger: Route transparency, better surge pricing logic, safety improvements.
7. Case Studies & Guesstimates
Airport Commute Optimization: Tra ic data, peak hours, ride-sharing incentives.
Ola Price Comparison: Surge pricing model, competitor adjustments, dynamic
discounting.
Final Notes & Preparation Tips
Practice SQL queries, joins, aggregation, ranking functions.
Prepare for RCA questions with structured problem-solving (internal, external,
competitive factors).
Solve puzzles using logic and breaking problems into parts.
Know web technologies, APIs, and system design basics.
Work on Excel Pivot Tables, VLOOKUP, revenue breakdown analysis.
Would you like me to focus on specific SQL questions or business case frameworks?
That's a great set of logical puzzles, SQL queries, and guesstimate problems! I'll go ahead
and provide solutions to each of them:
Puzzles & Logical Thinking Solutions
1⃣ Measuring 4 Liters using 3L, 5L, and 8L Buckets
1. Fill the 5L bucket completely. (5L)
2. Pour water from the 5L bucket into the 3L bucket. Now you have:
o 3L bucket → Full (3L)
o 5L bucket → 2L remaining
3. Empty the 3L bucket and transfer the 2L from the 5L bucket into it.
4. Fill the 5L bucket again.
5. Pour from the 5L bucket into the 3L bucket (which already has 2L). Now:
o 3L bucket → Full (3L)
o 5L bucket → 4L remaining
2⃣ Finding the Faulty Heavy Ball (9 Balls, Weighing Beam, 3 Weighings Max)
Step 1: First Weighing
Divide balls into 3 groups of 3 balls each.
Weigh Group A vs Group B.
If balanced → Faulty ball is in Group C. Otherwise, it is in the heavier group.
Step 2: Second Weighing
Take two balls from the heavier group and weigh them against each other.
o If balanced → The third ball is faulty.
o Otherwise → The heavier ball is faulty.
3⃣ Finding the Heavy Bottle (10 Bottles, 1.1g Pills, 1 Measurement Allowed)
1. Take 1 pill from Bottle 1, 2 from Bottle 2, 3 from Bottle 3 … up to 10 pills from
Bottle 10.
2. Weigh them together.
3. If all were 1g each, the total weight should be (1+2+3+...+10) = 55g.
4. If the actual weight is 55 + X * 0.1g, then Bottle X is the heavy one.
4⃣ Measuring 90 Minutes with 2 Uneven Burning Ropes
1. Light Rope 1 from both ends and Rope 2 from one end.
o Rope 1 burns in 30 minutes.
2. When Rope 1 is fully burned, light the other end of Rope 2.
o Rope 2 will now burn in 30 more minutes.
3. Total time = 30 + 30 + 30 = 90 minutes
5⃣ Bridge Crossing Problem (15 Minutes Limit)
A (1 min), B (2 min), C (5 min), D (8 min)
Optimal Steps:
1. A & B cross (2 min)
2. A returns (3 min total)
3. C & D cross (11 min total)
4. B returns (13 min total)
5. A & B cross again (15 min total, all crossed)
6⃣ Snail Climbing the 30m Well
Snail climbs 3m in the day and slips 2m at night → Net gain = 1m/day.
After 27 days, the snail reaches 27m by the end of the day.
On Day 28, the snail climbs 3m and reaches the top.
Answer: 28 Days
7⃣ Planting 10 Trees in 5 Rows with 4 Trees Each
Arrange the trees in a pentagram (star) shape, where each row shares trees with
other rows.
8⃣ Find the 3 Fastest Cars Among 25 (5 Cars per Race, Min Races?)
1. 5 Races → Each race has 5 cars, finding the fastest from each group.
2. 6th Race → Winners of 5 groups race to get the fastest car.
3. 7th Race → Take 2nd & 3rd place of the 6th race + 2nd & 3rd place from the winner’s
original race.
4. The top 3 from this final race are the 3 fastest.
Answer: 7 Races
SQL Queries
1⃣ Get the Highest Salary from Employee Table
SELECT MAX(salary) FROM employee;
2⃣ Get the Second Highest Salary
SELECT MAX(salary) FROM employee
WHERE salary < (SELECT MAX(salary) FROM employee);
3⃣ Query for Join
SELECT employees.name, departments.dept_name
FROM employees
JOIN departments ON employees.dept_id = departments.dept_id;
Business & Guesstimate Questions
1⃣ Website Revenue Drop - Possible Causes
✔ Technical Issues: Server downtime, slow page load times
✔ Market Trends: Seasonal changes, competitor price cuts
✔ Marketing Failure: Poor ad targeting, high ad costs
✔ User Experience Issues: High cart abandonment, confusing UI
2⃣ How Many Elevators for a 50-Story Building?
Factors: Peak hours, occupancy per floor, waiting time limits
Typical Estimate: ~6-10 elevators for smooth operation
3⃣ Guesstimate: ATM Transactions Per Day at a Busy Station
1. Assume 50,000 people use the station daily.
2. 10% use the ATM → 5,000 people.
3. Avg withdrawal time = 2 min → 5,000 × 2 = 10,000 min/day
4. If ATM operates 18 hours/day (~1,080 min), it needs ~9-10 ATMs
4⃣ Chessboard Squares Puzzle
Total squares in 8×8 board:
1. 1×1 squares: 64
2. 2×2 squares: 49
3. 3×3 squares: 36
4. 4×4 squares: 25
5. 5×5 squares: 16
6. 6×6 squares: 9
7. 7×7 squares: 4
8. 8×8 square: 1
Total = 204 squares
5⃣ Egg Doubling in a Basket Puzzle
Eggs double every minute.
Full at 60 min, so half-full at 59 min.
6⃣ Cut Cake into 8 Pieces with 3 Cuts
1. First Cut: Slice the cake in half.
2. Second Cut: Slice it perpendicularly (4 pieces).
3. Third Cut: Slice horizontally (8 pieces).
Would you like more mock interview questions or live SQL query problems?