0% found this document useful (0 votes)
15 views112 pages

Brainalyst's SQL Interview Guide

Sql

Uploaded by

Rahul Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views112 pages

Brainalyst's SQL Interview Guide

Sql

Uploaded by

Rahul Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 112

Q

S
I
NT
G
U
Q
E
R
I
VI
D
E
E
L
W
QUESTI
ONS
&ANSWERS
ABOUT BRAINALYST

Brainalyst is a pioneering data-driven company dedicated to transforming data into actionable insights and
innovative solutions. Founded on the principles of leveraging cutting-edge technology and advanced analytics,
Brainalyst has become a beacon of excellence in the realms of data science, artificial intelligence, and machine
learning.

OUR MISSION

At Brainalyst, our mission is to empower businesses and individuals by providing comprehensive data solutions
that drive informed decision-making and foster innovation. We strive to bridge the gap between complex data and
meaningful insights, enabling our clients to navigate the digital landscape with confidence and clarity.

WHAT WE OFFER

1. Data Analytics and Consulting


Brainalyst offers a suite of data analytics services designed to help organizations harness the power of their
data. Our consulting services include:

• Data Strategy Development: Crafting customized data strategies aligned with your business
objectives.

• Advanced Analytics Solutions: Implementing predictive analytics, data mining, and statistical
analysis to uncover valuable insights.

• Business Intelligence: Developing intuitive dashboards and reports to visualize key metrics and
performance indicators.

2. Artificial Intelligence and Machine Learning


We specialize in deploying AI and ML solutions that enhance operational efficiency and drive innovation.
Our offerings include:

• Machine Learning Models: Building and deploying ML models for classification, regression,
clustering, and more.

• Natural Language Processing: Implementing NLP techniques for text analysis, sentiment analysis,
and conversational AI.

• Computer Vision: Developing computer vision applications for image recognition, object detection,
and video analysis.

3. Training and Development


Brainalyst is committed to fostering a culture of continuous learning and professional growth. We provide:

• Workshops and Seminars: Hands-on training sessions on the latest trends and technologies in
data science and AI.

• Online Courses: Comprehensive courses covering fundamental to advanced topics in data


analytics, machine learning, and AI.

• Customized Training Programs: Tailored training solutions to meet the specific needs of
organizations and individuals.

2021-2024
4. Generative AI Solutions

As a leader in the field of Generative AI, Brainalyst offers innovative solutions that create new content and
enhance creativity. Our services include:

• Content Generation: Developing AI models for generating text, images, and audio.

• Creative AI Tools: Building applications that support creative processes in writing, design, and
media production.

• Generative Design: Implementing AI-driven design tools for product development and
optimization.

OUR JOURNEY

Brainalyst’s journey began with a vision to revolutionize how data is utilized and understood. Founded by
Nitin Sharma, a visionary in the field of data science, Brainalyst has grown from a small startup into a renowned
company recognized for its expertise and innovation.

KEY MILESTONES:

• Inception: Brainalyst was founded with a mission to democratize access to advanced data analytics and AI
technologies.

• Expansion: Our team expanded to include experts in various domains of data science, leading to the
development of a diverse portfolio of services.

• Innovation: Brainalyst pioneered the integration of Generative AI into practical applications, setting new
standards in the industry.

• Recognition: We have been acknowledged for our contributions to the field, earning accolades and
partnerships with leading organizations.

Throughout our journey, we have remained committed to excellence, integrity, and customer satisfaction.
Our growth is a testament to the trust and support of our clients and the relentless dedication of our team.

WHY CHOOSE BRAINALYST?

Choosing Brainalyst means partnering with a company that is at the forefront of data-driven innovation. Our
strengths lie in:

• Expertise: A team of seasoned professionals with deep knowledge and experience in data science and AI.

• Innovation: A commitment to exploring and implementing the latest advancements in technology.

• Customer Focus: A dedication to understanding and meeting the unique needs of each client.

• Results: Proven success in delivering impactful solutions that drive measurable outcomes.

JOIN US ON THIS JOURNEY TO HARNESS THE POWER OF DATA AND AI. WITH BRAINALYST, THE FUTURE IS
DATA-DRIVEN AND LIMITLESS.

2021-2024
BRAINALYST - SQL INTERVIEW QUESTIONS
SQL Roadmap
Truncate Table What are Relational Database?
Alter Table
RDBMS Benefits and Limitations
Create Table
Introduction
SQL vs NoSQL Databases
Data Defination Language (DDL) Basic SQL Syntox
SQL Keywords

Data Types
Data Manipulation Language (DDL) SELECT

Operators
FROM FROM

ORDER BY GROUP BY SELECT INSERT


SUM COUNT
HAVING JOINs
UPDATE DELETE
AVG MIN MAX
INSERT UPDATE DELETE Statements

SELECT

Aggregate Queries Data Constraints JOIN Queries

Primary Key INNER JOIN


GROUP BY
Foreign Key LEFT JOIN
HAVING
Unique RIGHT JOIN

Creating Views NOT NULL FULL OUTER JOIN

Views Modifing Views CHECK Self Join Cross Join


Dropping Views

CONCAT LENGTH Scalar Column


FLOOR ABS MOD Table
SUBSTRING REPLACE Row

UPPER LOWER ROUND CEILING Types of Sub Queries

String Functions Numeric Nested Subqueries Sub Queries

Correlated Subqueris

Advanced SQL Functions

Date and Time Conditional Data Integrity and Security


Data Integrity Constraints
DATE TIME CASE NULLIF
DATEPART DATEADD COALESCE GRANT and REVOKE

TIMESTAMP Database Security Best Practices


BEGIN

Indexes Managing Indexes COMMIT Stored Procudures and Functions

ROLLBACK Performance Optimization


Query Optimization
ACID SAVEPOINT
Query Optimization Techniques

Transactions Using Indexes


Optimizing Joins
Reducing Subqueries
Transactions Isolation Levels
Selective Projection

Advanced SQL Concepts Query Analysis Techniques

Recursive Queries Row_number

Pivot and Unpivot Operations rank

Window Functions dense_rank

CTEs (Common Table Expressions) lead lag

Dynamic SQL

Pg. No.1 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Complete SQL (Topic wise):-


1. Basic SQL Syntax:
SQL keywords
Data types
Operators
SQL statements (SELECT, INSERT, UPDATE, DELETE)
2. Data Definition Language (DDL):
CREATE TABLE
ALTER TABLE
DROP TABLE
Truncate table
3. Data Manipulation Language (DML):
SELECT statement (SELECT, FROM, WHERE, ORDER BY, GROUP BY, HAVING, JOINs)
INSERT statement
UPDATE statement
DELETE statement
4. Aggregate Functions:
SUM, AVG, COUNT, MIN, MAX
GROUP BY clause
HAVING clause
5. Data Constraints:
Primary Key
Foreign Key
Unique
NOT NULL
CHECK
6. Joins:
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL OUTER JOIN
Self Join
Cross Join
7. Subqueries:
Types of subqueries (scalar, column, row, table)
Nested subqueries
Correlated subqueries

2021-2024 Pg. No.2


BRAINALYST - SQL INTERVIEW QUESTIONS

8. Advanced SQL Functions:


String functions (CONCAT, LENGTH, SUBSTRING, REPLACE, UPPER, LOWER)
Date and time functions (DATE, TIME, TIMESTAMP, DATEPART, DATEADD)
Numeric functions (ROUND, CEILING, FLOOR, ABS, MOD)
Conditional functions (CASE, COALESCE, NULLIF)
9. Views:
Creating views
Modifying views
Dropping views
10. Indexes:
Creating indexes
Using indexes for query optimization
11. Transactions:
ACID properties
Transaction management (BEGIN, COMMIT, ROLLBACK, SAVEPOINT)
Transaction isolation levels
12. Data Integrity and Security:
Data integrity constraints (referential integrity, entity integrity)
GRANT and REVOKE statements (granting and revoking permissions)
Database security best practices
13. Stored Procedures and Functions:
Creating stored procedures
Executing stored procedures
Creating functions
Using functions in queries
14. Performance Optimization:
Query optimization techniques (using indexes, optimizing joins, reducing subqueries)
Performance tuning best practices
15. Advanced SQL Concepts:
Recursive queries
Pivot and unpivot operations
Window functions (Row_number, rank, dense_rank, lead & lag)
CTEs (Common Table Expressions)
Dynamic SQL

Pg. No.3 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Tips:
problem-solving:-
1. Understand the Problem: Before attempting a solution, fully understand the problem and clarify what
output is expected.
2. Identify Required Tables: Determine which tables are needed for the problem. Assess if any joins are
necessary.
3. Evaluate Filter Conditions: Check if any filtering conditions are required to refine the data.
4. Consider Aggregation and Grouping: Determine if the problem requires any aggregation or grouping of
data.
5. Develop the Logic: After considering the above steps, think about the logic that will yield the desired
output.
6. Leverage Others’ Solutions for Learning: If you’re a beginner, don’t hesitate to look at others’ solutions
for understanding different approaches.
7. Avoid Stubbornness: Initially, don’t be stubborn about solving the problem alone. Feel free to check
others’ solutions to gain perspective.
8. Seek Help When Stuck: If you’re still unable to understand a solution, you can ask ChatGPT to explain it
step-by-step according to the flow of execution.
9. Practice with Real Data: For a better understanding of each step’s output, consider creating the table in
a database and examining the results of each step yourself.
“Explain about your recent project.” Sounds familiar, right? It’s a common question in job interviews,
yet many of us struggle to answer it effectively. Why is that?

Takeaway:
Be prepared, clear, and impact-focused to master this question. Your project’s story reflects your
professional journey.
1. Understanding Various Types of Joins: Familiarize yourself with the outputs of different joins,
including non-equi joins.
2. Window Functions & Their Variations: Differentiate and grasp the nuances between various window
functions available in SQL.
3. Distinguishing ‘WHERE’ vs ‘HAVING’: Understand the disparity between these SQL clauses and their
appropriate usage.
4. Query Order of Execution: Know the sequence in which SQL queries are executed.
5. Creating and Utilizing CTEs (Common Table Expressions): Learn how and when to implement CTEs
effectively.
6. Aggregation Functions as Window Functions: Comprehend using aggregate functions within window
functions for more advanced operations.

2021-2024 Pg. No.4


BRAINALYST - SQL INTERVIEW QUESTIONS

7. Commonly Asked Queries: Be well-versed in solving frequently asked questions like finding the
2nd/3rd highest salary, cumulative/running total queries, employing lead & lag functions, and
utilizing self-joins and other join types.
8. Subqueries and their Application: Nested queries within a main SQL query, useful for complex
filtering or operations.
9. Indexing and its Importance in Query Performance: Enhances data retrieval speed by creating
efficient pathways for searching data.
10. Handling NULL Values in SQL: Managing and treating NULL values effectively within SQL queries.
11. Joins vs. Subqueries: Differentiating when to use joins or subqueries for better query efficiency.
Note:
The Essence of Window Functions
Window functions allow users to carry out calculations across a set of table rows that are related to the
current row. This is akin to a moving window that shifts through rows, and as it moves, calculations are
performed for each row relative to the position of the window.

The Significance of Window Functions


1. Analytical Depth: They empower you to execute complex analytical tasks, like calculating running totals,
averages, or ranking each row in a result set.
2. Flexibility: Window functions are unique in that they don’t affect the granularity of the result set. Unlike
GROUP BY which condenses results, window functions maintain the original row count.
3. Enhanced Performance: Complex data operations that would otherwise require joining tables or writing
subqueries can be streamlined with window functions.

Types of Window Functions in SQL


1. Ranking Functions:
෮ ROW_NUMBER(): Assigns a unique sequential integer to rows within a partition.
෮ RANK(): Assigns a rank to each row within a partition with the same rank for tied values.
෮ DENSE_RANK(): Same as RANK, but without gaps between rank values when there are tied values.
෮ NTILE(n): Divides the result set into n number of approximately equal parts.
2. Aggregate Functions: Most common aggregate functions like SUM(), AVG(), MIN(), and MAX() can be
used as window functions by providing an OVER() clause.

Pg. No.5 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

