SQL Stored Procedures


SQL Stored Procedures Interview with follow-up questions

1. What is a stored procedure in SQL and why is it used?

A stored procedure is a named, precompiled collection of SQL statements (and optional procedural logic) stored in the database that can be executed by name, with optional parameters.

-- PostgreSQL
CREATE OR REPLACE PROCEDURE update_salary(
    p_employee_id INT,
    p_new_salary  DECIMAL
)
LANGUAGE plpgsql AS $$
BEGIN
    UPDATE employees SET salary = p_new_salary WHERE employee_id = p_employee_id;
    COMMIT;
END;
$$;

-- Call it:
CALL update_salary(42, 95000);

Why stored procedures are used:

  1. Performance: The query is parsed and its execution plan cached on first call. Subsequent executions reuse the plan (plan caching), avoiding repeated parse/compile overhead.

  2. Reduced network traffic: A single CALL replaces sending multiple SQL statements over the network.

  3. Security: Applications can be granted EXECUTE permission on a procedure without direct table access — the procedure acts as a controlled API layer.

  4. Code reuse and maintainability: Business logic is centralized in the database, callable from multiple applications or services.

  5. Encapsulation: Multi-step operations (begin transaction, validate, update, commit) are wrapped in one callable unit.

Stored procedure vs function:

  • A procedure performs actions; in SQL standard it cannot return a value (but can use OUT parameters)
  • A function returns a value and can be used in SQL expressions (SELECT my_func(x))
  • PostgreSQL uses CREATE PROCEDURE (added in v11) for procedures and CREATE FUNCTION for functions; MySQL and SQL Server use CREATE PROCEDURE for both concepts with slight differences

2026 note: Many modern applications rely on ORMs and microservices, reducing stored procedure usage. They remain common in enterprise environments with SQL Server and Oracle.

↑ Back to top

Follow-up 1

Can you explain the difference between a stored procedure and a function in SQL?

In SQL, a stored procedure is a set of SQL statements that can perform various operations and may or may not return a value. On the other hand, a function is a database object that always returns a value. Functions can be used in SQL queries and expressions, while stored procedures cannot be used in such a way. Additionally, functions can be used in SELECT statements, whereas stored procedures cannot be used in this manner.

Follow-up 2

What are some advantages of using stored procedures?

There are several advantages of using stored procedures in SQL:

  1. Improved Performance: Stored procedures are pre-compiled and stored in the database, which reduces the overhead of parsing and optimizing SQL statements each time they are executed.

  2. Enhanced Security: Stored procedures can be used to control access to the database by granting permissions only to execute the stored procedures, rather than directly accessing the tables.

  3. Code Reusability: Stored procedures can be called from multiple applications or scripts, promoting code reusability and reducing code duplication.

  4. Simplified Maintenance: By encapsulating complex SQL logic into stored procedures, it becomes easier to maintain and update the database code.

  5. Transaction Management: Stored procedures can be used to define and manage transactions, ensuring data integrity and consistency.

Follow-up 3

Can you provide an example of a stored procedure?

Sure! Here's an example of a stored procedure in SQL that retrieves all employees from a table:

CREATE PROCEDURE GetEmployees
AS
BEGIN
    SELECT * FROM Employees;
END

This stored procedure named 'GetEmployees' does not accept any parameters and simply selects all rows from the 'Employees' table.

Follow-up 4

How can we modify an existing stored procedure?

To modify an existing stored procedure in SQL, you can use the ALTER PROCEDURE statement. Here's an example:

ALTER PROCEDURE GetEmployees
AS
BEGIN
    SELECT * FROM Employees WHERE Salary > 50000;
END

In this example, we modified the 'GetEmployees' stored procedure to include a filter condition to only retrieve employees with a salary greater than 50000.

2. How do you create a stored procedure in SQL?

Syntax varies by database, but the core structure is consistent: define a name, optional parameters, and a body of SQL statements.

SQL Server (T-SQL):

