SQL Stored Procedures Interview Questions

Master SQL Stored Procedures with interview-focused questions covering procedure creation, parameters, variables, control statements, exception handling, dynamic SQL, transactions, performance, and enterprise production best practices.

Introduction

A Stored Procedure is a precompiled collection of SQL statements stored inside the database.

Instead of sending multiple SQL statements from an application,

we can simply call a stored procedure.

Stored Procedures are widely used in

  • Banking
  • Insurance
  • ERP
  • Payroll
  • Healthcare
  • Financial Systems

They provide

  • Better Performance
  • Code Reusability
  • Security
  • Centralized Business Logic
  • Easier Maintenance

Stored Procedures are one of the most frequently asked SQL interview topics.


Stored Procedure Architecture

flowchart LR

Application --> StoredProcedure["Stored Procedure"]

StoredProcedure["Stored Procedure"] --> SqlStatements["SQL Statements"]

SqlStatements["SQL Statements"] --> Database

Sample Employee Table

ID Name Department Salary
101 John IT 90000
102 Alice HR 85000
103 David IT 95000

1. What is a Stored Procedure?

Answer

A Stored Procedure is a named collection of SQL statements stored inside the database that can be executed repeatedly.

Unlike normal SQL queries,

Stored Procedures are compiled and stored by the database.


Procedure Workflow

Application

↓

CALL Procedure

↓

Database Executes SQL

↓

Result

2. Why are Stored Procedures used?

Stored Procedures provide

  • Better Performance
  • Centralized Logic
  • Security
  • Reusability
  • Reduced Network Traffic

3. How do you create a Stored Procedure?

MySQL Example

DELIMITER $$

CREATE PROCEDURE GetEmployees()
BEGIN
    SELECT *
    FROM Employee;
END $$

DELIMITER ;

Oracle Example

CREATE OR REPLACE PROCEDURE GetEmployees
AS
BEGIN
    SELECT *
    FROM Employee;
END;

SQL Server Example

CREATE PROCEDURE GetEmployees
AS
BEGIN
    SELECT *
    FROM Employee;
END;

4. How do you execute a Stored Procedure?

MySQL

CALL GetEmployees();

Oracle

BEGIN
    GetEmployees;
END;

SQL Server

EXEC GetEmployees;

5. What are Procedure Parameters?

Parameters allow values to be passed into or out of a procedure.

Types

  • IN
  • OUT
  • INOUT (database dependent)

Parameter Flow

Application

↓

Parameters

↓

Stored Procedure

↓

Result

6. What is an IN Parameter?

An IN parameter

passes data

into

the procedure.

CREATE PROCEDURE GetEmployee(
IN empId INT
)

7. What is an OUT Parameter?

An OUT parameter

returns data

from

the procedure.

OUT totalSalary DECIMAL(10,2)

8. What is an INOUT Parameter?

INOUT

acts as

both

input

and

output.

Supported in databases such as MySQL.


9. What are Variables?

Variables temporarily store values during procedure execution.

Example

DECLARE total DECIMAL(10,2);

10. What is DECLARE?

DECLARE creates

local variables.

DECLARE employeeCount INT;

11. What is SET?

SET assigns values.

SET employeeCount = 100;

12. What are Control Statements?

Control statements manage program flow.

Examples

  • IF
  • CASE
  • LOOP
  • WHILE
  • REPEAT
  • FOR (Oracle PL/SQL)

Control Flow

IF

↓

TRUE

↓

Execute

FALSE

↓

Else

13. IF Statement Example

IF salary > 100000 THEN
   SET bonus = 5000;
ELSE
   SET bonus = 1000;
END IF;

14. CASE Statement Example

CASE department
WHEN 'IT'
THEN 'Technology'
WHEN 'HR'
THEN 'Human Resources'
ELSE 'Other'
END

15. What are Loops?

Loops repeat execution.

Common loops

  • LOOP
  • WHILE
  • REPEAT
  • FOR

Loop Example

WHILE counter <= 10 DO

SET counter = counter + 1;

END WHILE;

16. What is Exception Handling?

Exception Handling manages runtime errors.

Examples

  • Duplicate Keys
  • Divide by Zero
  • Missing Data

Exception Flow

flowchart LR

Procedure --> Exception

Exception --> Handler

Handler --> Recovery

17. Exception Example

Oracle

BEGIN

...

EXCEPTION

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('Error');

END;

MySQL

DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    ROLLBACK;
END;

18. What is Dynamic SQL?

Dynamic SQL builds SQL statements during execution.