3. Offset Functions:
෮ LEAD(): Fetches the value of a given expression for the next row in the result set.
෮ LAG(): Fetches the value of a given expression for the previous row in the result set.
෮ FIRST_VALUE(): Provides the value of the specified expression for the first row of the window
frame.
෮ LAST_VALUE(): Provides the value of the specified expression for the last row of the window
frame.
4. Statistical Functions: Examples include CUME_DIST() and PERCENT_RANK(), which are used to calculate
cumulative distributions and relative rank respectively.
Conclusion:
Window functions breathe life into SQL queries, making them dynamic, concise, and efficient. They allow
us to look at data in context, providing insights that would be difficult to extract otherwise. As the world
of data continues to grow and evolve, mastery of such tools is invaluable.
Note:
Window Functions: Learn how to use OVER() for advanced analytics tasks. They are crucial for calculating
running totals, rankings, and lead-lag analysis in datasets.
CTEs and Temp Tables: Common Table Expressions (CTEs) and temporary tables can simplify complex
queries, especially when dealing with large datasets.
Dynamic SQL: Understand how to construct SQL queries dynamically to increase the flexibility of your
database interactions.
Optimizing Queries for Performance: Explore how indexing, query restructuring, and understanding exe-
cution plans can drastically improve your query performance.
Using PIVOT and UNPIVOT: These operations are key for converting rows to columns and vice versa, mak-
ing data more readable and analysis-friendly.

Mostly are Interview asked questions:


Q1. Explain order of execution of SQL.
Answer:
Order of execution of SQL:
The order of execution in SQL is as follows:
• FROM: The tables listed in the FROM clause are accessed and joined together, forming the
initial result set.
• WHERE: The WHERE clause filters rows from the result set based on the specified conditions.
• GROUP BY: Rows in the result set are grouped based on the columns specified in the GROUP
BY clause.

2021-2024 Pg. No.6


BRAINALYST - SQL INTERVIEW QUESTIONS

• HAVING: The HAVING clause filters groups from the result set based on the specified
conditions.
• SELECT: The columns specified in the SELECT clause are evaluated to produce the result set.
• ORDER BY: The rows in the result set are sorted based on the columns specified in the
ORDER BY clause.

Q2. What is the use of group by?


Answer:
The GROUP BY clause is used to group rows that have the same values into summary rows, typically
for use with aggregate functions like SUM, COUNT, AVG, etc.

Q3. Explain all types of joins in SQL?


Answer:
There are several types of joins in SQL:
• INNER JOIN: Returns only the rows that have matching values in both tables.
• LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table and the matched rows
from the right table. If no matching rows found in the right table, NULL values are returned.
• RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table and the matched
rows from the left table. If no matching rows found in the left table, NULL values are returned.
• FULL JOIN (or FULL OUTER JOIN): Returns all rows when there is a match in either left or
right table.
• CROSS JOIN: Returns the Cartesian product of the two tables, resulting in all possible
combinations of rows.

Q4. What are triggers in SQL?


Answer:
Triggers in SQL are special stored procedures that are automatically executed (or fired) when certain
events occur in the database. These events can include INSERT, UPDATE, DELETE operations on
specific tables.

Pg. No.7 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Q5. What is stored procedure in SQL?


Answer:
A stored procedure in SQL is a precompiled collection of SQL statements and procedural logic that
is stored in the database and can be executed repeatedly by calling the procedure name. It helps in
modularizing and reusing code.

Q6. Explain all types of window functions? (Mainly rank, row_num, dense_rank, lead & lag)
Answer:
Window functions are used to perform calculations across a set of rows related to the current row.
Common window functions include:
• ROW_NUMBER(): Assigns a unique integer to each row within a partition of a result set.
• RANK(): Assigns a unique rank to each row within a result set, with gaps in the ranking sequence.
• DENSE_RANK(): Like RANK(), but without gaps in the ranking sequence.
• LEAD(): Accesses data from subsequent rows within the same result set.
• LAG(): Accesses data from previous rows within the same result set.

Q7. What is difference between Delete and Truncate?


Answer:
DELETE is a DML (Data Manipulation Language) command used to remove rows from a table based
on a condition, while TRUNCATE is a DDL (Data Definition Language) command used to remove all
rows from a table, but it does not log individual row deletions, making it faster than DELETE.

Q8. What is difference between DML, DDL and DCL?


Answer:
• DML (Data Manipulation Language): Used to manipulate data in the database, including
operations like SELECT, INSERT, UPDATE, and DELETE.
• DDL (Data Definition Language): Used to define and modify the structure of database objects,
including operations like CREATE, ALTER, DROP, and TRUNCATE.
• DCL (Data Control Language): Used to control access to data in the database, including
operations like GRANT and REVOKE.

Q9. What is aggregate function and when do we use them? explain with few examples.
Answer:
Aggregate functions are used to perform calculations on sets of values and return a single value.
Examples include SUM, AVG, COUNT, MAX, MIN. They are typically used with the GROUP BY clause
to calculate summary statistics for groups of rows.

2021-2024 Pg. No.8


BRAINALYST - SQL INTERVIEW QUESTIONS

Q10. Which is faster between CTE and Subquery?


Answer:
Common Table Expressions (CTE) and subqueries can achieve similar results, but CTEs are generally
considered more readable and easier to maintain. In terms of performance, there may not be a sig-
nificant difference between the two approaches, and it depends on factors like the specific query, the
size of the dataset, and the database optimization. However, in some cases, CTEs can be optimized
better by the database engine compared to equivalent subqueries.

Q11. What are window functions in SQL and how are they used?
Answer:
Window functions in SQL are special functions that operate on a set of rows called a “window” within
a query result. They allow you to perform calculations across a set of rows related to the current row.

Q12. How do you define a window in SQL?


Answer:
A window in SQL is defined using the OVER() clause, which specifies the window within which the
window function operates. The window can be defined by partitioning the rows into groups and
ordering them as needed.

Q13. What is the difference between a regular aggregate function and a window function?
Answer:
A regular aggregate function, such as SUM or AVG, computes a single result value from a set of input
values, typically grouped together. In contrast, a window function performs a calculation across a set
of rows related to the current row, without collapsing them into a single result.

Q14. Can you give an example of a problem that can be solved using a window function?
Answer:
Calculating a moving average of a time series data, where each value in the series is replaced by the
average of itself and its neighbouring values.

Q15. What is the syntax for using a window function in SQL?


Answer:
SELECT column1, column2, ..., window_function() OVER (window_specification)
FROM table_name;

Q16. How do you use the OVER() clause in SQL?


Answer:
The OVER() clause defines the window within which the window function operates. It specifies the
partitioning, ordering, and framing of rows for the window function.

Pg. No.9 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Q17. What is a partition in a window function?


Answer:
A partition in a window function is a way to divide the rows into groups based on one or more column
values. The window function operates independently within each partition.

Q18. How do you specify the order of the rows in a window function?
Answer:
You can specify the order of rows in a window function using the ORDER BY clause within the OVER()
clause. This determines the sequence in which the rows are processed by the window function.

Q19. Can you give an example of a query that uses the ROW_NUMBER() window function?
Answer:
SELECT column1, column2, ..., ROW_NUMBER() OVER (ORDER BY column1) AS row_num
FROM table_name;

Q20. Can you give an example of a query that uses the RANK() window function?
Answer:
SELECT column1, column2, ..., RANK() OVER (PARTITION BY column3 ORDER BY column2 DESC) AS
rank_num
FROM table_name;

Q21. What is the usage of the NVL() function?


Answer:
The NVL() function is used to convert the NULL value to the other value. The function returns the
value of the second parameter if the first parameter is NULL. If the first parameter is anything other
than NULL, it is left unchanged. This function is used in Oracle, not in SQL and MySQL. Instead of
NVL() function, MySQL have IFNULL() and SQL Server have ISNULL() function.

Q22. What is the difference between DROP and TRUNCATE commands?


Answer:
If a table is dropped, all things associated with that table are dropped as well. This includes the
relationships defined on the table with other tables, access privileges, and grants that the table has,
as well as the integrity checks and constraints.
However, if a table is truncated, there are no such problems as mentioned above. The table retains
its original structure, and the data is dropped.

Q23. Difference between having and where clause in SQL.


Answer:
WHERE Clause is used to filter the records from the table based on the specified condition. HAVING
Clause is used to filter record from the groups based on the specified condition.

2021-2024 Pg. No.10


BRAINALYST - SQL INTERVIEW QUESTIONS

Q24. What Is Interpolation and Extrapolation?


Answer:
Interpolation is the process of calculating the unknown value from known given values whereas
extrapolation is the process of calculating unknown values beyond the given data points.

Q25. SQL joins and Groups.


Answer:
The SQL Joins clause is used to combine records from two or more tables in a database. The GROUP
BY statement groups rows that have the same values into summary rows, like “find the number of
customers in each country”.

Q26. What is a Self-Join?


Answer:
A self-join is a type of join that can be used to connect two tables. As a result, it is a unary
relationship. Each row of the table is attached to itself and all other rows of the same table in a
self-join. As a result, a self-join is mostly used to combine and compare rows from the same data-
base table.

Q27. What is concurrency control in DBMS?


Answer:
This is a process of managing simultaneous operations in a database so that database integrity is
not compromised. The following are the two approaches involved in concurrency control:
Optimistic approach – Involves versioning
Pessimistic approach – Involves locking

Q28. What is a checkpoint in DBMS and when does it occur?


Answer:
A checkpoint is a mechanism where all the previous logs are removed from the system and are
permanently stored on the storage disk. So, basically, checkpoints are those points from where the
transaction log record can be used to recover all the committed data up to the point of crash.

Q29. What are Nested Triggers?


Answer:
Triggers may implement DML by using INSERT, UPDATE, and DELETE statements. These triggers that
contain DML and find other triggers for data modification are called Nested Triggers.

Q30. Find the second highest salary from an “Employees” table:


Answer:
SELECT MAX(salary) AS second_highest_salary
FROM Employees
WHERE salary < (SELECT MAX(salary) FROM Employees);

Pg. No.11 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Q31. Display the top 5 customers with the highest total revenue:
Answer:
SELECT customer_id, SUM(total_revenue) AS total_revenue
FROM Orders
GROUP BY customer_id
ORDER BY total_revenue DESC
LIMIT 5;

Q32. List the number of orders placed by each customer in the year 2022:
Answer:
SELECT customer_id, COUNT(order_id) AS num_orders
FROM Orders
WHERE YEAR(order_date) = 2022
GROUP BY customer_id;

Q33. Find the average salary of employees for each department in a “Employees” table:
Answer:
SELECT department_id, AVG(salary) AS avg_salary
FROM Employees
GROUP BY department_id;

Q34. Find the names of all customers who have placed at least one order for more than $1000:
Answer:
SELECT DISTINCT customer_name
FROM Customers
WHERE customer_id IN (SELECT customer_id FROM Orders WHERE total_amount > 1000);

Q35. List the top 3 most popular products (by the number of orders) in the year 2022:
Answer:
SELECT product_id, COUNT(order_id) AS num_orders
FROM Order_Details
WHERE YEAR(order_date) = 2022
GROUP BY product_id
ORDER BY num_orders DESC
LIMIT 3;

2021-2024 Pg. No.12


BRAINALYST - SQL INTERVIEW QUESTIONS

Q36. Find the names of all employees who have worked for more than 5 years:
Answer:
SELECT employee_name
FROM Employees
WHERE DATEDIFF(CURDATE (), hire_date) > 5*365;

Q37. List all orders that have at least one product with a price greater than $100:
Answer:
SELECT *
FROM Orders
WHERE order_id IN (SELECT order_id FROM Order_Details WHERE unit_price > 100);

Q38. Find the number of customers who have not placed any orders in the year 2022:
Answer:
SELECT COUNT(customer_id) AS num_customers
FROM Customers
WHERE customer_id NOT IN (SELECT DISTINCT customer_id FROM Orders WHERE YEAR(order_date)
= 2022);

Q39. Find the average number of orders placed by each customer:


Answer:
SELECT AVG(num_orders) AS avg_orders_per_customer
FROM (SELECT customer_id, COUNT(order_id) AS num_orders
FROM Orders
GROUP BY customer_id) AS order_counts;
Note:
These are indeed valuable tips for optimizing SQL queries, which can significantly increase query
performance and efficiency.
Here is a summary of the optimization process.
Use INNER JOIN instead of subqueries:
• INNER JOIN operations tend to perform better than subqueries, especially for large data sets.
• Subqueries can sometimes be rewritten as JOINs, which can improve readability and performance.
Prefer the WHERE clause to HAVING:
• The WHERE clause filters rows before splitting, making them more efficient than if filtering is DONE
after splitting.
• Use HAVING only when filtering based on aggregate functions or grouped columns.

