0% found this document useful (0 votes)
2 views9 pages

SQL Interview Questions

The document provides a comprehensive set of Oracle SQL and stored procedure interview questions, covering topics such as basic SQL queries, optimization techniques, SQL functions, and advanced concepts like window functions and dynamic SQL. It also explains the differences between stored procedures and functions, parameter types, and the use of Common Table Expressions (CTEs). Additionally, it includes practical examples and explanations of how to design and implement SQL queries for reporting purposes.

Uploaded by

as.joshi743
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

SQL Interview Questions

The document provides a comprehensive set of Oracle SQL and stored procedure interview questions, covering topics such as basic SQL queries, optimization techniques, SQL functions, and advanced concepts like window functions and dynamic SQL. It also explains the differences between stored procedures and functions, parameter types, and the use of Common Table Expressions (CTEs). Additionally, it includes practical examples and explanations of how to design and implement SQL queries for reporting purposes.

Uploaded by

as.joshi743
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

•• PROTECTED 関係者外秘

Oracle SQL & Stored Procedure Interview


Questions

Basic SQL
1. JOIN:
a. "Write a query to get the names of employees along with their department
names. Use employees and departments tables."
2. GROUP BY and aggregate:
a. "Write a query to find the total salary expense per department from the
employees table."
3. Subquery:
a. "Write a query to find employees who earn more than the average salary."

SQL in Reporting Context:


 How would you optimize an SQL query for generating a
report where large amounts of data from multiple tables are
being aggregated?
 Use Indexes: Make sure columns used in joins, filters (WHERE), or grouping (GROUP
BY) have appropriate indexes. This speeds up data retrieval.
 Limit the data early: Use WHERE clauses to filter unnecessary rows as soon as
possible. Only select the columns needed — avoid SELECT *.
 Choose efficient joins: Use INNER JOIN if you don't need unmatched data from
both tables. Make sure join keys are indexed.
 Aggregate smartly: Pre-aggregate data when possible. For example, use a
subquery to group data before joining with other tables.
 Use Common Table Expressions (CTEs) carefully: They can make queries easier
to read but might not always be the most efficient if reused multiple times.
 Partition large tables: This helps to scan only relevant partitions (e.g., filtering by
date).
 Use materialized views or summary tables: If the report runs regularly, you can
store pre-calculated results for faster performance.
 Check query plans: Use tools like EXPLAIN to understand how your query runs and
find performance issues.
 How would you use SQL functions (like TO_DATE, CONCAT,
etc.) to format or transform data for reporting purposes?
 Date functions:
o TO_DATE converts strings to date format (useful when dealing with text data).
o DATE_TRUNC (in some databases like PostgreSQL) can round dates to the start
of the month or year — useful for grouping data by time.
 String functions:
•• PROTECTED 関係者外秘

o CONCAT joins strings, like combining first and last names into a full name.
o SUBSTR, LEFT, or RIGHT let you extract specific parts of a string.
o UPPER, LOWER, and INITCAP change letter casing for cleaner formatting.
 Number formatting:
o ROUND is used to control decimal places.
o CAST or CONVERT changes data types, like turning a number into a string.
 Conditional logic:
o CASE lets you create custom categories or labels (e.g., marking salaries over
100k as "High Earners").

Advanced Functions and Operators:

 Explain the difference between ROWNUM and ROW_NUMBER().


When would you use each of these in Oracle SQL?
ANS: - ROWNUM is a pseudo column that assigns a unique number to
each row in the result set, starting from 1, based on the order they are
retrieved. ROW_NUMBER() is an analytic function that assigns a
unique number to each row within a partition, based on a specified
order. Use ROWNUM for simple row numbering
and ROW_NUMBER() for more complex ordering within partitions.

 What is the purpose of COLAESCE() Function?


ANS: - The COALESCE() function returns the first non-NULL value in a
list of arguments. It is useful for handling NULL values. For example:

 What are window functions (e.g., RANK(), DENSE_RANK(), LEAD(),


LAG()) in Oracle SQL? Can you provide an example of how and when
you would use them?
ANS:- Window functions perform calculations across a set of table
rows related to the current row, allowing for complex data analysis
without needing subqueries. Examples
include RANK(), DENSE_RANK(), LEAD(), and LAG().
When to Use:
RANK() and DENSE_RANK(): To assign ranks to rows based on a
column's value, useful for identifying top performers.
LEAD() and LAG(): To access subsequent or preceding row values,
helpful for trend analysis.

 Can you explain how you would design a stored procedure to


accept dynamic parameters for reporting purposes?
•• PROTECTED 関係者外秘

Designing a Stored Procedure with Dynamic Parameters for Reporting

 Use CREATE PROCEDURE with parameters to accept inputs like @StartDate,


@EndDate, @Region, etc.
 Parameters can have default values to support optional filtering.
 Use dynamic SQL (sp_executesql) for flexible WHERE clauses.
 Validate inputs inside the procedure for security.
 Support output parameters if required (e.g., total count).
 Consider using CASE logic to handle optional filters without dynamic SQL.
 Index columns used in filters to improve performance.
 Always use parameterized queries to prevent SQL injection.

 What is the difference between a subquery and a Common


