SQL
SQL
5.What are indexes in SQL? How do they work and what are their benefits and
drawbacks?
Indexes are special data structures that improve the speed of data retrieval
operations on a database table at the cost of additional writes and storage space.
Benefits:
Faster data retrieval.
Improved query performance.
Drawbacks:
Slower write operations (INSERT, UPDATE, DELETE) due to index maintenance.
Increased storage space.
10.What are stored procedures? How do they differ from functions in SQL?
Stored Procedures: Precompiled collections of one or more SQL statements that can
be executed as a single unit. They can perform actions such as modifying data and
managing database transactions.
Functions: Precompiled collections of SQL statements that return a single value.
They cannot modify data and are used mainly for computations.
Differences:
Stored procedures can perform both actions (INSERT, UPDATE, DELETE) and
computations, while functions are used primarily for computations.
Functions must return a value, whereas stored procedures may or may not return a
value.
UNION ALL: Combines the results of two or more SELECT statements without removing
duplicates.
SELECT column1 FROM table1
UNION ALL
SELECT column1 FROM table2;
20.Explain the concept of window functions and provide examples of their use.
Window functions perform calculations across a set of table rows related to the
current row. Unlike aggregate functions, they do not group the result set into a
single output row.
Examples:
ROW_NUMBER(): Assigns a unique number to each row within a partition.
sql
Copy code
SELECT employee_id, salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM Employees;
RANK(): Assigns a rank to each row within a partition of the result set.
SELECT employee_id, salary, RANK() OVER (ORDER BY salary DESC) AS rank
FROM Employees;
SUM() OVER: Calculates a running total.
SELECT employee_id, salary, SUM(salary) OVER (ORDER BY employee_id) AS
running_total
FROM Employees;