Pg. No.13 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Select only required characters:


• Instead of using SELECT *, just specify the characters you need in the results.
• This reduces the amount of data generated and transferred and speeds up the execution of the
query.
Limit or TOP for data preview:
• Use LIMIT (for MySQL) or TOP (for SQL Server) when viewing data or retrieving many rows.
• This prevents unnecessary row retrieval and improves query performance, especially for large tables.
Avoid SELECT DISTINCT: CONFIGURATION:
• Although SELECT DISTINCT eliminates duplicate rows, it can be very resource consuming, especially
in large data sets.
• Consider alternatives such as using GROUP BY to achieve the desired result without overloading
DISTINCT.

Q40. How to keep information fine and statistics amount in an evaluation? Here are a few pointers you
can comply with: -
Answer:
Define your studies question: Before you begin gathering records, make certain you’ve got a clear
research question in thoughts. This will help you determine the type and quantity of information
you want to acquire. It may also help you to discover the capability sources of bias which could
affect the first-class of your data.
Use suitable facts collection strategies: Choose appropriate statistics collection methods that are
appropriate to your studies question. For instance, surveys, interviews, and observational research
may be used to gather qualitative records, at the same time as experiments and randomized
controlled trials may be used to accumulate quantitative statistics.
Consider the sample length: When accumulating statistics, it’s crucial to remember the pattern
size. A large pattern length can enhance the statistical strength of your evaluation and increase the
precision of your estimates, but it is able to also boost the threat of amassing low-pleasant data.
A small sample size, on the other hand, may be less consultant of the populace you are studying;
however, it could be easier to gather incredible records.
• Ensure facts quality: To ensure the great of your facts, don’t forget the subsequent factors:
• Validity: The records you gather ought to measure what it is meant to measure.
• Reliability: The records ought to be consistent over the years and throughout distinctive
observers.
• Objectivity: The facts need to be amassed without bias or prejudice.
• Accuracy: The records should be loose from errors and mistakes.
• Use appropriate records analysis strategies: Once you have amassed your information,
use suitable facts analysis strategies to answer your research query. This could include
descriptive statistics, inferential data, or gadget getting to know algorithms

2021-2024 Pg. No.14


BRAINALYST - SQL INTERVIEW QUESTIONS

Q41. Writing SQL queries is simple but efficient writing that will make you appear different in a data
analyst interview.
Answer:
So here are some ways to write an efficient SQL query:-
Use SELECT statements to retrieve only the necessary data.
Use proper indexing to improve query performance.
Use UNION ALL instead of UNION if possible since UNION ALL doesn’t remove duplicates.
Avoid using subqueries, if possible, as they can slow down performance.
Use INNER JOIN instead of OUTER JOIN if you only need to retrieve matching records.
Avoid using wildcard characters at the beginning of LIKE clauses.
Use LIMIT or TOP to retrieve only a specific number of rows.
Use aggregate functions like SUM, AVG, and COUNT to perform calculations on large amounts of
data.
Use GROUP BY to group data and improve query performance.
Use EXISTS instead of IN or NOT IN clauses, as EXISTS is typically faster.
Use a WHERE clause to filter data before retrieving it.
Use CASE statements to perform conditional logic.
Avoid using SELECT * to retrieve all columns when you only need a few columns.
Use stored procedures to reduce network traffic and improve performance.
Use views to simplify complex queries and reduce the amount of code needed.
Use subqueries in the FROM clause instead of in the WHERE clause.
Use table aliases to simplify query code and improve readability
Use UNION instead of UNION ALL if you need to remove duplicates.
Avoid using functions in WHERE clauses, as they can slow down performance.
Use EXPLAIN to analyse query performance and identify bottlenecks.
Avoid using correlated subqueries, if possible, as they can be slow.
Use proper data types to optimize query performance.
Use stored procedures to reduce the number of round trips to the database.
Use temp tables to reduce query complexity and improve performance.

Pg. No.15 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Q42. Find count of duplicate rows in a table:


Answer:
SELECT COUNT(*)
FROM (
SELECT column1, column2, ..., COUNT(*)
FROM table_name
GROUP BY column1, column2, ...
HAVING COUNT(*) > 1
) AS duplicates;

Q43. Remove duplicate rows in a table:


Answer:
DELETE FROM table_name
WHERE ROWID NOT IN (
SELECT MIN(ROWID)
FROM table_name
GROUP BY column1, column2, ...
);

Q44. Find the 2nd highest salary:


Answer:
SELECT DISTINCT Salary
FROM Employees
ORDER BY Salary DESC
LIMIT 1 OFFSET 1;

Q45. Find the Department-wise highest salaries:


Answer:
SELECT Department, MAX(Salary) AS HighestSalary
FROM Employees
GROUP BY Department;

Q46. Difference among DENSE_RANK and RANK:


Answer:
DENSE_RANK: Assigns ranks to rows in a result set, but without any gaps. If rows have the identical
fee, they may be assigned the equal rank, and the following rank is incremented by using 1.
RANK: Assigns ranks to rows in a end result set, however leaves gaps while there are ties. If two rows
have the same cost, they are assigned the identical rank, and the following rank won’t be consecutive.

2021-2024 Pg. No.16


BRAINALYST - SQL INTERVIEW QUESTIONS

Q47. Difference among PARTITION BY and GROUP BY:


Answer:
PARTITION BY: Used with window features to divide the result set into partitions to carry out
calculations within each partition one after the other.
GROUP BY: Used to institution rows which have the equal values into precis rows, commonly with
combination functions like SUM, COUNT, AVG.

Q48. Outputs of Left, Right, and Cross Joins:


Answer:
Left Join: Returns all rows from the left desk and the matched rows from the proper desk. If there are
no healthy, NULL values are back.
Right Join: Returns all rows from the right table and the matched rows from the left desk. If there is
no in shape, NULL values are returned.
Cross Join: Returns the Cartesian made from the two tables, in which every row from the primary
table is mixed with each row from the second one desk.

Q49. Which is faster: Joins, Subqueries, or CTEs?


Answer:
Performance relies upon on different factors inclusive of indexes, facts quantity, and query
complexity. In trendy, joins tend to be quicker than subqueries and CTEs for large datasets, mainly
if appropriate indexes are used. However, it’s crucial to research execution plans and remember
particular use instances to decide the most efficient method.

Q 50. Write sql query to remove duplicate job listings within same company.
Answer:
table name - job_listings

Pg. No.17 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Q51. Write a SQL query to find the second highest salary from the ‘emp’ table. (Columns: id, salary)
Answer:
SELECT MAX(salary) AS second_highest_salary
FROM emp
WHERE salary < (SELECT MAX(salary) FROM emp);

Q52. Write a SQL query to find numbers that consecutively occur 3 times in the ‘id’ column of a table.
(Columns: id, numbers)
Answer:
SELECT DISTINCT a.numbers
FROM table_name a, table_name b, table_name c
WHERE a.numbers = b.numbers AND b.numbers = c.numbers
AND a.id = b.id - 1 AND b.id = c.id - 1;

Q53. Write a SQL query to find the days when the temperature was higher than its previous dates.
(Columns: Days, Temp)
Answer:
SELECT Days, Temp
FROM table_name t1
WHERE Temp > (SELECT Temp FROM table_name t2 WHERE t2.Days = t1.Days - 1);

Q54. Write a SQL query to delete duplicate rows in a table.


Answer:
DELETE FROM table_name
WHERE ROWID NOT IN (SELECT MIN(ROWID) FROM table_name GROUP BY column1, column2, ...);

Q55. Write a SQL query for the cumulative sum of salary for each employee from January to July.
(Columns: Emp_id, Month, Salary)
Answer:
SELECT Emp_id, Month, SUM(Salary) OVER (PARTITION BY Emp_id ORDER BY Month) AS
Cumulative_Salary
FROM salary_table
WHERE Month BETWEEN ‘January’ AND ‘July’;

Q56. Write a SQL query to display year-on-year growth for each product. (Columns: transaction_id,
Product_id, transaction_date, spend, Output: year, product_id, yoy_growth)
Answer:
SELECT EXTRACT(YEAR FROM transaction_date) AS year,
Product_id,
(spend - LAG(spend, 1, 0) OVER (PARTITION BY Product_id ORDER BY transaction_date)) /
LAG(spend, 1, 0) OVER (PARTITION BY Product_id ORDER BY transaction_date) * 100 AS yoy_growth
FROM transactions;

2021-2024 Pg. No.18


BRAINALYST - SQL INTERVIEW QUESTIONS

Q57. Write a SQL query to find the rolling average of posts on a daily basis for each user_id. (Columns:
user_id, date, post_count)
Answer:
SELECT user_id,
date,
ROUND(AVG(post_count) OVER (PARTITION BY user_id ORDER BY date ROWS BETWEEN 2 PRE-
CEDING AND CURRENT ROW), 2) AS rolling_average
FROM posts_table;

Q58. Write a SQL query to get emp id and department for each department, considering employees who
recently joined the organization and are currently working. (Columns: emp id, first name, last name, date
of join, date of exit, department)
Answer:
SELECT e.emp_id, e.first_name, e.last_name, e.date_of_join, e.date_of_exit, d.department
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE e.date_of_join > DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR)
AND e.date_of_exit IS NULL;

Q59. Write a query to get mean, median, and mode for earning? (Columns: Emp_id, salary)
Answer:
SELECT
AVG(salary) AS mean_earning,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_earning,
MODE() WITHIN GROUP (ORDER BY salary) AS mode_earning
FROM earnings_table;
Q60.
1. Second Highest Salary
SQL -

SELECT MAX(salary) AS second_highest_salary


FROM emp
WHERE salary < (SELECT MAX(salary) FROM emp);
python-
second_highest_salary = emp[‘salary’].nlargest(2).iloc[-1]
2. Consecutive Numbers
SQL -
SELECT DISTINCT a.numbers
FROM table_name a, table_name b, table_name c
WHERE a.numbers = b.numbers AND b.numbers = c.numbers
AND a.id = b.id - 1 AND b.id = c.id - 1;

Pg. No.19 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

python-
consecutives = table_name[table_name[‘numbers’].eq(table_name[‘numbers’].shift()) & table_
name[‘numbers’].eq(table_name[‘numbers’].shift(-1))][‘numbers’].unique()

3. Higher Temperature Than Previous Day


SQL -
SELECT Days, Temp
FROM table_name t1
WHERE Temp > (SELECT Temp FROM table_name t2 WHERE t2.Days = t1.Days - 1);
python-
higher_temp = table_name[table_name[‘Temp’] > table_name[‘Temp’].shift(1)]

4. Cumulative Sum of Salary (Jan to July)


SQL -
SELECT Emp_id, Month, SUM(Salary) OVER (PARTITION BY Emp_id ORDER BY Month) AS
Cumulative_Salary
FROM salary_table
WHERE Month BETWEEN ‘January’ AND ‘July’;
python-
salary_table[‘Cumulative_Salary’] = salary_table[salary_table[‘Month’].isin([‘January’,
‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’])].groupby(‘Emp_id’)[‘Salary’].cumsum()

5. Year-on-Year Growth for Each Product

SQL -
SELECT EXTRACT(YEAR FROM transaction_date) AS year,
Product_id,
(spend - LAG(spend, 1, 0) OVER (PARTITION BY Product_id ORDER BY transaction_date)) /
LAG(spend, 1, 0) OVER (PARTITION BY Product_id ORDER BY transaction_date) * 100 AS yoy_
growth
FROM transactions;
python-
transactions[‘year’] = transactions[‘transaction_date’].dt.year
transactions[‘lag_spend’] = transactions.groupby(‘Product_id’)[‘spend’].shift(1)
transactions[‘yoy_growth’] = (transactions[‘spend’] - transactions[‘lag_spend’]) /
transactions[‘lag_spend’] * 100

2021-2024 Pg. No.20


BRAINALYST - SQL INTERVIEW QUESTIONS

6. Rolling Average of Posts for Each User