CREATE PROCEDURE GetEmployeesByDept
    @dept_id    INT,
    @min_salary DECIMAL(10,2) = 0  -- default value
AS
BEGIN
    SET NOCOUNT ON;
    SELECT employee_id, first_name, salary
    FROM employees
    WHERE department_id = @dept_id
      AND salary >= @min_salary
    ORDER BY salary DESC;
END;
GO

MySQL:

DELIMITER //
CREATE PROCEDURE GetEmployeesByDept(
    IN  p_dept_id    INT,
    IN  p_min_salary DECIMAL(10,2),
    OUT p_count      INT
)
BEGIN
    SELECT employee_id, first_name, salary
    FROM employees
    WHERE department_id = p_dept_id
      AND salary >= p_min_salary;

    SELECT COUNT(*) INTO p_count
    FROM employees
    WHERE department_id = p_dept_id;
END //
DELIMITER ;

PostgreSQL:

CREATE OR REPLACE PROCEDURE GetEmployeesByDept(
    p_dept_id    INT,
    p_min_salary DECIMAL DEFAULT 0
)
LANGUAGE plpgsql AS $$
BEGIN
    -- PostgreSQL procedures cannot return result sets directly;
    -- use functions with RETURNS TABLE or RETURNS SETOF for that
    UPDATE employees SET last_accessed = NOW()
    WHERE department_id = p_dept_id;
    COMMIT;
END;
$$;

Key elements:

  • IN parameters: values passed into the procedure
  • OUT parameters: values returned by the procedure (SQL Server, MySQL, Oracle)
  • INOUT parameters: passed in and modified (MySQL, Oracle)
  • OR REPLACE: overwrites existing definition without dropping first (PostgreSQL, MySQL, Oracle)
  • GO (SQL Server): batch separator, not part of the procedure definition
↑ Back to top

Follow-up 1

What is the syntax for creating a stored procedure?

The syntax for creating a stored procedure in SQL is as follows:

CREATE PROCEDURE procedure_name
    [parameter1 data_type [ = default_value ] [ OUT | OUTPUT ] ]
    [,...n]
AS
    SQL_statements
GO

The CREATE PROCEDURE statement is followed by the name of the procedure, optional parameters, and the SQL statements that make up the procedure's logic. The GO keyword is used to execute the statement.

Follow-up 2

Can you provide a step-by-step process for creating a stored procedure?

Sure! Here is a step-by-step process for creating a stored procedure in SQL:

  1. Open your SQL client or editor.
  2. Connect to the database where you want to create the stored procedure.
  3. Write the CREATE PROCEDURE statement with the desired name for the procedure.
  4. Define any input or output parameters for the procedure.
  5. Write the SQL statements that make up the logic of the procedure.
  6. Use the GO keyword to execute the CREATE PROCEDURE statement.

That's it! Your stored procedure is now created and ready to be executed.

Follow-up 3

What are some common errors that can occur when creating a stored procedure and how can they be resolved?

When creating a stored procedure in SQL, you may encounter some common errors. Here are a few examples and how to resolve them:

  1. Syntax errors: Double-check the syntax of your CREATE PROCEDURE statement and make sure it follows the correct format.
  2. Missing or incorrect parameter declarations: Ensure that you have declared all the necessary parameters and that their data types and names match the intended usage.
  3. Invalid SQL statements: Review the SQL statements within the procedure and verify that they are valid and will produce the desired results.

To resolve these errors, carefully review your code, consult the SQL documentation, and use debugging techniques such as printing intermediate results or using a SQL debugger if available.

3. How do you call a stored procedure in SQL?

SQL Server / T-SQL:

-- Using EXECUTE (or EXEC shorthand)
EXEC GetEmployeesByDept @dept_id = 10, @min_salary = 70000;

-- Positional parameters
EXEC GetEmployeesByDept 10, 70000;

