Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
BEGIN SELECT * FROM employees WHERE id = @emp_id; END; PostgreSQL: CREATE OR REPLACE FUNCTION GetEmployeeDetails(emp_id INT) RETURNS TABLE(id INT, name VARCHAR) AS $$ BEGIN RETURN QUERY SELECT id, name FROM employees WHE…
SQL Server: CREATE PROCEDURE GetEmployeeDetails (@emp_id INT) BEGIN SELECT * FROM employees WHERE id = @emp_id; END; PostgreSQL: CREATE OR REPLACE FUNCTION GetEmployeeDetails(emp_id INT) RETURNS TABLE(id INT, name VARCHA…
Performance: Stored procedures are precompiled, so execution is faster compared to running individual SQL queries each time. Code Reusability: Once defined, stored procedures can be reused in multiple places, reducing re…
BEGIN SELECT salary FROM employees WHERE id = @emp_id; END; Calling the procedure: EXEC GetEmployeeSalary @emp_id = 101; MySQL: DELIMITER // CREATE PROCEDURE GetEmployeeSalary(IN emp_id INT) BEGIN SELECT salary FROM empl…
Stored procedures allow you to pass parameters to them, either input or output parameters. Input Parameters: These allow you to send data to the procedure. Output Parameters: These allow the procedure to send data back t…
Function: Return Type: Always returns a value (can be scalar or table). Used in Queries: Can be used in SELECT, WHERE, and ORDER BY clauses. Side Effects: Typically designed to perform calculations or return a result wit…
Error handling is an essential part of stored procedures. Here’s how you handle errors in different databases: SQL Server: Use TRY...CATCH blocks to handle errors. BEGIN TRY - Some SQL operation INSERT INTO employees (na…
You can call stored procedures from programming languages using appropriate database connectors and drivers. Example (C# with SQL Server): using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); u…
wait conn.OpenAsync(); using (SqlCommand cmd = new SqlCommand("GetEmployeeDetails", conn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@emp_id", SqlDbType.Int)).Value = 101; usin…
Executing stored procedures asynchronously can improve the performance of applications by allowing other tasks to run while waiting for the procedure to finish. Example (C#): using (SqlConnection conn = new SqlConnection…
Vendor Lock-In: Stored procedures use database-specific syntax, making it harder to migrate to different database platforms. Complexity: As business logic grows within stored procedures, they can become difficult to main…
Answer: Debugging stored procedures can be done in the following ways: SQL Server: SQL Server Management Studio (SSMS) allows you to set breakpoints, step through the code, and inspect variable values during execution. S…
Stored Procedures: The RETURN keyword in a stored procedure is typically used to exit the procedure and can optionally return an integer value (usually indicating the success or failure of the procedure). The return valu…
n index in SQL is a database object that improves the speed of data retrieval operations on a table. It works by maintaining a sorted order of column values in a separate structure, llowing for faster search and retrieva…
Indexes improve query performance in several ways: What interviewers expect A clear definition tied to SQL in SQL & Databases projects Trade-offs (performance, maintainability, security, cost) When you would and woul…
There are several types of indexes in SQL: Unique Index: Ensures that all values in the indexed column(s) are unique. Automatically created when a PRIMARY KEY or UNIQUE constraint is defined on a column. Example: CREATE…
Answer: Creating an Index: CREATE INDEX idx_index_name ON table_name(column_name); Dropping an Index: DROP INDEX idx_index_name ON table_name; In SQL Server, dropping an index: DROP INDEX idx_index_name; -- No need to sp…
Clustered Index: The data in the table is physically sorted based on the clustered index. Each table can have only one clustered index (usually the primary key). Fast for queries that involve range-based retrieval (e.g.,…
Indexes can slow down data modification operations: INSERT: When a new row is inserted, the index must also be updated to include the new value, adding extra overhead. UPDATE: If the indexed column is updated, the index…
Consider creating an index when: What interviewers expect A clear definition tied to SQL in SQL & Databases projects Trade-offs (performance, maintainability, security, cost) When you would and would not use it in pr…
composite index is an index that is created on multiple columns. It is used when a query filters or sorts based on more than one column. Composite indexes are especially useful when queries frequently involve conditions…
Unique Index: Ensures that the values in the indexed columns are unique. Can be created on any column and allows NULL values (in most DBMS). A table can have multiple unique indexes. Primary Key Index: Enforces the uniqu…
Answer: The query optimizer in the database engine decides which index to use based on several factors: What interviewers expect A clear definition tied to SQL in SQL & Databases projects Trade-offs (performance, mai…
covering index is an index that contains all the columns needed by a query, meaning the query can be answered entirely by the index without accessing the actual table data. This can improve query performance by reducing…
Answer: Index fragmentation occurs when data is inserted, updated, or deleted, causing the index structure to become inefficient. This can negatively impact performance in several ways: What interviewers expect A clear d…
SQL & Databases SQL Server Tutorial · SQL
BEGIN
SELECT * FROM employees WHERE id = @emp_id;
END;
CREATE OR REPLACE FUNCTION GetEmployeeDetails(emp_id INT)
RETURNS TABLE(id INT, name VARCHAR) AS $$
BEGIN
RETURN QUERY SELECT id, name FROM employees WHERE id = emp_id;
END;
$$ LANGUAGE plpgsql;
DELIMITER //
CREATE PROCEDURE GetEmployeeDetails(IN emp_id INT)
BEGIN
SELECT * FROM employees WHERE id = emp_id;
END //
DELIMITER ;
SQL & Databases SQL Server Tutorial · SQL
SQL Server:
CREATE PROCEDURE GetEmployeeDetails (@emp_id INT)
BEGIN
SELECT * FROM employees WHERE id = @emp_id;
END;
PostgreSQL:
CREATE OR REPLACE FUNCTION GetEmployeeDetails(emp_id INT)
RETURNS TABLE(id INT, name VARCHAR) AS $$
BEGIN
RETURN QUERY SELECT id, name FROM employees WHERE id = emp_id;
END;
$$ LANGUAGE plpgsql;
MySQL:
DELIMITER //
CREATE PROCEDURE GetEmployeeDetails(IN emp_id INT)
BEGIN
SELECT * FROM employees WHERE id = emp_id;
END //
DELIMITER ;
The syntax varies slightly between the databases, but the core idea remains the same.
SQL & Databases SQL Server Tutorial · SQL
to running individual SQL queries each time.
places, reducing redundancy.
giving them direct access to the underlying tables.
maintenance easier, especially when making changes to the logic.
like TRY...CATCH in SQL Server or EXCEPTION in PostgreSQL.
SQL & Databases SQL Server Tutorial · SQL
BEGIN
SELECT salary FROM employees WHERE id = @emp_id;
END;
EXEC GetEmployeeSalary @emp_id = 101;
DELIMITER //
CREATE PROCEDURE GetEmployeeSalary(IN emp_id INT)
BEGIN
SELECT salary FROM employees WHERE id = emp_id;
END //
DELIMITER ;
CALL GetEmployeeSalary(101);
SQL & Databases SQL Server Tutorial · SQL
Stored procedures allow you to pass parameters to them, either input or output
parameters.
Example:
SQL Server:
CREATE PROCEDURE GetEmployeeSalary (@emp_id INT)
BEGIN
SELECT salary FROM employees WHERE id = @emp_id;
END;
Calling the procedure:
EXEC GetEmployeeSalary @emp_id = 101;
MySQL:
DELIMITER //
CREATE PROCEDURE GetEmployeeSalary(IN emp_id INT)
BEGIN
SELECT salary FROM employees WHERE id = emp_id;
END //
DELIMITER ;
Calling the procedure:
CALL GetEmployeeSalary(101);
SQL & Databases SQL Server Tutorial · SQL
without modifying the database.
result sets).
INSERT, UPDATE, DELETE).
business logic.
Example:
Function (returns a value):
CREATE FUNCTION GetEmployeeSalary (emp_id INT) RETURNS DECIMAL
BEGIN
RETURN (SELECT salary FROM employees WHERE id = emp_id);
END;
CREATE PROCEDURE UpdateEmployeeSalary (IN emp_id INT, IN new_salary
DECIMAL)
BEGIN
UPDATE employees SET salary = new_salary WHERE id = emp_id;
END;
SQL & Databases SQL Server Tutorial · SQL
Error handling is an essential part of stored procedures. Here’s how you handle errors in
different databases:
SQL Server: Use TRY...CATCH blocks to handle errors.
BEGIN TRY
INSERT INTO employees (name) VALUES ('John Doe');
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
BEGIN
INSERT INTO employees (name) VALUES ('John Doe');
EXCEPTION
WHEN others THEN
RAISE NOTICE 'Error occurred: %', SQLERRM;
END;
DECLARE...HANDLER.
DELIMITER //
CREATE PROCEDURE ExampleProcedure()
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
SELECT 'An error occurred';
INSERT INTO employees (name) VALUES ('John Doe');
END //
DELIMITER ;
SQL & Databases SQL Server Tutorial · SQL
You can call stored procedures from programming languages using appropriate database
connectors and drivers.
Example (C# with SQL Server):
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("GetEmployeeDetails",
conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@emp_id",
SqlDbType.Int)).Value = 101;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["name"]);
}
}
}
}SQL & Databases SQL Server Tutorial · SQL
wait conn.OpenAsync();
using (SqlCommand cmd = new SqlCommand("GetEmployeeDetails",
conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@emp_id",
SqlDbType.Int)).Value = 101;
using (SqlDataReader reader = await
cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
Console.WriteLine(reader["name"]);
}
}
}
}SQL & Databases SQL Server Tutorial · SQL
Executing stored procedures asynchronously can improve the performance of applications
by allowing other tasks to run while waiting for the procedure to finish.
Example (C#):
using (SqlConnection conn = new SqlConnection(connectionString))
await conn.OpenAsync();
using (SqlCommand cmd = new SqlCommand("GetEmployeeDetails",
conn))
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@emp_id",
SqlDbType.Int)).Value = 101;
using (SqlDataReader reader = await
cmd.ExecuteReaderAsync())
while (await reader.ReadAsync())
Console.WriteLine(reader["name"]);
SQL & Databases SQL Server Tutorial · SQL
to migrate to different database platforms.
difficult to maintain and debug.
hurt performance.
code, and they cannot easily handle more complex logic that might be easier in a
high-level programming language.
application code.
SQL & Databases SQL Server Tutorial · SQL
Answer: Debugging stored procedures can be done in the following ways: SQL Server: SQL Server Management Studio (SSMS) allows you to set breakpoints, step through the code, and inspect variable values during execution. Steps:
In a production SQL & Databases application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
SQL & Databases SQL Server Tutorial · SQL
exit the procedure and can optionally return an integer value (usually indicating the
success or failure of the procedure). The return value is often used for error handling
or status reporting.
Indexing
SQL & Databases SQL Server Tutorial · SQL
n index in SQL is a database object that improves the speed of data retrieval operations
on a table. It works by maintaining a sorted order of column values in a separate structure,
llowing for faster search and retrieval compared to scanning every row in the table. The
index essentially creates a quick lookup table to find specific values.
Example of an index creation:
CREATE INDEX idx_column_name ON table_name(column_name);
Indexes are particularly useful for queries that involve WHERE, JOIN, ORDER BY, and GROUP
BY clauses.
SQL & Databases SQL Server Tutorial · SQL
Indexes improve query performance in several ways:
In a production SQL & Databases application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
SQL & Databases SQL Server Tutorial · SQL
There are several types of indexes in SQL:
Unique Index: Ensures that all values in the indexed column(s) are unique. Automatically
created when a PRIMARY KEY or UNIQUE constraint is defined on a column.
Example:
CREATE UNIQUE INDEX idx_employee_id ON employees(id);
like full-text searches (e.g., MATCH in MySQL).
Example (MySQL):
CREATE FULLTEXT INDEX idx_fulltext_desc ON products(description);
index. Each table can have only one clustered index.
indexed columns and pointers to the actual data rows. A table can have multiple
non-clustered indexes.
filter based on multiple columns.
polygons (mostly for geographical data).
SQL & Databases SQL Server Tutorial · SQL
Answer: Creating an Index: CREATE INDEX idx_index_name ON table_name(column_name); Dropping an Index: DROP INDEX idx_index_name ON table_name; In SQL Server, dropping an index: DROP INDEX idx_index_name; -- No need to specify table name.
In a production SQL & Databases application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
SQL & Databases SQL Server Tutorial · SQL
BY).
stored separately from the actual data.
range-based searches.
SQL & Databases SQL Server Tutorial · SQL
Indexes can slow down data modification operations:
new value, adding extra overhead.
new value, which can be slower.
causing additional overhead.
While indexes speed up SELECT queries, they can reduce the performance of INSERT,
UPDATE, and DELETE operations due to the extra work needed to maintain the index.
SQL & Databases SQL Server Tutorial · SQL
Consider creating an index when:
In a production SQL & Databases application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
SQL & Databases SQL Server Tutorial · SQL
composite index is an index that is created on multiple columns. It is used when a query
filters or sorts based on more than one column. Composite indexes are especially useful
when queries frequently involve conditions on multiple columns.
creating a composite index on (last_name, first_name) will speed up the
query.
Example of creating a composite index:
CREATE INDEX idx_lastname_firstname ON employees(last_name,
first_name);
SQL & Databases SQL Server Tutorial · SQL
constraint on the column(s).
In short, both enforce uniqueness, but the primary key also guarantees that the column(s)
cannot be NULL.
SQL & Databases SQL Server Tutorial · SQL
Answer: The query optimizer in the database engine decides which index to use based on several factors:
In a production SQL & Databases application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
SQL & Databases SQL Server Tutorial · SQL
covering index is an index that contains all the columns needed by a query, meaning the
query can be answered entirely by the index without accessing the actual table data. This
can improve query performance by reducing disk I/O.
Example:
If a query selects id, name, and salary from the employees table and there is an index
on (id, name, salary), the index itself is sufficient to satisfy the query, and the
database doesn't need to access the table at all.
SQL & Databases SQL Server Tutorial · SQL
Answer: Index fragmentation occurs when data is inserted, updated, or deleted, causing the index structure to become inefficient. This can negatively impact performance in several ways:
In a production SQL & Databases application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.