SQL -
SELECT user_id,
date,
ROUND(AVG(post_count) OVER (PARTITION BY user_id ORDER BY date ROWS BETWEEN 2
PRECEDING AND CURRENT ROW), 2) AS rolling_average
FROM posts_table;
python-
posts_table[‘rolling_average’] = posts_table.groupby(‘user_id’)[‘post_count’].rolling(window=3,
min_periods=1).mean().reset_index(level=0, drop=True)
7. Emp ID and Department for Recently Joined Employees
SQL -
SELECT e.emp_id, e.first_name, e.last_name, e.date_of_join, e.date_of_exit, d.department
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE e.date_of_join > DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR)
AND e.date_of_exit IS NULL;
python-
recent_joins = employees.merge(departments, left_on=’department_id’, right_on=
’department_id’)
recent_joins = recent_joins[(recent_joins[‘date_of_join’] > pd.Timestamp(‘now’) - pd.Date
Offset(years=1)) & (recent_joins[‘date_of_exit’].isna())]

-----------------------------------------------------------------------------------------------------------------------------------

Practical Questions:
1. Combine Two Tables
Write a SQL query for a report that provides the following information for each person in the Person
table, regardless of if there is an address for each of those people: FirstName, LastName, City, State

Pg. No.21 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

# Write your MySQL query statement below


select FirstName, LastName, City, State from Person as p left join Address as a on p.PersonId =
a.PersonId
-----------------------------------------------------------------------------------------------------------------------------------

2. Second Highest Salary


Write a SQL query to get the second highest salary from the Employee table.

For example, given the above Employee table, the query should return 200 as the second highest
salary. If there is no second highest salary, then the query should return null.

# Write your MySQL query statement below


select ifnull(( select distinct Salary from Employee order by Salary desc limit 1 offset 1), null) as
SecondHighestSalary;

2021-2024 Pg. No.22


BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------------

3. Nth Highest Salary


Write a SQL query to get the nth highest salary from the Employee table.

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth
highest salary, then the query should return null.

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT


BEGIN
declare M INT;
set M = N - 1;
RETURN (
# Write your MySQL query statement below.
select distinct Salary
from Employee
order by Salary desc
limit 1 offset M );
END
-----------------------------------------------------------------------------------------------------------------------------------------------

4. Write a SQL query to rank scores. If there is a tie between two scores, both should have the same
ranking. Note that after a tie, the next ranking number should be the next consecutive integer value.
In other words, there should be no “holes” between ranks.

For example, given the above Scores table, your query should generate the following report (order
by highest score):

Pg. No.23 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

/* Write your T-SQL query statement below */


select Score,
dense_rank() over(order by Score desc) as Rank from Scores;
# Write your MySQL query statement below
select Score, (select count(distinct Score)
from Scores
where Score >= s.Score) as Rank from Scores as s
order by Score desc;
------------------------------------------------------------------------------------------------------------------------------

5. Write a SQL query to find all numbers that appear at least three times consecutively.

SELECT Num
FROM (
SELECT Num,
ROW_NUMBER() OVER (ORDER BY Id) AS rn,
ROW_NUMBER() OVER (PARTITION BY Num ORDER BY Id) AS rn_id
FROM your_table_name
) AS subquery
GROUP BY Num, (rn - rn_id)
HAVING COUNT(*) >= 3;

2021-2024 Pg. No.24


BRAINALYST - SQL INTERVIEW QUESTIONS

6. The Employee table holds all employees including their managers. Every employee has an Id, and there
is also a column for the manager Id.

Given the Employee table, write a SQL query that finds out employees who earn more than their
managers. For the above table, Joe is the only employee who earns more than his manager.

# Write your MySQL query statement below


select e.Name as Employee
from Employee as e
inner join Employee as m
on e.ManagerId = m.id
where e.Salary > m.Salary;
------------------------------------------------------------------------------------------------------------------------------
7. Write a SQL query to find all duplicate emails in a table named Person.

# Write your MySQL query statement below


select Email from Person
group by Email
having count(Email) > 1;

Pg. No.25 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------
8. Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL
query to find all customers who never order anything.

# Write your MySQL query statement below


select Name as Customers
from Customers
where Id not in ( select CustomerId from Orders );
-----------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.26


BRAINALYST - SQL INTERVIEW QUESTIONS

9. Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique
emails based on its smallest Id.

# Write your MySQL query statement below


delete p.* from Person as p,
( select Email, min(Id) as minId from Person
group by Email
having count(*) > 1 ) as q
where p.Email = q.Email and Id > q.minId;
# Write your MySQL query statement below
delete p1 from Person as p1, Person as p2
where p1.Email = p2.Email and p1.Id > p2.Id;
-----------------------------------------------------------------------------------------------------------------------------------
10. Given a Weather table, write a SQL query to find all dates’ Ids with higher temperature compared to
its previous (yesterday’s) dates.

# Write your MySQL query statement below


select w1.Id from Weather as w1,
Weather as w2
where datediff(w1.RecordDate, w2.RecordDate) = 1
and w1.Temperature > w2.Temperature;
Pg. No.27 2021-2024
BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------
11. Game Play Analysis I

# Write your MySQL query statement below


select player_id, min(event_date) as first_login
from Activity
group by player_id
order by player_id;

-----------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.28


BRAINALYST - SQL INTERVIEW QUESTIONS

12. Game Play Analysis II

# Write your MySQL query statement below


select player_id, device_id from Activity
where (player_id, event_date) in ( select player_id, min(event_date)
from Activity
group by player_id );
-----------------------------------------------------------------------------------------------------------------------------------

Pg. No.29 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

13. Game Play Analysis III

SELECT player_id,
event_date,
SUM(games_played) OVER (PARTITION BY player_id ORDER BY event_date) AS games_played_so_far
FROM Activity
ORDER BY player_id, event_date;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.30


BRAINALYST - SQL INTERVIEW QUESTIONS

14. Managers with at Least 5 Direct Reports

# Write your MySQL query statement below


select Name from Employee
where Id in ( select ManagerId from Employee
group by ManagerId
having count(*) >= 5 );
-----------------------------------------------------------------------------------------------------------------------------------

Pg. No.31 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

15. Employee Bonus

# Write your MySQL query statement below


select name, bonus from Employee as e
left join Bonus as b
on e.empId = b.empId
where bonus < 1000 or bonus is null;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.32


BRAINALYST - SQL INTERVIEW QUESTIONS

16. Find Customer Referee

# Write your MySQL query statement below


select name from customer
where referee_id is null or referee_id <> 2;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.33 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

17. Customer Placing the Largest Number of Orders

# Write your MySQL query statement below


select customer_number from (select customer_number, count (*) as cnt
from orders group by customer_number ) as e
order by e.cnt desc limit 1;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.34


BRAINALYST - SQL INTERVIEW QUESTIONS

18. Big Countries

# Write your MySQL query statement below


select name, population, area from World
where area >= 3000000 or population >= 25000000;
-----------------------------------------------------------------------------------------------------------------------------------------------

19. Classes More Than 5 Students

Pg. No.35 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

# Write your MySQL query statement below


select class from courses
group by class
having count(distinct student) >= 5;
-----------------------------------------------------------------------------------------------------------------------------------------------
20. Friend Requests I: Overall Acceptance Rate

# Write your MySQL query statement below


select round(if(requests = 0, 0, accepts / requests), 2) as accept_rate
from
( select count(distinct sender_id, send_to_id) as requests from friend_request ) as r,
( select count(distinct requester_id, accepter_id) as accepts
from request_accepted ) as a;

2021-2024 Pg. No.36


BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------------------

21. Consecutive Available Seats

# Write your MySQL query statement below


select distinct c1.seat_id
from cinema as c1
join cinema as c2 join cinema as c3
on c1.seat_id = c2.seat_id + 1 || c1.seat_id = c3.seat_id - 1 where c1.free = 1 and c2.free = 1 and
c3.free = 1;

# Write your MySQL query statement below


select distinct c2.seat_id
from cinema as c1, cinema as c2
where c1.free = 1 and c2.free = 1 and c1.seat_id = c2.seat_id + 1
union
select distinct c1.seat_id from cinema as c1, cinema as c2
where c1.free = 1 and c2.free = 1 and c1.seat_id = c2.seat_id + 1
order by seat_id;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.37 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

22. Salesperson

# Write your MySQL query statement below


select s.name from salesperson as s
where s.sales_id not in( select sales_id from orders as o left join company as c on o.com_id =
c.com_id where c.name = ‘RED’)
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.38


BRAINALYST - SQL INTERVIEW QUESTIONS

23. Tree Node

# Write your MySQL query statement below


select id,
case
when p_id is null then ‘Root’
when p_id is not null and id in (select distinct p_id from tree) then ‘Inner’
else ‘Leaf’ end as Type from tree;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.39 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

24. Triangle Judgement

# Write your MySQL query statement below


select x, y, z,
case when x + y > z and x + z > y and y + z > x then ‘Yes’ else ‘No’ end as triangle
from triangle ;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.40


BRAINALYST - SQL INTERVIEW QUESTIONS

25. Shortest Distance in a Plane

# Write your MySQL query statement below


select round(min(dist), 2) as shortest
from ( select if(a.x = b.x and a.y = b.y, 10000, sqrt(power(a.x - b.x, 2) + power(a.y - b.y, 2))) as dist
from point_2d as a, point_2d as b ) as d;
-----------------------------------------------------------------------------------------------------------------------------------------------

26. Shortest Distance in a Line

Pg. No.41 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Write your MySQL query statement below


select min(abs(a.x - b.x)) as shortest
from point as a, point as b
where a.x != b.x;
-----------------------------------------------------------------------------------------------------------------------------------------------

27. Biggest Single Number

# Write your MySQL query statement below


select max(num) as num
from ( select num from my_numbers
group by num
having count(num) = 1 ) as n;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.42


BRAINALYST - SQL INTERVIEW QUESTIONS

28. Not Boring Movies

# Write your MySQL query statement below


select id, movie, description,
rating from cinema where id % 2 = 1 and description <> ‘boring’
order by rating desc;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.43 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

29. Exchange Seats

# Write your MySQL query statement below


select if (mod (id, 2) = 0, id - 1,
if (id < (select max(id) from seat), id + 1, id)) as id, student
from seat
order by id;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.44


BRAINALYST - SQL INTERVIEW QUESTIONS

30. Swap Salary

# Write your MySQL query statement below


# update salary
# set sex = case when sex = ‘m’ then ‘f’ else ‘m’ end;
update salary set sex = if(sex = ‘m’, ‘f’, ‘m’);
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.45 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

31. Customers Who Bought All Products

# Write your MySQL query statement below


select customer_id from Customer
group by customer_id
having sum(distinct product_key) = ( select sum(product_key) from Product );
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.46


BRAINALYST - SQL INTERVIEW QUESTIONS

32. Actors and Directors Who Cooperated At Least Three Times

# Write your MySQL query statement below


# select actor_id, director_id
# from (
# select actor_id, director_id, count(*) as cnt
# from ActorDirector
# group by actor_id, director_id
# having cnt >= 3) as e;

select actor_id, director_id from ActorDirector group by actor_id, director_id having count(*) >= 3;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.47 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

33. Product Sales Analysis I

# Write your MySQL query statement below


select distinct P.product_name, S.year, S.price
from (select distinct product_id, year, price from Sales) S
inner join Product as P
using (product_id);

2021-2024 Pg. No.48


BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------------------

34. Product Sales Analysis II

# Write your MySQL query statement below


select product_id, sum(quantity) as total_quantity
from Sales
group by product_id;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.49 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

35. Product Sales Analysis III

select product_id, year as first_year, quantity, price


from Sales
where (product_id, year)
in (select product_id, min(year) as year
from Sales
group by product_id);

2021-2024 Pg. No.50


BRAINALYST - SQL INTERVIEW QUESTIONS
-----------------------------------------------------------------------------------------------------------------------------------------------

36. Project Employees I

# Write your MySQL query statement below


select project_id, round(avg(experience_years), 2) as average_years
from Project as p
left join Employee as e
on p.employee_id = e.employee_id
group by project_id;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.51 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

37. Project Employees II

# Write your MySQL query statement below


select project_id from Project
group by project_id
having count(employee_id) >= ( select count(employee_id) as cnt from Project
group by project_id
order by cnt desc limit 1);
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.52


BRAINALYST - SQL INTERVIEW QUESTIONS

38. Project Employees III

# Write your MySQL query statement below


select project_id, round(avg(experience_years), 2) as average_years
from Project as p
left join Employee as e
on p.employee_id = e.employee_id
group by project_id;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.53 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

39. Project Employees II

# Write your MySQL query statement below


select project_id from Project
group by project_id
having count(employee_id) >= ( select count(employee_id) as cnt
from Project group by project_id
order by cnt desc limit 1 );
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.54


