SQL Interview Questions
SQL 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."
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").
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;
RETURN v_salary;
END;
USAGE: USAGE:
END;
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.