-- Capturing an OUTPUT parameter
DECLARE @emp_count INT;
EXEC GetEmployeesByDept @dept_id = 10, @min_salary = 0, @count = @emp_count OUTPUT;
PRINT @emp_count;

MySQL:

CALL GetEmployeesByDept(10, 70000, @emp_count);
SELECT @emp_count;  -- retrieve OUT parameter value

PostgreSQL:

-- For stored procedures (CALL, PostgreSQL 11+)
CALL GetEmployeesByDept(10, 70000);

-- For functions (used in SELECT or via PERFORM inside PL/pgSQL)
SELECT * FROM GetEmployeesByDeptFunc(10, 70000);

Oracle:

EXEC GetEmployeesByDept(10, 70000);
-- Or inside PL/SQL:
BEGIN
    GetEmployeesByDept(10, 70000);
END;

Key distinctions:

  • SQL Server uses EXEC / EXECUTE
  • MySQL and PostgreSQL use CALL
  • Oracle uses EXEC in SQL*Plus or BEGIN...END blocks
  • In PostgreSQL, CALL is for procedures; functions are called with SELECT or within SQL expressions

Interview note: In PostgreSQL, procedures (using CALL) and functions (using SELECT) are distinct. A procedure can contain COMMIT/ROLLBACK; a function cannot (it runs within the caller's transaction). This distinction was introduced in PostgreSQL 11.

↑ Back to top

Follow-up 1

What is the syntax for calling a stored procedure?

The syntax for calling a stored procedure in SQL is as follows:

EXECUTE procedure_name;

or

EXEC procedure_name parameter1, parameter2, ...;

Follow-up 2

Can you provide an example of calling a stored procedure?

Sure! Here's an example of calling a stored procedure named GetCustomerDetails with two parameters @customerId and @startDate:

EXEC GetCustomerDetails @customerId = 123, @startDate = '2022-01-01';

Follow-up 3

What happens if a stored procedure that does not exist is called?

If a stored procedure that does not exist is called, an error will be thrown indicating that the procedure does not exist. You will need to make sure that the procedure name is spelled correctly and that it exists in the database.

4. What is the role of parameters in a stored procedure?

Parameters in a stored procedure serve as the interface between the calling code and the procedure's internal logic. They make procedures flexible and reusable across different inputs.

Three parameter modes:

IN parameters (input only — the default in most databases) Pass a value into the procedure. The procedure can read it but modifications to the parameter do not affect the caller.

CREATE PROCEDURE raise_salary(IN p_emp_id INT, IN p_pct DECIMAL)

OUT parameters (output only) Return a value from the procedure to the caller. The procedure sets the value; the initial value passed in is ignored.

CREATE PROCEDURE get_headcount(IN p_dept INT, OUT p_count INT)
-- Caller: CALL get_headcount(5, @count); SELECT @count;

INOUT parameters (bidirectional) The caller provides an initial value that the procedure can read and modify. The modified value is returned.

CREATE PROCEDURE apply_discount(INOUT p_price DECIMAL, IN p_pct DECIMAL)

Default values (SQL Server):

CREATE PROCEDURE search_employees
    @dept_id    INT = NULL,
    @min_salary DECIMAL = 0
AS ...
-- EXEC search_employees  -- uses defaults
-- EXEC search_employees @dept_id = 5  -- overrides one default

Best practices:

  • Use IN parameters for filters and configuration
  • Use OUT parameters to return counts, generated IDs, or status codes
  • Avoid INOUT when IN + OUT is clearer
  • Validate input parameters at the start of the procedure and raise an error for invalid inputs
↑ Back to top

Follow-up 1

Can you explain the difference between input and output parameters in a stored procedure?

In a stored procedure, input parameters are used to pass values into the procedure. These values are used by the procedure to perform calculations or operations. Output parameters, on the other hand, are used to return values from the procedure back to the calling code. The calling code can then use these values for further processing.

Follow-up 2

How do you pass parameters to a stored procedure?

Parameters can be passed to a stored procedure in multiple ways. One way is to specify the parameter values when calling the procedure. Another way is to declare variables in the calling code and assign values to them before calling the procedure. These variables can then be used as parameter values when calling the procedure. Additionally, parameters can also be passed using named parameters, where the parameter values are specified by name rather than by position.

Follow-up 3

Can a stored procedure have no parameters?

Yes, a stored procedure can have no parameters. In such cases, the procedure may not require any input values and may not return any output values. It can simply perform a series of operations or calculations without the need for external input or output.

5. How can stored procedures improve the performance of SQL queries?

Stored procedures can improve query performance through several mechanisms, but it is important to understand when and why:

1. Execution plan caching (the primary benefit) The first time a stored procedure is called, the database parses the SQL, generates an execution plan, and caches it. Subsequent calls reuse the cached plan — eliminating the parse/compile overhead.

Ad-hoc queries may be cached too (in SQL Server with "optimize for ad-hoc workloads"), but procedures provide more predictable plan reuse.

2. Reduced network round-trips A single CALL procedure_name(params) replaces sending multiple SQL statements across the network. This matters for high-latency connections or when many small statements would otherwise be batched.

3. Parameter sniffing (a nuance — not always a benefit) SQL Server generates a plan based on the first set of parameter values used to call the procedure. This plan may be optimal for those values but suboptimal for other values (parameter sniffing problem). Mitigations include OPTION (RECOMPILE) or OPTIMIZE FOR UNKNOWN.

4. Reduced permission overhead Applications can be granted EXECUTE on a procedure rather than SELECT/UPDATE on tables directly, simplifying permission checks at runtime.

5. Server-side execution Logic runs on the database server — reducing data transfer when only summary results are needed by the client.

What stored procedures do NOT guarantee:

  • They don't automatically improve a poorly written query inside them
  • A bad execution plan cached for a procedure can hurt performance for some parameter combinations
  • In PostgreSQL, plan caching for PREPARE/stored functions uses generic plans after 5 executions, which may be less optimal than custom plans

Modern context (2026): Many ORMs and query builders use parameterized queries with prepared statements, which provide similar plan caching benefits without stored procedures.

↑ Back to top

Follow-up 1

How does the use of stored procedures affect the execution time of SQL queries?

The use of stored procedures can potentially improve the execution time of SQL queries. Since stored procedures are precompiled and stored in the database, they can have an optimized execution plan. This means that the database engine can skip the process of parsing and optimizing the query each time it is executed, resulting in faster execution times. Additionally, database systems often cache the execution plans of frequently executed stored procedures, further improving performance for subsequent executions.

Follow-up 2

Can stored procedures be used to prevent SQL injection attacks?

Yes, stored procedures can be used to prevent SQL injection attacks. When using stored procedures, the input parameters are typically passed as parameters to the stored procedure, rather than being concatenated directly into the SQL query. This parameterization helps to prevent SQL injection attacks, as the database engine treats the input parameters as data rather than executable code. By using parameterized queries within stored procedures, the database can validate and sanitize the input values, reducing the risk of SQL injection.

Follow-up 3

What are some best practices for optimizing stored procedures?

Here are some best practices for optimizing stored procedures:

  1. Keep it simple: Try to keep the logic within a stored procedure as simple as possible. Complex logic can make it harder for the database engine to optimize the execution plan.

  2. Avoid unnecessary operations: Only include the necessary operations and calculations within the stored procedure. Unnecessary operations can slow down the execution time.

  3. Use appropriate data types: Choose the appropriate data types for the input parameters and variables within the stored procedure. Using smaller data types can help reduce memory usage and improve performance.

  4. Indexing: Consider adding indexes to the tables used within the stored procedure. Indexes can improve query performance by allowing the database engine to quickly locate the required data.

  5. Testing and monitoring: Regularly test and monitor the performance of stored procedures. This can help identify any bottlenecks or areas for optimization.

Live mock interview

Mock interview: SQL Stored Procedures

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.