BRAINALYST - SQL INTERVIEW QUESTIONS

40. Project Employees III

# Write your MySQL query statement below


select p.project_id, e.employee_id from (
select project_id, max(experience_years) as max_years from Project as p
join Employee as e on p.employee_id = e.employee_id group by project_id ) as q, Project as p,
Employee as e
where p.project_id = q.project_id and p.employee_id = e.employee_id and e.experience_years >=
max_years;

# Write your MySQL query statement below


select p.project_id, e.employee_id from Project as p, Employee as e
where p.employee_id = e.employee_id and (p.project_id, e.experience_years) in ( select
project_id, max(experience_years) as experience_years from Project as p join Employee as e on
p.employee_id = e.employee_id group by project_id )
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.55 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

41. Sales Analysis I

# Write your MySQL query statement below


select seller_id from Sales
group by seller_id having sum(price) >= ( select sum(price) as total_price from Sales
group by seller_id
order by total_price desc limit 1);

2021-2024 Pg. No.56


BRAINALYST - SQL INTERVIEW QUESTIONS

# select seller_id
# from Sales
# group by seller_id
# having sum(price) >= all(
# select sum(price)
# from Sales
# group by seller_id # );
-----------------------------------------------------------------------------------------------------------------------------------------------

42. Sales Analysis II

Pg. No.57 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

# Write your MySQL query statement below


select distinct s.buyer_id from Sales as s
join Product as p on s.product_id = p.product_id
where product_name = ‘S8’ and s.buyer_id not
in ( select buyer_id from Sales as s join Product as p
on s.product_id = p.product_id where product_name = ‘iPhone’ );

# Write your MySQL query statement below


select buyer_id from Sales
join Product using(product_id)
group by buyer_id
having sum(product_name = ‘S8’) > 0 and sum(product_name = ‘iPhone’) = 0;
-----------------------------------------------------------------------------------------------------------------------------------------------

43. Sales Analysis III

2021-2024 Pg. No.58


BRAINALYST - SQL INTERVIEW QUESTIONS

select product_id, product_name


from Sales
inner join product using(product_id)
group by product_id
having sum(if(sale_date between ‘2019-01-01’ and ‘2019-03-31’, 1, 0)) = sum(if(sale_date, 1, 0));
-----------------------------------------------------------------------------------------------------------------------------------------------

44. Highest Grade for Each Student

# Write your MySQL query statement below


select student_id, min(course_id) as course_id, grade
from Enrollments
where (student_id, grade) in ( select student_id, max(grade)

Pg. No.59 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

from Enrollments group by student_id )


group by student_id
order by student_id asc;
-----------------------------------------------------------------------------------------------------------------------------------------------

45. Reported Posts

# Write your MySQL query statement below


select extra as report_reason, count(*) as report_count
from ( select post_id, extra from Actions
where action_date = ‘2019-07-04’ and action = ‘report’
group by post_id, extra) as t
group by t.extra;

# Write your MySQL query statement below


select extra as report_reason, count(distinct post_id) as report_count
from Actions
where action_date = ‘2019-07-04’ and action = ‘report’ group by extra;

2021-2024 Pg. No.60


BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------------------

46. Active Businesses

# Write your MySQL query statement below


select business_id from Events e, ( select event_type, avg(occurences) as avg_occurences from
Events
group by event_type ) as a
where e.event_type = a.event_type and e.occurences > a.avg_occurences
group by e.business_id
having count(*) > 1;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.61 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

47. User Activity for the Past 30 Days I

# Write your MySQL query statement below


select activity_date as day, count(distinct user_id) as active_users
from Activity
where activity_date between ‘2019-06-28’ and ‘2019-07-27’
group by day;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.62


BRAINALYST - SQL INTERVIEW QUESTIONS

48. User Activity for the Past 30 Days II

# Write your MySQL query statement below


select round(ifnull(sum(sessions) / count(user_id), 0), 2) as average_sessions_per_user
from ( select distinct user_id, count(distinct session_id) as sessions
from Activity where activity_date between ‘2019-06-28’ and ‘2019-07-27’
group by user_id
having count(*) >= 1 ) as u;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.63 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

49. Article Views I

# Write your MySQL query statement below


select distinct author_id as id
from Views
where author_id = viewer_id
order by author_id;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.64


BRAINALYST - SQL INTERVIEW QUESTIONS

50. Product Price at a Given Date

select i.product_id, max(if(i.product_id not in (select product_id


from Products
where change_date <= date ‘2019-08-16’
group by product_id), 10, (select new_price from Products where product_id = i.product_id and
product_id = q.product_id and change_date = q.max_change_date))) as price
from (select distinct product_id from Products) as i, ( select product_id, max(change_date) as
max_change_date
from Products where change_date <= date ‘2019-08-16’
group by product_id ) as q
group by i.product_id;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.65 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

51. Immediate Food Delivery I

# Write your MySQL query statement below


# select round(
# (select count(*) from Delivery where order_date = customer_pref_delivery_date) /
# (select count(*) from Delivery) * 100,
# 2) as immediate_percentage;

select round( sum(case when order_date = customer_pref_delivery_date then 1 else 0 end) /


count(delivery_id) * 100 , 2) as immediate_percentage from Delivery;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.66


BRAINALYST - SQL INTERVIEW QUESTIONS

52. Immediate Food Delivery II

# Write your MySQL query statement below


select round(sum(if(order_date = customer_pref_delivery_date, 1, 0)) / count(*) * 100, 2) as
immediate_percentage from Delivery where (customer_id, order_date) in ( select customer_id,
min(order_date) from Delivery group by customer_id )
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.67 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

53. Reformat Department Table

# Write your MySQL query statement below


# select
# id,
# sum(case when month = ‘Jan’ then revenue else null end) as Jan_Revenue,
# sum(case when month = ‘Feb’ then revenue else null end) as Feb_Revenue,
# sum(case when month = ‘Mar’ then revenue else null end) as Mar_Revenue,
# sum(case when month = ‘Apr’ then revenue else null end) as Apr_Revenue,
# sum(case when month = ‘May’ then revenue else null end) as May_Revenue,
# sum(case when month = ‘Jun’ then revenue else null end) as Jun_Revenue,
# sum(case when month = ‘Jul’ then revenue else null end) as Jul_Revenue,
# sum(case when month = ‘Aug’ then revenue else null end) as Aug_Revenue,
# sum(case when month = ‘Sep’ then revenue else null end) as Sep_Revenue,
# sum(case when month = ‘Oct’ then revenue else null end) as Oct_Revenue,

2021-2024 Pg. No.68


BRAINALYST - SQL INTERVIEW QUESTIONS

# sum(case when month = ‘Nov’ then revenue else null end) as Nov_Revenue,
# sum(case when month = ‘Dec’ then revenue else null end) as Dec_Revenue
# from Department # group by id;

select id, sum(if(month = ‘Jan’, revenue, null)) as Jan_Revenue, sum(if(month = ‘Feb’, revenue,
null)) as Feb_Revenue, sum(if(month = ‘Mar’, revenue, null)) as Mar_Revenue, sum(if(month =
‘Apr’, revenue, null)) as Apr_Revenue, sum(if(month = ‘May’, revenue, null)) as May_Revenue,
sum(if(month = ‘Jun’, revenue, null)) as Jun_Revenue, sum(if(month = ‘Jul’, revenue, null)) as
Jul_Revenue, sum(if(month = ‘Aug’, revenue, null)) as Aug_Revenue, sum(if(month = ‘Sep’, reve-
nue, null)) as Sep_Revenue, sum(if(month = ‘Oct’, revenue, null)) as Oct_Revenue, sum(if(month
= ‘Nov’, revenue, null)) as Nov_Revenue, sum(if(month = ‘Dec’, revenue, null)) as Dec_Revenue
from Department group by id;
-----------------------------------------------------------------------------------------------------------------------------------------------

54. Monthly Transactions I

Pg. No.69 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

# Write your MySQL query statement below


select date_format(trans_date, ‘%Y-%m’) as month, country, count(*) as trans_count, sum(if(state=
’approved’, 1, 0)) as approved_count, sum(amount) as trans_total_amount, sum(if(state=’approved’,
amount, 0)) as approved_total_amount from Transactions group by date_format(trans_date, ‘%Y-
%m’), country;
-----------------------------------------------------------------------------------------------------------------------------------------------

55. Last Person to Fit in the Elevator

# Write your MySQL query statement below


select person_name from ( select person_name, @total_weight := @total_weight + weight as to-
tal_weight from 1211. Queries Quality and Percentage Description Queue, (select @total_weight
:= 0) as tmp order by turn ) as t where total_weight <= 1000 order by total_weight desc limit 1;
# Write your MySQL query statement below
select q1.person_name from Queue as q1 join Queue as q2 on q1.turn >= q2.turn group by
q1.turn having sum(q2.weight) <= 1000 order by sum(q2.weight) desc limit 1;

2021-2024 Pg. No.70


BRAINALYST - SQL INTERVIEW QUESTIONS
-----------------------------------------------------------------------------------------------------------------------------------------------

56. Queries Quality and Percentage

# Write your MySQL query statement below


select q.query_name, round(ifnull(avg(rating / position), 0), 2) as quality, round(ifnull(cnt /
count(q.rating) * 100, 0), 2) as poor_query_percentage from Queries as q left join ( select que-
ry_name, count(*) as cnt from Queries where rating < 3 group by query_name ) as p on q.que-
ry_name = p.query_name group by q.query_name;
# Write your MySQL query statement below
select query_name, round(avg(rating / position), 2) as quality, round(avg(if(rating < 3, 1, 0)) * 100,
2) as poor_query_percentage from Queries group by query_name;

Pg. No.71 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------------------

57. Team Scores in Football Tournament

# Write your MySQL query statement below


select t.team_id, team_name, ifnull(num_points, 0) as num_points from Teams as t left join ( select
team_id, sum(num_points) as num_points from ( select host_team as team_id, sum(case when
host_goals > guest_goals then 3 when host_goals = guest_goals then 1 else 0 end) as num_points
from Matches group by host_team union all select guest_team as team_id, sum(case when host_
goals < guest_goals then 3 when host_goals = guest_goals then 1 else 0 end) as num_points from

2021-2024 Pg. No.72


BRAINALYST - SQL INTERVIEW QUESTIONS

Matches group by guest_team ) as u group by team_id ) as r on t.team_id = r.team_id order by


num_points desc, team_id asc;

# Write your MySQL query statement below


select team_id, team_name, sum(if(team_id = host_team,
case when host_goals > guest_goals then 3 when host_goals = guest_goals then 1 else 0 end, 0))
+ sum(if(team_id = guest_team, case when host_goals < guest_goals then 3 when host_goals =
guest_goals then 1 else 0 end, 0)) as num_points from Teams as t, Matches as m group by team_id
order by num_points desc, team_id asc;
-----------------------------------------------------------------------------------------------------------------------------------------------

58. Report Contiguous Dates

Pg. No.73 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

# Write your MySQL query statement below


select period_state, start_date, end_date from (
select ‘failed’ as period_state, f1.fail_date as start_date, f2.fail_date as end_date
from
( select fail_date from Failed where fail_date between ‘2019-01-01’ and ‘2019-12-31’ and date_
sub(fail_date, interval 1 day) not in (select * from Failed where fail_date between ‘2019-01-01’ and
‘2019-12-31’) ) as f1,
( select fail_date from Failed where fail_date between ‘2019-01-01’ and ‘2019-12-31’ and date_ad-
d(fail_date, interval 1 day) not in
(select * from Failed where fail_date between ‘2019-01-01’ and ‘2019-12-31’) ) as f2 where f1.fail_
date <= f2.fail_date group by f1.fail_date union select ‘succeeded’ as period_state, s1.success_date
as start_date, s2.success_date as end_date from
( select success_date from Succeeded where success_date between ‘2019-01-01’ and ‘2019-12-31’
and date_sub(success_date, interval 1 day) not in
(select * from Succeeded where success_date between ‘2019-01-01’ and ‘2019-12-31’) ) as s1,
( select success_date from Succeeded where success_date between ‘2019-01-01’ and ‘2019-12-31’
and date_add(success_date, interval 1 day) not in
(select * from Succeeded where success_date between ‘2019-01-01’ and ‘2019-12-31’) ) as s2
where s1.success_date <= s2.success_date group by s1.success_date ) as p
order by start_date;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.74


BRAINALYST - SQL INTERVIEW QUESTIONS

