

What is a stored procedure in SQL? Discuss its purpose, how it differs from regular SQL statements, and when it is beneficial to use them.
The interviewer expects a clear explanation of what stored procedures are, their advantages, and examples of scenarios where they are particularly useful.
A stored procedure is a precompiled collection of one or more SQL statements that can be executed as a single unit. It is stored in the database and can be invoked by applications or users.
CREATE PROCEDURE GetCustomerOrders(@CustomerID INT)
AS
BEGIN
SELECT * FROM Orders WHERE CustomerID = @CustomerID;
END;
Stored procedures enhance performance by reducing the amount of information sent between the application and the database. They also promote code reusability and maintainability.
Stored procedures are useful for encapsulating complex business logic, batch processing, and data validation. They can also help in implementing security measures by restricting direct access to tables.