Table Expression (CTE)? When would you prefer using one
over the other?
 Subquery: Nested SELECT inside another query.
 CTE: Defined using WITH, works like a named temporary result set.
 Subqueries can be in SELECT, FROM, or WHERE clauses.
 CTEs improve readability, especially for complex logic.
 CTEs support recursion, subqueries do not.
 CTEs are reusable within the main query (subqueries are not).
 Subqueries can be correlated or non-correlated.
 Use CTEs for clarity and recursive operations; subqueries for simple filtering or
scalar values.

 What is a WITH clause, and how does it differ from a


temporary table?
The WITH clause (also known as Common Table Expression or CTE) allows you to
define a temporary result set that can be referenced within a SELECT, INSERT, UPDATE,
or DELETE statement. It is used for simplifying complex queries and improving
readability.

 Can you write a query that uses a CTE to calculate running


totals?
WITH Sales_CTE AS (
SELECT
OrderID,
CustomerID,
OrderDate,
TotalAmount,
ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNum
FROM Orders
)
SELECT
a.OrderID,
•• PROTECTED 関係者外秘

a.CustomerID,
a.OrderDate,
a.TotalAmount,
SUM(b.TotalAmount) AS RunningTotal
FROM Sales_CTE a
JOIN Sales_CTE b ON b.RowNum <= a.RowNum
GROUP BY a.OrderID, a.CustomerID, a.OrderDate, a.TotalAmount
ORDER BY a.OrderDate;

 CTE assigns row numbers based on OrderDate.


 Self-join on row numbers to get all earlier (or equal) rows.
 SUM() calculates the cumulative total up to that point.
 Useful for financial reports, trend analysis, etc.

 How would you use a subquery to filter rows in a SELECT


statement?
 When to Use Subqueries in Filtering
 To filter by results from another table or aggregated values.
 When joins are unnecessary or too complex.
 For reusability inside a condition (IN, =, <, EXISTS, etc.).

PL/SQL Procedures and Functions:

 What are the differences between a stored procedure and a


stored function in Oracle SQL? Can you provide an example
of each and describe when to use one over the other?

Stored Procedure Stored Function


•• PROTECTED 関係者外秘

CREATE OR REPLACE PROCEDURE CREATE OR REPLACE FUNCTION


Update_Salary ( Get_Annual_Salary (

p_emp_id IN NUMBER, p_emp_id IN NUMBER

p_increase IN NUMBER ) AS ) RETURN NUMBER AS

BEGIN v_salary NUMBER;

UPDATE Employees BEGIN

SET Salary = Salary + p_increase SELECT Salary * 12 INTO


v_salary
WHERE EmployeeID = p_emp_id;
FROM Employees
END;
WHERE EmployeeID = p_emp_id;

RETURN v_salary;

END;

USAGE: USAGE:

BEGIN SELECT Get_Annual_Salary(101)


FROM dual;
Update_Salary(101, 1000);

END;

 How would you pass parameters to a stored procedure or


function? What is the difference between IN, OUT, and
INOUT parameters, and when would you use each type?
 Define the parameters in the procedure/function header.
 Call with actual values in either positional or named style.
 Procedures are called using EXEC or within PL/SQL blocks.
 Functions can be used in SQL queries or PL/SQL blocks.
 Positional syntax: Order matters → MyProc(10, 'HR')
 Named syntax: More flexible → MyProc(p_id => 10, p_dept => 'HR')
 In PL/SQL, OUT/INOUT parameters must be variables, not literals.
•• PROTECTED 関係者外秘

Example of Parameter IN & OUT & INOUT

 Explain this query -


 customer_orders: This table stores the details of customer orders.
 clients: This table stores information about clients (customers).
 products: This table stores information about products available for sale.
•• PROTECTED 関係者外秘

 target_table = sales_report: This is the target table where aggregated or


processed sales data is stored
•• PROTECTED 関係者外秘

QUERY -

Explanation:

1. Parameters:
a. p_case IN OUT NUMBER: A parameter that controls the flow of logic. If it's 1,
the procedure performs an INSERT operation; otherwise, it performs a MERGE.
b. p_start_date IN DATE & p_end_date IN DATE: These parameters filter
records by order date range.
c. p_status IN VARCHAR2: This parameter filters clients based on their status
(e.g., "ACTIVE" or "INACTIVE").
2. Dynamic SQL (EXECUTE IMMEDIATE):
a. The EXECUTE IMMEDIATE statement here is just a placeholder for dynamic SQL
queries, which you can customize if needed.
3. Conditional Logic (IF-ELSE):
•• PROTECTED 関係者外秘

a. If p_case = 1, the procedure inserts data into the sales_report table. The
data is aggregated based on client and product, summing up order amounts
for each combination, and filtered by the date range and client status.
b. If p_case != 1, a MERGE INTO operation is performed. This will update the
existing records in the sales_report table if a matching combination of client
and product exists. If no match is found, it inserts new records.
4. Joins:
a. In both the INSERT and MERGE operations, multiple joins are performed:
i. customer_orders is joined with clients to filter by client.
ii. customer_orders is joined with products to include product details.
5. COMMIT:
a. After the INSERT or MERGE operation, the changes are committed to the
database.

You might also like