59. Number of Comments per Post

# Write your MySQL query statement below


# select post_id, ifnull(number_of_comments, 0) as number_of_comments # from (
# select distinct sub_id as post_id
# from Submissions
# where parent_id is null
# ) as s1
# left join
#(
# select parent_id, count(*) as number_of_comments
# from (
# select distinct sub_id, parent_id

Pg. No.75 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

# from Submissions
# ) as ds
# where parent_id is not null
# group by parent_id
# ) as s2
# on s1.post_id = s2.parent_id
# order by post_id;

select t.post_id, count(distinct s.sub_id) as number_of_comments from ( select distinct sub_id as


post_id from Submissions where parent_id is null ) as t left join
Submissions as s on t.post_id = s.parent_id group by t.post_id order by t.post_id;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.76


BRAINALYST - SQL INTERVIEW QUESTIONS

60. Average Selling Price

# Write your MySQL query statement below


select distinct p.product_id, round(sum(price * units) / sum(units), 2) as average_price from Prices
as p join UnitsSold as u on p.product_id = u.product_id and u.purchase_date between p.start_date
and p.end_date group by p.product_id order by p.product_id;

Pg. No.77 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------------------

61. Page Recommendations

# Write your MySQL query statement below


select distinct page_id as recommended_page from Likes as l left join Friendship as f on f.user2_id
= l.user_id where f.user1_id = 1 and page_id not in ( select page_id from Likes where user_id = 1
) union select distinct page_id as recommended_page from Likes as l left join Friendship as f on
f.user1_id = l.user_id where f.user2_id = 1 and page_id not in ( select page_id from Likes where
user_id = 1 );
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.78


BRAINALYST - SQL INTERVIEW QUESTIONS

62. All People Report to the Given Manager

# Write your MySQL query statement below


select distinct e1.employee_id from Employees as e1 inner join Employees as e2 inner join
Employees as e3 on e1.manager_id = e2.employee_id and e2.manager_id = e3.employee_id
where e1.employee_id <> 1 and (e1.manager_id = 1 or e2.manager_id = 1 or e3.manager_id = 1);
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.79 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

63. Students and Examinations

2021-2024 Pg. No.80


BRAINALYST - SQL INTERVIEW QUESTIONS

# Write your MySQL query statement below


select s.student_id, s.student_name, u.subject_name, count(e.subject_name) as attended_exams
from Students as s join Subjects as u left join Examinations as e on s.student_id = e.student_id and
u.subject_name = e.subject_name group by s.student_id, u.subject_name order by s.student_id,
u.subject_name;
-----------------------------------------------------------------------------------------------------------------------------------------------

64. Find the Start and End Number of Continuous Ranges

# Write your MySQL query statement below


select l1.log_id as start_id, l2.log_id as end_id from ( select log_id from Logs where log_id - 1 not
in (select * from Logs) ) as l1, ( select log_id from Logs where log_id + 1 not in (select * from Logs) )
as l2 where l1.log_id <= l2.log_id group by l1.log_id;

# Write your MySQL query statement below


select min(log_id) as start_id, max(log_id) as end_id from( select *, (@id:=@id+1) as id from logs,
(select @id:= 0) as init ) tmp group by log_id - id
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.81 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

65. Weather Type in Each Country

# Write your MySQL query statement below


select country_name, case when avg(weather_state) <= 15 then ‘Cold’ when avg(weather_state)
>= 25 then ‘Hot’ else ‘Warm’ end as weather_type from Weather as w left join Countries as c
on c.country_id = w.country_id where day between ‘2019-11-01’ and ‘2019-11-30’ group by
w.country_id;

2021-2024 Pg. No.82


BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------------------

66. Find the Team Size

# Write your MySQL query statement below


select employee_id, team_size from Employee as e join (select team_id, count(*) as team_size
from employee group by team_id) as t on e.team_id = t.team_id;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.83 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

67. Running Total for Different Genders

/* Write your T-SQL query statement below


*/ select gender, day, sum(score_points) over(partition by gender order by day) as total from
Scores order by gender, day;
# Write your MySQL query statement below
select s1.gender, s1.day, sum(s2.score_points) as total from Scores as s1 join Scores as s2 on s1.
gender = s2.gender and s1.day >= s2.day group by s1.gender, s1.day order by gender, day;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.84


BRAINALYST - SQL INTERVIEW QUESTIONS

68. Restaurant Growth

# Write your MySQL query statement below


select visited_on, amount, average_amount from ( select visited_on, @cnt := @cnt + 1 as cnt, @
d7 := @d6, @d6 := @d5, @d5 := @d4, @d4 := @d3, @d3 := @d2, @d2 := @d1, @d1 := amount, @
total := @d1 + @d2 + @d3 + @d4 + @d5 + @d6 + @d7 as amount, round(@total / 7, 2) as aver-
age_amount from ( select visited_on, sum(amount) as amount from Customer group by visited_on
) as c, ( select @cnt := 0, @total := 0, @d1 := 0, @d2 := 0, @d3 := 0, @d4 := 0, @d5 := 0, @d6 := 0,
@d7 := 0 ) as t ) as s where cnt >= 7;

Pg. No.85 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

-----------------------------------------------------------------------------------------------------------------------------------------------

69. Ads Performance

# Write your MySQL query statement below


select ad_id, round(if(clicks + views = 0, 0, clicks / (clicks + views) * 100), 2) as ctr from ( select ad_
id, sum(if(action=’Clicked’, 1, 0)) as clicks, sum(if(action=’Viewed’, 1, 0)) as views from Ads group by
ad_id ) as a order by ctr desc, ad_id asc;
-----------------------------------------------------------------------------------------------------------------------------------------------

2021-2024 Pg. No.86


BRAINALYST - SQL INTERVIEW QUESTIONS

70. List the Products Ordered in a Period

# Write your MySQL query statement below


select product_name, sum(unit) as unit from Orders as o left join Products as p on o.product_id = p.prod-
uct_id where order_date between ‘2020-02-01’ and ‘2020-02-29’ group by o.product_id having sum(unit)
>= 100;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.87 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

71. Number of Transactions per Visit

2021-2024 Pg. No.88


BRAINALYST - SQL INTERVIEW QUESTIONS

# Write your MySQL query statement below


select (select 0) as transactions_count, count(*) as visits_count from Visits where (user_id, vis-
it_date) not in ( select user_id, transaction_date from Transactions ) union select s.transactions_
count, if(visits_count is null, 0, visits_count) as visits_count from ( select tc as transactions_count
from ( select t.user_id, @tc := @tc + 1 as tc from Transactions as t, (select @tc := 0) as u ) as s where
tc <= ( select ifnull(max(transactions_count), 0) from ( select count(*) as transactions_count from
Transactions group by user_id, transaction_date ) as t ) ) as s left join ( select transactions_count,
count(*) as visits_count from ( select count(*) as transactions_count from Transactions group by
user_id, transaction_date ) as t group by transactions_count ) as t on s.transactions_count = t.trans-
actions_count order by transactions_count;
-----------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.89 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

𝐓𝐨𝐩 𝐒𝐐𝐋 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧𝐬 𝐘𝐨𝐮 𝐌𝐮𝐬𝐭 𝐏𝐫𝐞𝐩𝐚𝐫𝐞 𝐈𝐧 𝟐𝟎𝟐𝟒 💡


(Try it yourself)
Part1:
1. What is the difference between SQL and MySQL?
2. What are the different subsets of SQL?
3. What do you mean by DBMS? What are its different types?
4. What do you mean by table and field in SQL?
5. What are joins in SQL?
6. What is the difference between CHAR and VARCHAR2 datatype in SQL?
7. What is the Primary key?
8. What are Constraints?
9. What is the difference between DELETE and TRUNCATE statements?
10. What is a Unique key?
11. What is the SELECT statement?
12. What are UNION, MINUS and INTERSECT commands?
13. What is Cursor? How to use a Cursor?
14. What are SQL comments?
15. What is the usage of the NVL() function?
16. Explain character-manipulation functions? Explains its different types in SQL.
17. Write the SQL query to get the third maximum salary of an employee from a table named employees
18. What is the difference between the RANK() and DENSE_RANK() functions?
19. What are Tables and Fields?
20. What is a UNIQUE constraint?
21. What is a Self-Join?
22. List the different types of relationships in SQL.
23. How to create a temp table in SQL Server?
24. What is the case when in SQL Server?
25. What is the difference between NOW() and CURRENT_DATE()?
26. What is BLOB and TEXT in MySQL?
27. How to remove duplicate rows in SQL?

2021-2024 Pg. No.90


BRAINALYST - SQL INTERVIEW QUESTIONS

28. How to create a stored procedure using SQL Server?


29. How to find the nth highest salary in SQL
30. What are joins in SQL?
31. What is a Foreign key in SQL?
32. What do you mean by data integrity?
33. What is the difference between clustered and non-clustered index in SQL?
34. Write a SQL query to display the current date?
35. What do you understand by query optimization?
36. What is an Index?
37. Explain different types of index in SQL.
38. What is Normalization and what are the advantages of it?
39. What is the difference between DROP and TRUNCATE commands?
40. What is SQL Injection?
41. How many Aggregate functions are available in SQL?
42. What is the default data ordering using the ORDER BY clause? How could it be changed?
43. How do we use the DISTINCT statement? What is its use?
44. What are the syntax and use of the COALESCE function?
45. What is the ACID property in a database?
46. what do you mean by “Trigger” in SQL?
47. What are the different operators available in SQL?
48. Are NULL values the same as that of zero or a blank space?
49. What is the difference between cross-join and natural join?
50. What is subquery in SQL?
51. What are the different types of a subquery?

Pg. No.91 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Part 2:

1. What is a foreign key in SQL?


2. What do you mean by data integrity?
3. What is the difference between clustered and non-clustered index in SQL?
4. Write a SQL query to display the current date?
5. What do you understand by query optimization?
6. What is an Index?
7. What are the different types of SQL joins and when would you use each one?
8. What is the difference between INNER JOIN and OUTER JOIN in SQL?
9. Explain the concept of normalization in database design and why it’s important.
10. What is a primary key and why is it used in a database?
11. Explain the difference between UNION and UNION ALL in SQL.
12. How do you create a new table in SQL? Provide an example.
13. What is a subquery in SQL and how can it be used in a query?
14. Explain the concept of indexing in databases and how it can improve query performance.
15. How do you retrieve the top N records from a table in SQL?
16. What are stored procedures and functions in SQL, and how do they differ?
17. Explain the difference between VARCHAR and CHAR data types in SQL.
18. How do you calculate the average, sum, minimum, and maximum values of a column in SQL?
19. What is a foreign key and how is it used in a database?
20. Explain the concept of ACID properties in the context of database transactions.
21. What is the purpose of the GROUP BY clause in SQL and how does it work?
22. How do you add, modify, and delete data in a table using SQL?
23. Explain the concept of NULL in SQL and how it’s handled in queries.
24. What is a view in SQL and why would you use it?
25. How do you retrieve data from multiple tables using JOINs in SQL?
26. Explain the difference between a clustered and a non-clustered index in SQL.
27. What are triggers in SQL and how do they work?
28. How do you handle duplicate records in a table using SQL?
29. Explain the difference between a candidate key, primary key, and super key in database design.
30. How do you concatenate strings in SQL?
31. What is the purpose of the HAVING clause in SQL and how does it differ from the WHERE clause?
32. Explain the concept of a self-join in SQL and when it might be used.
33. How do you perform data aggregation across multiple groups in SQL?
34. Explain the difference between a database and a schema in SQL.
35. How do you retrieve data from a table in a random order in SQL?
36. What is the purpose of the ORDER BY clause in SQL and how does it work?

2021-2024 Pg. No.92


BRAINALYST - SQL INTERVIEW QUESTIONS

37. What are window functions? Explain with examples.