Example

SET @sql =
'SELECT * FROM Employee';

PREPARE stmt FROM @sql;

EXECUTE stmt;

19. Why use Dynamic SQL?

Useful when

  • Table Names Change
  • Optional Filters
  • Dynamic Reports
  • Flexible Search

Use carefully to avoid SQL injection.


20. Can Stored Procedures contain Transactions?

Yes.

Example

START TRANSACTION;

UPDATE Accounts
SET balance = balance - 100
WHERE id = 1;

UPDATE Accounts
SET balance = balance + 100
WHERE id = 2;

COMMIT;

21. Banking Example

Transfer Money

Validate Accounts

Debit

Credit

Commit


22. HR Example

Employee Promotion

Update Salary

Update Grade

Commit


23. Healthcare Example

Patient Registration

Insert Patient

Create Appointment

Commit


24. E-Commerce Example

Order Placement

Inventory Check

Create Order

Payment

Commit


25. Production Example

Loan Approval

Credit Score

Risk Validation

Approval

Notification


26. Advantages of Stored Procedures

  • Faster Execution
  • Centralized Logic
  • Reusable Code
  • Better Security
  • Reduced Network Calls
  • Easier Maintenance

27. Limitations

  • Vendor Specific Syntax
  • Debugging Can Be Difficult
  • Version Control Challenges
  • Complex Business Logic Can Become Hard to Maintain
  • Limited Portability Across Databases

28. Stored Procedure vs Function

Stored Procedure Function
Can Return Multiple Values Returns One Value
Can Modify Data Usually Used for Calculations (database dependent)
Can Manage Transactions Generally Cannot Control Transactions
Called Using EXEC/CALL Used Inside SQL Expressions

29. Common Mistakes

  • Large Procedures
  • No Exception Handling
  • Hardcoded Values
  • Missing Transactions
  • Dynamic SQL Without Validation
  • Poor Naming Conventions

30. What are the Best Practices?

  • Keep procedures focused on one business operation.
  • Use meaningful names.
  • Validate all input parameters.
  • Handle exceptions properly.
  • Use transactions for critical operations.
  • Avoid unnecessary dynamic SQL.
  • Parameterize queries to prevent SQL injection.
  • Log important errors.
  • Keep procedures modular.
  • Document procedure behavior.

Stored Procedure Workflow

flowchart LR

Application --> Procedure

Procedure --> BusinessLogic["Business Logic"]

BusinessLogic["Business Logic"] --> SQL

SQL --> Database

Database --> Result

Enterprise Best Practices

  • Keep business logic modular.
  • Use parameterized procedures.
  • Handle exceptions consistently.
  • Use transactions for ACID compliance.
  • Avoid very large procedures.
  • Review execution plans regularly.
  • Secure procedures with least-privilege permissions.
  • Version-control procedure scripts.
  • Log failures and execution time.
  • Regularly review and optimize long-running procedures.

Quick Revision

Topic Key Point
Stored Procedure Precompiled SQL Program
CALL / EXEC Execute Procedure
IN Input Parameter
OUT Output Parameter
INOUT Input + Output
Variables Temporary Storage
IF Conditional Logic
LOOP Repeated Execution
Exception Handling Error Recovery
Dynamic SQL Runtime SQL
Transaction COMMIT / ROLLBACK

Interview Tips

Interviewers frequently ask

  • What is a Stored Procedure?
  • Why use Stored Procedures?
  • Stored Procedure vs Function.
  • IN vs OUT Parameters.
  • Dynamic SQL.
  • Exception Handling.
  • Transactions inside Procedures.
  • Advantages and disadvantages.
  • Performance benefits.
  • Real-world use cases.

A strong interview explanation is:

"A Stored Procedure is a precompiled collection of SQL statements stored inside the database. It improves performance by reducing repeated SQL parsing, centralizes business logic, enhances security through controlled access, and reduces network traffic by executing multiple SQL operations in a single database call. Stored Procedures support parameters, variables, control flow, exception handling, and transactions, making them ideal for enterprise business operations."


Summary

Stored Procedures are powerful database programs that encapsulate business logic close to the data. They improve performance, security, maintainability, and code reuse while supporting parameters, variables, conditional logic, loops, exception handling, dynamic SQL, and transactions. They are widely used for implementing complex business workflows in enterprise applications.

Mastering Stored Procedures, parameters, control statements, exception handling, dynamic SQL, transactions, and enterprise best practices is essential for Backend Developers, Database Engineers, Java Developers, and Solution Architects working with relational databases.