38. How do you perform string manipulation and pattern matching in SQL?
39. Explain the difference between a left outer join and a right outer join in SQL.
40. What are the different types of subqueries in SQL and how are they used?
41. How do you find and remove duplicate records from a table in SQL?
42. Explain the concept of a materialized view in SQL and how it differs from a regular view.
43. How do you perform data validation and data cleansing in SQL?
44. Explain the difference between a transaction and a savepoint in SQL.
45. What is a schema in SQL and why is it used?
46. How do you calculate the difference between two dates in SQL?
47. Explain the concept of a composite key in database design and when it might be used.
48. What is a temporary table in SQL and how is it used?
49. Types of Keys?
50. Different types of Operators?
51. Difference between Group By and Where
52. What are Views?
53. What are different types of constraints?
54. What is difference between varchar and nvarchar?
55. Similar for char and nchar?
56. What are index and their types?
57. What is an index? Explain its different types.
58. List the different types of relationships in SQL.
59. How many types of clauses in SQL ?
60. What is the difference between UNION and UNION ALL in SQL?
61. What are the various types of relationships in SQL?
62. Difference between Primary Key and Secondary Key?
63. What is the difference between where and having?
64. Find the second highest salary of an employee?
65. Write retention query in SQL?
66. Write year-on-year growth in SQL?
67. Write a query for cummulative sum in SQL?
68. Difference between Function and Store procedure?
69. Do we use variable in views?
70. What are the limitations of views?

Pg. No.93 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Part 3:
Case study Based Questions:
Q: 1
Schema
Imagine a table named “Movies” with columns: MovieID, Title, ReleaseDate, GenreID. There’s
another table “Genres” with columns: GenreID, GenreName.
Write a SQL query to fetch the genres that don’t have any movies associated with them.

Q:2
Schema
You are given a table named “Attendance” with columns: StudentID, ClassDate, IsPresent (a boolean
where 1 indicates presence and 0 indicates absence).
Write a SQL query to identify students who have missed more than 3 consecutive classes.
Q: 3
Schema
Consider a table named “Elections” with columns: CandidateID, VoterID, VoteDate.
Write a SQL query to calculate the candidate who received the highest number of votes each
month.
Q: 4
Schema
You have a table named “ProductSales” with columns: ProductID, SaleDate, UnitsSold.
Write a SQL query to find the top 3 products that have shown the most significant sales growth
month-over-month.
Q: 5
Schema
You are provided with a table named “LibraryBooks” with columns: BookID, BorrowerID,
BorrowDate, ReturnDate.
Write a SQL query to find out which books are currently borrowed and have passed their return
date without being returned.

2021-2024 Pg. No.94


BRAINALYST - SQL INTERVIEW QUESTIONS

Q: 6
Schema
Consider a table named “OnlineCourses” with columns: CourseID, EnrollmentDate, StudentID,
CompletionDate.
Write a SQL query to determine the courses which have the highest drop rate (i.e., students enrolling
but not completing).
Q: 7
Schema
You have a table named “EmployeeFeedback” with columns: EmployeeID, FeedbackDate, Rating
(from 1 to 10).
Write a SQL query to identify employees whose rating has been declining for the past 3 consecutive
feedback.
Q: 8
Schema
There are two tables: “BlogPosts” and “Comments”.
The “BlogPosts” table has columns: PostID, Title, PostDate, AuthorID.
The “Comments” table has columns: CommentID, PostID, CommentDate, Text.
Write a SQL query to fetch the blog posts that have not received any comments within a week of their
posting.
Q: 9
Schema
You are given a table named “Subscription” with columns: UserID, SubscriptionDate, ExpiryDate.
Write a SQL query to count the number of active subscriptions on the first day of each month in the
past year.
Q: 10
Consider a table named “TouristSpots” with columns: SpotID, SpotName, VisitorID, VisitDate. Write a
SQL query to find the least visited tourist spots in the last summer.

Pg. No.95 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Q: 11
Schema:
There are two tables: “Books” and “Authors”.
The “Books” table has columns: BookID, BookName, AuthorID, SoldCopies.
The “Authors” table has columns: AuthorID, AuthorName.
Write a SQL query to find authors whose books, on average, have sold more than 10,000 copies, but
have written less than 3 books.
Q: 12
Schema
You have a table named “FlightBookings” with columns: BookingID, FlightDate, PassengerID,
Destination.
Write a SQL query to determine which destination has seen a steady month-on-month increase in
bookings over the last year.
Q13
Schema
Table: PatientRecords
Columns: PatientID, VisitDate, DiagnosisCode
Write an SQL query to identify the most frequent diagnosis code for each month. (Note: Patients may
have multiple visits and diagnoses in a month.)
Q:14
Schema
Table: ClinicStaff
Columns: StaffID, Name, HireDate
Craft an SQL query to find the names of staff members who are celebrating their 5th, 10th, and 15th
work anniversaries in 2023.
Q:15
Schema
Table X:
Columns: ids with values 10, 20, 30, 40, 50, null, 60, 70, 80, null, 90, 100
Table Y:
Columns: ids with values 20, null, 40, 60, null, 80, 100, null
Task: Use SQL to demonstrate the results of an inner join, left join, right join, and full outer join
between these tables.
2021-2024 Pg. No.96
BRAINALYST - SQL INTERVIEW QUESTIONS

Q:16
Schema
Table X:
Columns: ids with values 1, 1, 1, 1
Table Y:
Columns: ids with values 1, 1, 1, 1, 1, 1, 1, 1
Q 17: Task: Determine the count of rows in the output of the following queries:
Select * From X join Y on X.ids != Y.ids
Select * From X left join Y on X.ids != Y.ids
Select * From X right join Y on X.ids != Y.ids
Select * From X full outer join Y on X.ids != Y.ids
Q18. Employee Project Allocation - Consider two tables, Employees and Projects:
Schema
CREATE TABLE Employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(255),
department VARCHAR(255) );
CREATE TABLE Projects ( project_id INT PRIMARY KEY, lead_employee_id INT, project_name
VARCHAR(255), start_date DATE, end_date DATE );
Assume necessary INSERT statements are already executed.
Task: The goal is to write an SQL query to find the names of employees who have led more than 3
projects in the last year. The result should be ordered by the number of projects led.
Q19.
Tables:
Orders (Order_id, Customer_id, Order_Date, Total_Amount)
Order_Details (Order_Detail_id, Order_id, Product_id, Quantity, Unit_Price)
Products (Product_id, Product_Name, Category)
Task: Write an SQL query to find the top-selling product (highest revenue) in each category for the
last quarter.
Q20.
Table:
Sales (Sale_id, Sale_Date, Amount)
Question: Write an SQL query to calculate last 7-day rolling average of sales amounts.

Pg. No.97 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Q21. Tables:
Customers (Customer_id, Name, Join_Date)
Orders (Order_id, Customer_id, Order_Date, Amount)
Question: Write an SQL query to list customers who have not placed an order in the last 6 months but
have placed more than 5 orders in total.
Q22. Tables:
Sales (Sale_id, Salesperson_id, Sale_Date, Amount)
Salesperson (Salesperson_id, Name, Region)
Question: Write an SQL query using window functions to rank salespersons in each region by their
total sales amount.
Q23. Customer Purchase Patterns - You have two tables, Customers and Purchases:
Schema
CREATE TABLE Customers ( customer_id INT PRIMARY KEY, customer_name VARCHAR(255) );
CREATE TABLE Purchases ( purchase_id INT PRIMARY KEY, customer_id INT, product_id INT,
purchase_date DATE );
Assume necessary INSERT statements are already executed.
Task: Write an SQL query to find the names of customers who have purchased more than 5 different
products within the last month. Order the result by customer_name.
Q24. Call Log Analysis -Suppose you have a CallLogs table:
Schema
CREATE TABLE CallLogs ( log_id INT PRIMARY KEY, caller_id INT, receiver_id INT, call_start_time
TIMESTAMP, call_end_time TIMESTAMP );
Assume necessary INSERT statements are already executed.
Task: Write a query to find the average call duration per user. Include only users who have made more
than 10 calls in total. Order the result by average duration descending.
Q25.
Tables:
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(255)
);
--
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,

2021-2024 Pg. No.98


BRAINALYST - SQL INTERVIEW QUESTIONS
product_name VARCHAR(255)
);
--
INSERT INTO Customers (customer_id, customer_name) VALUES
(1, ‘Daniel’),
(2, ‘Diana’),
(3, ‘Elizabeth’),
(4, ‘Jhon’);
--
INSERT INTO Orders (order_id, customer_id, product_name) VALUES
(10, 1, ‘A’),
(20, 1, ‘B’),
(30, 1, ‘D’),
(40, 1, ‘C’),
(50, 2, ‘A’),
(60, 3, ‘A’),
(70, 3, ‘B’),
(80, 3, ‘D’),
(90, 4, ‘C’);
Tasks:
1. List all customers who have placed orders and the total number of orders each customer
has placed.
2. Find the product(s) ordered by each customer along with the corresponding customer
name.
3. Identify customers who have not placed any orders.
Q26. Write an SQL query to report the customer_id and customer_name of customers who bought
products “A”, “B” but did not buy the product “C”. Return the result table ordered by customer_id.
Table:
create table call_details (
call_type varchar(10),
call_number varchar(12),
call_duration int
);
--
insert into call_details
values (‘OUT’,’181868’,13),(‘OUT’,’2159010’,8)
,(‘OUT’,’2159010’,178),(‘SMS’,’4153810’,1),(‘OUT’,’2159010’,152),(‘OUT’,’9140152’,18),(‘S
MS’,’4162672’,1)
,(‘SMS’,’9168204’,1),(‘OUT’,’9168204’,576),(‘INC’,’2159010’,5),(‘INC’,’2159010’,4),(‘S

Pg. No.99 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

MS’,’2159010’,1)
,(‘SMS’,’4535614’,1),(‘OUT’,’181868’,20),(‘INC’,’181868’,54),(‘INC’,’218748’,20),(‘INC’,’2159010’,9)
,(‘INC’,’197432’,66),(‘SMS’,’2159010’,1),(‘SMS’,’4535614’,1);
Q27. Write a query to retrieve number having both incoming and outgoing calls & sum of duration of
outgoing is more than that of incoming.
Table:
CREATE TABLE Person (
id INT PRIMARY KEY,
name VARCHAR(255),

phone_number VARCHAR(255)
);
--
CREATE TABLE Country (
name VARCHAR(255),
country_code VARCHAR(3) PRIMARY KEY
);
--
CREATE TABLE Calls (
caller_id INT,
callee_id INT,
duration INT
);
--
INSERT INTO Person (id, name, phone_number) VALUES
(3, ‘Jonathan’, ‘051-1234567’),
(12, ‘Elvis’, ‘051-7654321’),
(1, ‘Monce’, ‘972-5432110’),
(2, ‘Maroua’, ‘212-4321098’),
(7, ‘Meir’, ‘972-2211111’),
(9, ‘Rachel’, ‘972-2221111’);
--
INSERT INTO Country (name, country_code) VALUES
(‘Peru’, ‘051’),
(‘Israel’, ‘972’),
(‘Morocco’, ‘212’),
(‘Germany’, ‘049’),
(‘Ethiopia’, ‘251’);
--
INSERT INTO Calls (caller_id, callee_id, duration) VALUES
(1, 9, 33),
(2, 9, 4),
(1, 2, 59),
(3, 12, 102),
(3, 12, 330),
(12, 3, 5),

2021-2024 Pg. No.100


BRAINALYST - SQL INTERVIEW QUESTIONS

(7, 9, 13),
(7, 1, 3),
(9, 7, 1),
(1, 7, 7);
Q28. A telecommunications company wants to invest in new countries. The company intends to
invest in countries where the average call duration of the calls in that country is strictly greater than
the global average call duration. Write an SQL query to find the countries where this company can
invest.
Q29. Customer Purchase Patterns - You have two tables, Customers and Purchases:
Tables
CREATE TABLE Customers ( customer_id INT PRIMARY KEY, customer_name VARCHAR(255) );
CREATE TABLE Purchases ( purchase_id INT PRIMARY KEY, customer_id INT, product_id INT,
purchase_date DATE );
Assume necessary INSERT statements are already executed.
Task: Write an SQL query to find the names of customers who have purchased more than 5 different
products within the last month. Order the result by customer_name.
Q30. Call Log Analysis -Suppose you have a CallLogs table:
Table:
CREATE TABLE CallLogs ( log_id INT PRIMARY KEY, caller_id INT, receiver_id INT, call_start_time
TIMESTAMP, call_end_time TIMESTAMP );
Assume necessary INSERT statements are already executed.
Task: Write a query to find the average call duration per user. Include only users who have made more
than 10 calls in total. Order the result by average duration descending.
Q31.
Tables:
CREATE TABLE Customers (
cstomer_id INT PRIMARY KEY,
customer_name VARCHAR(255)
);
--
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,
product_name VARCHAR(255)
);
--
INSERT INTO Customers (customer_id, customer_name) VALUES
(1, ‘Daniel’),
(2, ‘Diana’),
(3, ‘Elizabeth’),
Pg. No.101 2021-2024
BRAINALYST - SQL INTERVIEW QUESTIONS

(4, ‘Jhon’);
--
INSERT INTO Orders (order_id, customer_id, product_name) VALUES
(10, 1, ‘A’),
(20, 1, ‘B’),
(30, 1, ‘D’),
(40, 1, ‘C’),
(50, 2, ‘A’),

(60, 3, ‘A’),
(70, 3, ‘B’),
(80, 3, ‘D’),
(90, 4, ‘C’);
Q32. Write an SQL query to report the customer_id and customer_name of customers who bought
products “A”, “B” but did not buy the product “C”. Return the result table ordered by customer_id.
Call details_table:
create table call_details (
call_type varchar(10),
call_number varchar(12),
call_duration int
);
--
insert into call_details
values (‘OUT’,’181868’,13),(‘OUT’,’2159010’,8)
,(‘OUT’,’2159010’,178),(‘SMS’,’4153810’,1),(‘OUT’,’2159010’,152),(‘OUT’,’9140152’,18),(‘S
MS’,’4162672’,1)
,(‘SMS’,’9168204’,1),(‘OUT’,’9168204’,576),(‘INC’,’2159010’,5),(‘INC’,’2159010’,4),(‘S
MS’,’2159010’,1)
,(‘SMS’,’4535614’,1),(‘OUT’,’181868’,20),(‘INC’,’181868’,54),(‘INC’,’218748’,20),(‘INC’,’2159010’,9)
,(‘INC’,’197432’,66),(‘SMS’,’2159010’,1),(‘SMS’,’4535614’,1);
Q33. Write a query to retrieve number having both incoming and outgoing calls & sum of duration of
outgoing is more than that of incoming.
Tables:
CREATE TABLE Person (
id INT PRIMARY KEY,
name VARCHAR(255),
phone_number VARCHAR(255)
);
--
CREATE TABLE Country (
name VARCHAR(255),
country_code VARCHAR(3) PRIMARY KEY
);
--
CREATE TABLE Calls (
2021-2024 Pg. No.102
BRAINALYST - SQL INTERVIEW QUESTIONS

caller_id INT,
callee_id INT,
duration INT
);
--
INSERT INTO Person (id, name, phone_number) VALUES
(3, ‘Jonathan’, ‘051-1234567’),
(12, ‘Elvis’, ‘051-7654321’),
(1, ‘Monce’, ‘972-5432110’),
(2, ‘Maroua’, ‘212-4321098’),

(7, ‘Meir’, ‘972-2211111’),


(9, ‘Rachel’, ‘972-2221111’);
--
INSERT INTO Country (name, country_code) VALUES
(‘Peru’, ‘051’),
(‘Israel’, ‘972’),
(‘Morocco’, ‘212’),
(‘Germany’, ‘049’),
(‘Ethiopia’, ‘251’);
--
INSERT INTO Calls (caller_id, callee_id, duration) VALUES
(1, 9, 33),
(2, 9, 4),
(1, 2, 59),
(3, 12, 102),
(3, 12, 330),
(12, 3, 5),
(7, 9, 13),
(7, 1, 3),
(9, 7, 1),
(1, 7, 7);
Q34. A telecommunications company wants to invest in new countries. The company intends to
invest in countries where the average call duration of the calls in that country is strictly greater than
the global average call duration. Write an SQL query to find the countries where this company can
invest.
Q35.
Swiggy SQL interview Questions:-
Question 1: Year-Over-Year Customer Spend Analysis
- Scenario: Analyze year-over-year growth in customer spending.
- Table Schema: CREATE TABLE customer_purchases (
Customer_id VARCHAR,
Product_id VARCHAR,
Purchase_amount DECIMAL(10,2),

Pg. No.103 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Purchase_date DATE
);
Challenge: Write a SQL query to calculate the YoY growth rate of the amount spent by each custom-
er.
Question 2: Inventory Threshold Analysis
- Scenario: Identify days when product stock falls below a critical level.
- Table Schema:
CREATE TABLE supplier_inventory (
Supplier_id VARCHAR,
Product_id VARCHAR,
Stock_quantity INT,
Record_date DATE
);
Challenge: Find the periods when stock quantity was below 50 units for more than two consecutive
days.
Q36: Employee Sales Performance Ranking
- Scenario: Rank employees in each store by their sales in the current year.
- Table Schema:
CREATE TABLE employee_sales (
Employee_id VARCHAR,
Store_id VARCHAR,
Sale_amount DECIMAL(10,2),
Sale_year INT
);
Challenge: Select Employee_id, Store_id, and rank based on Sale_amount for 2023.
Q37: Frequent Flyers from the Same Airport
- Scenario: Find passengers with frequent flights from the same airport over the last year.
- Table Schema:
CREATE TABLE passenger_flights (
Passenger_id VARCHAR,
Flight_id VARCHAR,
Departure_date DATE
);
CREATE TABLE flight_details (
Flight_id VARCHAR PRIMARY KEY,
Departure_airport_code VARCHAR,
Arrival_airport_code VARCHAR
);
Challenge: Identify passengers with more than 10 flights from the same airport since last year.

2021-2024 Pg. No.104


BRAINALYST - SQL INTERVIEW QUESTIONS

Q38. Product Sales Analysis - Consider two tables, Products and Sales:
Table Schemas -
CREATE TABLE Products ( product_id INT PRIMARY KEY, product_name VARCHAR(255), category
VARCHAR(255) );
CREATE TABLE Sales ( sale_id INT PRIMARY KEY, product_id INT, sale_date DATE, quantity_sold INT
);
Assume necessary INSERT statements are already executed.
Task: Write an SQL query to find the names of products that have sold more than 100 units in the last
quarter. The result should be ordered by product_name.
Q39. Employee Attendance Tracking - Imagine you have an EmployeeAttendance table:
Table Schemas -
CREATE TABLE EmployeeAttendance ( attendance_id INT PRIMARY KEY, employee_id INT, clock_
in_time TIMESTAMP, clock_out_time TIMESTAMP );
Assume necessary INSERT statements are already executed.
Task: Write a query to find the average working hours per day for each employee. Include only
employees who have clocked more than 20 days. Order the results by average working hours
ascending.
Q40. Customer Feedback Analysis - You have two tables, Customers and Feedback:
Table Schemas -
CREATE TABLE Customers ( customer_id INT PRIMARY KEY, customer_name VARCHAR(255), email
VARCHAR(255) );
CREATE TABLE Feedback ( feedback_id INT PRIMARY KEY, customer_id INT, feedback_date DATE,
rating INT );
Note:
Assume necessary INSERT statements are already executed.
The task is to write an SQL query to find the names of customers who have given a rating of 5 more
than 3 times in the last 6 months. Order the result by customer_name
Q41.
Write an SQL query to select Product_id for products that had a stock quantity of less than 20 units
for each of the last 5 recorded days.
Question 1: Calculate the average stock price for Company X over the last 6 months.
Question 2: Identify the month with the highest total sales for Company Y using their monthly sales
data.

Pg. No.105 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Question 3: Find the maximum and minimum stock price for Company Z on any given day in the last
year.
Question 4: Create a column in the DataFrame showing the percentage change in stock price from
the previous day for Company X.
Question 5: Determine the number of days when the sales of Company Y were above its 30-day
moving average.
Question 6: Compare the average stock price of Companies X and Z in the first quarter of the year.
Q42.
Q1. Given a sales_data table, write a query to display the month-over-year change in total sales.
Table structure:
CREATE TABLE sales_data (
Sale_id VARCHAR PRIMARY KEY,
Product_id VARCHAR,
Sale_amount DECIMAL(10,2),
Sale_date DATE
);
Required: Write an SQL query to calculate the percentage change in total sales for each month
compared to the same month in the previous year.
Q2. You have a customer_orders table that tracks every order placed by customers. Find customers
who placed orders in the first quarter of 2022 but did not place any orders in the first quarter of
2023.
Table structure:
CREATE TABLE customer_orders (
Order_id VARCHAR PRIMARY KEY,
Customer_id VARCHAR,
Order_amount DECIMAL(10,2),
Order_date DATE
);
Required: Write an SQL query to select the Customer_id of those who were active in Q1 of 2022
but inactive in Q1 of 2023.
Q3. Given an employee_tasks table, rank employees based on the number of tasks completed this
month.
Table structure:
CREATE TABLE employee_tasks (
Task_id VARCHAR PRIMARY KEY,
Employee_id VARCHAR,
Task_status VARCHAR, -- Values can be ‘Completed’, ‘In Progress’, or ‘Not Started’
Task_date DATE
);

2021-2024 Pg. No.106


BRAINALYST - SQL INTERVIEW QUESTIONS

Required: Write an SQL query to select Employee_id and a rank based on the count of completed
tasks for the current month, with 1 being the employee with the most tasks completed.
Q4. Using the product_inventory table, identify products that have consistently low stock (below 20
units) for the last 5 days.
Table structure:
CREATE TABLE product_inventory (
Product_id VARCHAR,
Stock_quantity INT,
Record_date DATE);
Q43.
#Data#
import pandas as pd
import numpy as np

data = {
‘Date’: pd.date_range(start=’2023-01-01’, periods=180, freq=’D’),
‘CompanyX_StockPrice’: np.random.randint(50, 150, 180),
‘CompanyY_Sales’: np.random.randint(20000, 50000, 180),
‘CompanyZ_StockPrice’: np.random.randint(70, 200, 180)
}

df = pd.DataFrame(data)
Q44:
Question 1: Calculate the average stock price for Company X over the last 6 months.
Question 2: Identify the month with the highest total sales for Company Y using their monthly sales
data.
Question 3: Find the maximum and minimum stock price for Company Z on any given day in the last
year.
Question 4: Create a column in the DataFrame showing the percentage change in stock price from
the previous day for Company X.
Question 5: Determine the number of days when the sales of Company Y were above its 30-day
moving average.
Question 6: Compare the average stock price of Companies X and Z in the first quarter of the year.

Pg. No.107 2021-2024


BRAINALYST - SQL INTERVIEW QUESTIONS

Q45:
#Data#----------------------------------------------

import pandas as pd
import numpy as np

data = {
‘Date’: pd.date_range(start=’2023-01-01’, periods=180, freq=’D’),
‘CompanyX_StockPrice’: np.random.randint(50, 150, 180),
‘CompanyY_Sales’: np.random.randint(20000, 50000, 180),
‘CompanyZ_StockPrice’: np.random.randint(70, 200, 180)
}

df = pd.DataFrame(data)
Task: Write a SQL query to calculate the average stock price of CompanyX for each month, along
with the total sales of CompanyY for each month. Display the results with the month and year as
the grouping criteria.
Q46:
A. SQL-:
1 - You have two tables - Employee & Department
Columns of Employee Table - Emp_id, Emp_Name, Salary, Dept_id
Columns of Department Table - Dept_id, Dept_Name
Write SQL query to fetch Dept_Name which have 2nd Highest average salary.
2 - You have two tables - Orders & Delivery_Status
Columns of Orders Table - order_id, timestamp, product_id, unit_price
Columns of Delivery_Status Table - order_id, timestamp, status
FYI - status column have these entries - New, Cancelled, RTO, Returned
NMV = sum of unit_price (orders who have status = New) - sum of unit_price (orders who have sta-
tus = Cancelled) - sum of unit_price (orders who have status = RTO) - sum of unit_price (orders who
have status = Returned)
Q47:
Write SQL query to calculate NMV value Month-on-Month. Output tables should contain these two
columns - Month, NMV.

2021-2024 Pg. No.108


BRAINALYST - SQL INTERVIEW QUESTIONS

Q48.
1. You have two tables: Product and Supplier.
- Product Table Columns: Product_id, Product_Name, Supplier_id, Price
- Supplier Table Columns: Supplier_id, Supplier_Name, Country
Write an SQL query to find the name of the product with the highest price in each country.
2. You have two tables: Customer and Transaction.
- Customer Table Columns: Customer_id, Customer_Name, Registration_Date
- Transaction Table Columns: Transaction_id, Customer_id, Transaction_Date, Amount
Write an SQL query to calculate the total transaction amount for each customer for the current
year. The output should contain Customer_Name and the total amount.

------------------------------------------------------------------------------------------------------------------------------------------------------

Pg. No.109 2021-2024

You might also like