Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.
SQL Server Tutorial · SQL queries
Short answer: SQL queries is essential when working with SQL Server Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
SQL Server Tutorial · Schema design
Short answer: Schema design is essential when working with SQL Server Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
SQL Server Tutorial · Transactions
Short answer: Transactions is essential when working with SQL Server Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
SQL Server Tutorial · Indexing
Short answer: Indexing is essential when working with SQL Server Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
SQL Server Tutorial · Normalization
Short answer: Normalization is essential when working with SQL Server Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.
Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.
SQL & Databases SQL Server Tutorial · SQL
schema changes. These tools allow you to write migrations in SQL or as
scripts that can be version-controlled.
SQL & Databases SQL Server Tutorial · SQL
single database server.
existing server.
also increases the risk of downtime during upgrades.
SQL & Databases SQL Server Tutorial · SQL
tenant_id) is used to segregate data.
SQL & Databases SQL Server Tutorial · SQL
multiple records in another table.
to only one Customer.
SQL & Databases SQL Server Tutorial · SQL
conditions, and ORDER BY clauses.
SQL & Databases SQL Server Tutorial · SQL
identify slow queries.
SQL & Databases SQL Server Tutorial · SQL
shards. Each shard is stored on a different server (or cluster) to distribute the
load.
than columns) of a database table are distributed across multiple databases.
1-1000 are stored in one database, 1001-2000 in another, and so on.
SQL & Databases SQL Server Tutorial · SQL
databases (slaves) replicate the data for read queries and redundancy.
SQL & Databases SQL Server Tutorial · SQL
run daily, weekly, or at specific intervals.
Script for automated backups:
BACKUP DATABASE MyDatabase TO DISK = 'C:\Backups\MyDatabase.bak';
SQL & Databases SQL Server Tutorial · SQL
taken. It is a complete snapshot of the database.
backup types.
weekly.
SQL & Databases SQL Server Tutorial · SQL
data.
Encryption, PostgreSQL using pg_dump with -Fc and encrypting the output
file).
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
GROUP BY clauses are good candidates for indexing.
SQL & Databases SQL Server Tutorial · SQL
redundancy by eliminating unnecessary duplication.
SQL & Databases SQL Server Tutorial · SQL
more likely it is to be chosen. The optimizer prefers indexes that significantly reduce
the number of rows processed.
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
SQL & Databases SQL Server Tutorial · SQL
Structured Query Language (SQL) for defining and manipulating data. They store
data in tables with rows and columns. SQL databases enforce a strict schema,
meaning the structure of the data must be defined beforehand.
Examples: MySQL, PostgreSQL, SQL Server, Oracle
and allow storage of unstructured or semi-structured data. They don't require a fixed
schema and are often used for large-scale applications where flexibility, scalability,
and speed are more important than the strict relational model.
Examples: MongoDB, Cassandra, CouchDB, Firebase
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
SQL & Databases SQL Server Tutorial · SQL
read and write operations on any node.
simultaneously on multiple nodes.
SQL & Databases SQL Server Tutorial · SQL
Example (Linux):
0 3 * * * pg_dump -U postgres mydatabase >
/path/to/backup/mydatabase_$(date +\%Y\%m\%d).sql
SQL & Databases SQL Server Tutorial · SQL
It does not depend on other differential backups.
backups.
between full backups.
taken on Wednesday would include all changes since Monday.
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
access-controlled locations, ideally offsite or in the cloud (e.g., AWS S3, Azure Blob
Storage).
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
matched rows from the right table. If there’s no match, NULL is returned for the right
table.
SQL & Databases SQL Server Tutorial · SQL
change is applied in a sequential, ordered fashion.
SQL & Databases SQL Server Tutorial · SQL
on the primary key. Remove partial dependencies (when a non-key attribute depends
on part of a composite key).
SQL & Databases SQL Server Tutorial · SQL
WHERE, JOIN, ORDER BY, and GROUP BY clauses to choose the most appropriate
index.
SQL & Databases SQL Server Tutorial · SQL
data are important.
Isolation, Durability) properties, making them ideal for applications where data
integrity is crucial, such as banking systems.
subqueries, and aggregations.
robust set of features, tools, and community support.
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
same tables but is isolated per tenant.
SQL & Databases SQL Server Tutorial · SQL
SQL & Databases SQL Server Tutorial · SQL
Prometheus, Grafana, or cloud-specific monitoring tools like AWS
CloudWatch or Azure Monitor.
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
multiple associations with each other.
have many Students. This would typically be modeled using a junction table
like Student_Course.
SQL & Databases SQL Server Tutorial · SQL
make queries faster.
single query.
SQL & Databases SQL Server Tutorial · SQL
replication.
SQL & Databases SQL Server Tutorial · SQL
same type of data (e.g., storing multiple phone numbers in separate columns).
SQL & Databases SQL Server Tutorial · SQL
chunks rather than all at once.
SQL & Databases SQL Server Tutorial · SQL
data as required.
SQL & Databases SQL Server Tutorial · SQL
on another non-key attribute). Ensure that no non-key attribute is dependent on
another non-key attribute.
For example:
Employee_ID Employee_Nam
Department Department_Manager
1 Alice HR John
2 Bob IT Sarah
employees and departments.
on Department, not directly on Employee, so it should be moved to a separate table
for Departments.
SQL & Databases SQL Server Tutorial · SQL
dynamic and can vary over time.
weight, but some products may not have all attributes, so you store them as
key-value pairs.
SQL & Databases SQL Server Tutorial · SQL
SQL & Databases SQL Server Tutorial · SQL
ACID stands for:
none are. If one part of a transaction fails, the whole transaction fails.
rules, including constraints, after a transaction.
one transaction does not interfere with another.
case of system failures.
SQL & Databases SQL Server Tutorial · SQL
I/O, CPU, etc.) and chooses the one with the lowest cost.
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
Example: SaaS applications often use multi-tenancy to serve multiple clients with the same
infrastructure while keeping data separated.
SQL & Databases SQL Server Tutorial · SQL
different environments to ensure smooth deployment.
SQL & Databases SQL Server Tutorial · SQL
to retrieve data.
To resolve this, indexes can be reorganized or rebuilt to improve their performance.
SQL & Databases SQL Server Tutorial · SQL
the database can use the index to quickly find matching rows.
SQL & Databases SQL Server Tutorial · SQL
the last transaction log backup. It allows point-in-time recovery.
(assuming all previous logs are available).
full recovery.
moment in time by replaying the logs up to that point.
SQL & Databases SQL Server Tutorial · SQL
matched rows from the left table. If there’s no match, NULL is returned for the left
table.
SQL & Databases SQL Server Tutorial · SQL
load, typically using replication, sharding, or clustering.
workload is distributed across multiple servers.
specialized techniques like load balancing and data partitioning.
SQL & Databases SQL Server Tutorial · SQL
and cache usage to monitor the internal database performance.
SQL & Databases SQL Server Tutorial · SQL
NOTICE for debugging or use third-party tools like pgAdmin for debugging.
stepping through the stored procedure and monitoring execution.
Example (PostgreSQL):
RAISE NOTICE 'Debugging variable: %', my_variable;
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
responsibilities.
Example (SQL Server):
CREATE ROLE Manager;
GRANT SELECT, UPDATE ON Employees TO Manager;
EXEC sp_addrolemember 'Manager', 'john_doe';
In PostgreSQL or MySQL, you would follow similar steps using GRANT statements and role
management commands.
SQL & Databases SQL Server Tutorial · SQL
Trade-offs:
availability will fail during network partitions.
partition tolerance may not be available during network issues.
partition tolerance may return stale data.
SQL & Databases SQL Server Tutorial · SQL
files.
SQL & Databases SQL Server Tutorial · SQL
secondary databases after a delay.
failure.
Tools for Replication:
Example (PostgreSQL Streaming Replication):
# On Master Node
wal_level = replica
archive_mode = on
archive_command = 'cp %p /var/lib/postgresql/archive/%f'
# On Standby Node
primary_conninfo = 'host=master_ip port=5432 user=replication_user
password=replication_password'
Database Scaling & Performance
SQL & Databases SQL Server Tutorial · SQL
cloud environments. These platforms allow automatic backup scheduling
without manual intervention.
backups for a configurable retention period.
SQL & Databases SQL Server Tutorial · SQL
and recovery procedures to verify data integrity.
Example (SQL Server):
BACKUP DATABASE MyDatabase TO DISK = 'D:\Backups\MyDatabase.bak'
WITH ENCRYPTION (ALGORITHM = AES_256, SERVER CERTIFICATE = MyCert);
Restoration Example:
RESTORE DATABASE MyDatabase FROM DISK = 'D:\Backups\MyDatabase.bak'
WITH FILE = 1, NOUNLOAD, STATS = 10;
Additional Best Practices:
data that has changed since the last backup.
properly archived or deleted.
Backup & Recovery
SQL & Databases SQL Server Tutorial · SQL
the need for complex joins, and speeding up read queries.
SQL & Databases SQL Server Tutorial · SQL
overwhelming the system.
SQL & Databases SQL Server Tutorial · SQL
performance.
SQL & Databases SQL Server Tutorial · SQL
with primary keys and referential integrity rather than repeating the data.
SQL & Databases SQL Server Tutorial · SQL
available. If there’s no match, NULL is returned for the missing side.
SQL & Databases SQL Server Tutorial · SQL
tools like MySQL Workbench or SQL Server Integration Services (SSIS)
can be used. For NoSQL, tools like MongoDB Compass or Data Migration
Tools can be utilized.
SQL & Databases SQL Server Tutorial · SQL
an index on the filtering columns can improve performance.
SQL & Databases SQL Server Tutorial · SQL
of data from disk.
In summary, indexes drastically speed up SELECT queries at the cost of increased overhead
during INSERT, UPDATE, and DELETE operations.
SQL & Databases SQL Server Tutorial · SQL
fragmentation, and distribution of data to make its decision.
SQL & Databases SQL Server Tutorial · SQL
a table can have the same primary key value. It ensures entity integrity.
Example: user_id in a users table.
row of another table. It establishes a relationship between two tables and enforces
referential integrity.
Example: user_id in an orders table linking to user_id in the users table.
SQL & Databases SQL Server Tutorial · SQL
rows).
SQL & Databases SQL Server Tutorial · SQL
frequently accessed data, and using denormalization where appropriate.
NoSQL (MongoDB - Optional)
SQL & Databases SQL Server Tutorial · SQL
performing data checks (e.g., record counts, sampling).
SQL & Databases SQL Server Tutorial · SQL
They work like the index in a book, allowing quick lookup of data without having to
scan the entire table.
Importance:
retrieval.
SQL & Databases SQL Server Tutorial · SQL
read replicas.
Tools for Monitoring:
STATUS (for MySQL), or SQL Server Profiler for SQL Server.
SQL & Databases SQL Server Tutorial · SQL
used repeatedly across the database.
then referenced by other tables like Customers or Employees.
SQL & Databases SQL Server Tutorial · SQL
Rewrite queries using joins or CTEs (Common Table Expressions).
SQL & Databases SQL Server Tutorial · SQL
Why is it important?
redundancy and dependency by dividing large tables into smaller ones and linking
them with relationships.
Importance:
entire system.
SQL & Databases SQL Server Tutorial · SQL
query to leverage more efficient join algorithms.
SQL & Databases SQL Server Tutorial · SQL
full table scans) and refactor accordingly.
Advanced Topics
SQL & Databases SQL Server Tutorial · SQL
A database schema is the structure that defines the organization of data in a database. It
includes definitions of tables, relationships, indexes, constraints, and other elements.
SQL & Databases SQL Server Tutorial · SQL
Can you give examples?
Database Constraints are rules applied to ensure the integrity and accuracy of the data
within a database. Examples include:
another table.
SQL & Databases SQL Server Tutorial · SQL
Referential integrity ensures that relationships between tables remain consistent.
Specifically, it guarantees that foreign keys in a table must match primary keys in another
table, or they must be NULL.
SQL & Databases SQL Server Tutorial · SQL
A trigger is a special kind of stored procedure that is automatically executed or fired when
certain events occur in a database, such as INSERT, UPDATE, or DELETE.
Example: A trigger that automatically updates a timestamp field every time a row is modified.
SQL & Databases SQL Server Tutorial · SQL
Microsoft products. It’s commonly used in enterprise environments.
compliance, extensibility, and advanced features like support for complex queries,
JSONB, and custom data types.
It's often used in web applications (e.g., with PHP) and is less feature-rich than
PostgreSQL but highly reliable.
SQL & Databases SQL Server Tutorial · SQL
A view is a virtual table created by querying data from one or more tables. It does not store
data itself but presents it in a specific format.
Use cases:
reuse.
giving them full table access.
SQL & Databases SQL Server Tutorial · SQL
and vice versa. This often requires a junction table.
SQL & Databases SQL Server Tutorial · SQL
one clustered index because the rows can only be ordered in one way.
pointers to the data. A table can have multiple non-clustered indexes.
SQL & Databases SQL Server Tutorial · SQL
A composite index is an index that involves more than one column in a table. It's used
when queries often filter or sort by multiple columns, optimizing performance for those
specific queries.
SQL & Databases SQL Server Tutorial · SQL
matching rows from the right table. If no match is found, NULLs are returned for
columns from the right table.
SQL & Databases SQL Server Tutorial · SQL
A subquery is a query within a query. It is used to retrieve data that will be used in the main
query.
Use case:
SQL & Databases SQL Server Tutorial · SQL
rows.
even duplicates.
Joins & Queries
SQL & Databases SQL Server Tutorial · SQL
A FULL OUTER JOIN returns all rows from both tables, matching rows where possible. If
there's no match, the result will contain NULL values for the columns from the table that
doesn't have a match.
Use case: When you want to combine all records from both tables, regardless of whether
they match, and include NULL where no match exists.
Example:
SELECT * FROM table1
FULL OUTER JOIN table2 ON table1.id = table2.id;
SQL & Databases SQL Server Tutorial · SQL
Window functions allow you to perform calculations across a set of table rows that are
related to the current row, without collapsing the result set into a single row.
Example: ROW_NUMBER() generates a sequential integer to each row within the result set.
Example:
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM employees;
This query adds a sequential row number to each employee, ordered by salary.
SQL & Databases SQL Server Tutorial · SQL
A JOIN condition specifies the columns that will be used to match rows between two or
more tables. This condition typically uses ON or USING in SQL.
Example:
SELECT *
FROM table1
JOIN table2 ON table1.id = table2.id;
In this example, the condition table1.id = table2.id determines how the rows from
both tables will be joined.
SQL & Databases SQL Server Tutorial · SQL
Example:
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
In this query, HAVING is used to filter groups that have an average salary greater than
50,000.
SQL & Databases SQL Server Tutorial · SQL
subquery returns one or more rows, otherwise FALSE.
Example with IN:
SELECT name
FROM employees
WHERE department_id IN (SELECT id FROM departments WHERE name =
'HR');
Example with EXISTS:
SELECT name
FROM employees e
WHERE EXISTS (SELECT 1 FROM departments d WHERE d.id =
e.department_id AND d.name = 'HR');
SQL & Databases SQL Server Tutorial · SQL
The BETWEEN operator filters the result set within a given range. It is inclusive, meaning it
includes the boundary values.
Example:
SELECT *
FROM employees
WHERE salary BETWEEN 40000 AND 60000;
This query will return employees whose salaries are between 40,000 and 60,000 (inclusive).
SQL & Databases SQL Server Tutorial · SQL
The LIKE operator is used to search for a specified pattern in a column.
Example:
SELECT *
FROM employees
WHERE name LIKE 'J%n'; -- Names that start with 'J' and end with
'n'
SQL & Databases SQL Server Tutorial · SQL
Aggregate functions perform a calculation on a set of values and return a single value.
Common aggregate functions include:
Example:
SELECT AVG(salary)
FROM employees;
SQL & Databases SQL Server Tutorial · SQL
Example:
SELECT COUNT(*) FROM employees; -- Counts all rows
SELECT COUNT(salary) FROM employees; -- Counts rows where salary is
NOT NULL
SQL & Databases SQL Server Tutorial · SQL
Conditional aggregation allows you to apply aggregate functions to a subset of data that
meets a certain condition. This is usually done with a CASE expression.
Example:
SELECT department,
SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) AS male_count,
SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) AS female_count
FROM employees
GROUP BY department;
This query counts the number of male and female employees in each department.
SQL & Databases SQL Server Tutorial · SQL
A Common Table Expression (CTE) is a temporary result set that can be referenced within
a SELECT, INSERT, UPDATE, or DELETE statement. CTEs are often used for organizing
complex queries.
Example:
WITH EmployeeCTE AS (
SELECT name, salary
FROM employees
WHERE salary > 50000
SELECT * FROM EmployeeCTE;
SQL & Databases SQL Server Tutorial · SQL
right table. If there's no match, NULL values are returned for the right table's
columns.
left table. If there's no match, NULL values are returned for the left table's columns.
SQL & Databases SQL Server Tutorial · SQL
The UNION ALL operator combines the result sets of two or more queries, but unlike
UNION, it does not remove duplicate rows.
Example:
SELECT name FROM employees
UNION ALL
SELECT name FROM contractors;
This will return all names from both employees and contractors, including duplicates.
SQL & Databases SQL Server Tutorial · SQL
A subquery in the FROM clause allows you to treat the result of a query as a temporary table,
which can then be joined or queried further.
Example:
SELECT avg_salary
FROM (SELECT AVG(salary) AS avg_salary FROM employees) AS avg_table;
This query calculates the average salary using a subquery in the FROM clause.
Views
SQL & Databases SQL Server Tutorial · SQL
A view in SQL is a virtual table that is defined by a SELECT query. It does not store data
itself but rather provides a way to view and work with the results of a query as if it were a
table. Views allow users to access specific, formatted data without modifying the underlying
tables directly.
security by exposing only the necessary data.
Example:
CREATE VIEW employee_view AS
SELECT id, name, department
FROM employees;
You can then query the view like a regular table:
SELECT * FROM employee_view;
SQL & Databases SQL Server Tutorial · SQL
store data. It derives its data from the underlying tables each time it is
queried.
Some views (those based on a single table) are updatable, while others
(especially those with JOINs, aggregations, or complex logic) are not.
and so on.
time the view is accessed, especially if it's a complex view or involves large
datasets.
SQL & Databases SQL Server Tutorial · SQL
them reusable and easier to manage.
access to the data without revealing the full database schema.
sensitive data and only expose the columns or rows that are necessary.
or applications, ensuring consistent results.
you can create a view to encapsulate it and reuse the view in different queries.
SQL & Databases SQL Server Tutorial · SQL
Under what conditions?
Yes, views can be updated in SQL, but there are conditions for when this is possible:
that modify the set of rows.
clauses are typically non-updatable.
You can still modify data through these views by using triggers, such as INSTEAD
OF triggers, which allow you to define custom behavior for updating or deleting rows.
Example of an updatable view:
CREATE VIEW simple_view AS
SELECT id, name, salary FROM employees;
UPDATE simple_view SET salary = 60000 WHERE id = 101;
SQL & Databases SQL Server Tutorial · SQL
An indexed view (also called a materialized view) in SQL Server is a view that has a
unique clustered index created on it. This results in the view storing the query results
physically in the database, similar to a table. It is useful for improving performance when you
have complex queries that aggregate data, as the results of the view are precomputed and
stored.
the view is accessed.
additional overhead because the indexed view must also be updated.
Example:
CREATE VIEW employee_summary AS
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
CREATE UNIQUE CLUSTERED INDEX idx_employee_summary
ON employee_summary(department);
SQL & Databases SQL Server Tutorial · SQL
Here’s how you can create a view in each of these DBMS:
SQL Server:
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;
PostgreSQL:
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;
MySQL:
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;
The syntax for creating a view is generally the same across these databases, although there
are certain DBMS-specific features and optimizations (e.g., indexed views in SQL Server).
SQL & Databases SQL Server Tutorial · SQL
A materialized view is a database object that stores the result of a query physically, similar
to an indexed view but more generalized. Unlike regular views, which generate their result
dynamically when queried, materialized views store the result set and can be periodically
refreshed.
since the data is precomputed and stored.
needs to be refreshed periodically, either manually or automatically, depending on the
DBMS.
Example:
CREATE MATERIALIZED VIEW sales_summary AS
SELECT product_id, SUM(sales) AS total_sales
FROM sales
GROUP BY product_id;
REFRESH MATERIALIZED VIEW sales_summary;
Materialized views are supported in systems like PostgreSQL and Oracle, but MySQL does
not have a built-in materialized view feature. You can simulate one using tables and
scheduled jobs.
SQL & Databases SQL Server Tutorial · SQL
To delete a view, you use the DROP VIEW statement. This removes the view from the
database entirely.
Example:
DROP VIEW view_name;
Be cautious when dropping a view, as it will no longer be available for use in queries. Ensure
no other objects are dependent on the view before dropping it.
SQL & Databases SQL Server Tutorial · SQL
and query data without modifying the underlying tables directly.
single unit. It can include complex logic like loops, conditionals, and multiple
queries.
operations on the database. They can also return results.
Example of a stored procedure:
CREATE PROCEDURE GetEmployeeSalary(IN emp_id INT)
BEGIN
SELECT salary FROM employees WHERE id = emp_id;
END;
SQL & Databases SQL Server Tutorial · SQL
Optimizing views is important to ensure that your queries are efficient. Here are some
strategies:
JOINs, GROUP BY, or subqueries), as they can result in slower performance. Keep
views simple and focused.
columns used in JOIN or WHERE conditions.
performing heavy aggregations. These views store the results physically and can be
refreshed periodically.
columns. Only select the data that is necessary.
those tables are optimized (e.g., with appropriate indexing and normalization).
as the inner view’s query needs to be executed each time the outer view is queried.
Stored Procedures & Functions
SQL & Databases SQL Server Tutorial · SQL
A stored procedure is a precompiled collection of SQL statements that can be executed as
a single unit. It allows you to encapsulate logic, such as data manipulation, complex queries,
or repetitive tasks, into reusable blocks. Stored procedures can accept parameters, perform
actions like SELECT, INSERT, UPDATE, and DELETE, and return results.
reusability, centralized logic, and security (by restricting direct access to tables).
Example:
CREATE PROCEDURE GetEmployeeDetails (IN emp_id INT)
BEGIN
SELECT * FROM employees WHERE id = emp_id;
END;
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
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;
Stored Procedure (performs an action):
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;
PostgreSQL: Use EXCEPTION blocks in PL/pgSQL.
BEGIN
INSERT INTO employees (name) VALUES ('John Doe');
EXCEPTION
WHEN others THEN
RAISE NOTICE 'Error occurred: %', SQLERRM;
END;
MySQL: MySQL doesn't have a built-in TRY...CATCH, but you can use
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
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
Debugging stored procedures can be done in the following ways:
step through the code, and inspect variable values during execution.
Steps:
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
An 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,
allowing 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:
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);
Full-Text Index: Used for indexing large text fields. It allows for more advanced searches
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
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.
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
A 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
The query optimizer in the database engine decides which index to use based on several
factors:
SQL & Databases SQL Server Tutorial · SQL
A 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
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:
SQL & Databases SQL Server Tutorial · SQL
Reorganizing an Index: A lighter operation that compacts the index and defragments it. It is
used when fragmentation is low (less than 30%).
SQL Server:
ALTER INDEX idx_name ON table_name REORGANIZE;
PostgreSQL:
PostgreSQL does not have an explicit REORGANIZE command, but you can run VACUUM to
clean up the database and reduce fragmentation:
VACUUM INDEX idx_name;
MySQL:
OPTIMIZE TABLE table_name;
Rebuilding an Index: A more intensive operation where the index is completely dropped
and recreated. This can reduce fragmentation to nearly zero.
SQL Server:
ALTER INDEX idx_name ON table_name REBUILD;
PostgreSQL:
REINDEX INDEX idx_name;
MySQL:
ALTER TABLE table_name DROP INDEX idx_name, ADD INDEX idx_name
(column_name);
SQL & Databases SQL Server Tutorial · SQL
For large datasets, query optimization can be crucial to ensure performance is not impacted.
Here are several tips:
SQL & Databases SQL Server Tutorial · SQL
A transaction is a sequence of SQL operations that are treated as a single unit of work. A
transaction must either be fully completed (committed) or fully undone (rolled back) to
ensure the integrity of the database. Transactions provide the foundation for the ACID
properties (Atomicity, Consistency, Isolation, Durability) that ensure reliable and consistent
operations.
SQL & Databases SQL Server Tutorial · SQL
The ACID properties are critical to ensuring the reliability of transactions in a database:
ensuring that all rules (constraints, triggers, etc.) are respected.
a transaction are invisible to others until the transaction is committed.
case of a system crash.
SQL & Databases SQL Server Tutorial · SQL
The COMMIT statement is used to finalize a transaction by making all the changes made
during the transaction permanent. It ensures that all changes made during the transaction
are saved and visible to other transactions.
want to ensure that the changes are saved to the database.
Example:
BEGIN TRANSACTION;
UPDATE employees SET salary = 5000 WHERE id = 1;
COMMIT;
SQL & Databases SQL Server Tutorial · SQL
The ROLLBACK statement is used to undo all changes made during a transaction. If an error
occurs or something goes wrong, ROLLBACK ensures that the database is restored to its
state before the transaction began.
made during the transaction.
Example:
BEGIN TRANSACTION;
UPDATE employees SET salary = 5000 WHERE id = 1;
ROLLBACK;
SQL & Databases SQL Server Tutorial · SQL
A SAVEPOINT is a way to set a point within a transaction to which you can later roll back if
necessary. It provides more granular control, allowing partial rollback rather than undoing the
entire transaction.
for partial rollback if an error occurs.
Example:
BEGIN TRANSACTION;
SAVEPOINT sp1;
UPDATE employees SET salary = 5000 WHERE id = 1;
ROLLBACK TO sp1; -- Rolls back to the savepoint, undoing only the
changes after it
COMMIT;
SQL & Databases SQL Server Tutorial · SQL
Can you explain the different isolation
levels (e.g., READ UNCOMMITTED, READ COMMITTED, REPEATABLE
READ, SERIALIZABLE)?
The isolation level in SQL defines how transactions interact with each other in terms of
visibility of data. The isolation level affects the balance between data consistency and
transaction concurrency.
changes made by another transaction. This is the lowest level of isolation.
can change during the transaction).
reads (new rows can appear in a query) are still possible.
reads, and phantom reads by making transactions execute sequentially.
SQL & Databases SQL Server Tutorial · SQL
Transactions impact concurrent operations by introducing locking mechanisms to ensure
that multiple transactions don't interfere with each other and cause inconsistent data. This
affects concurrency in several ways:
leading to possible delays for other transactions.
locks, causing a cycle of dependency. This can be automatically detected and
resolved by the DBMS.
SQL & Databases SQL Server Tutorial · SQL
The DBMS treats each individual statement as a transaction and automatically
commits after each statement, unless explicitly rolled back.
TRANSACTION, COMMIT, and ROLLBACK. The user decides when the transaction
begins and ends.
SQL & Databases SQL Server Tutorial · SQL
Deadlocks occur when two or more transactions are waiting for each other to release locks,
causing a cycle of dependencies. To handle deadlocks:
deadlocks and terminate one of the transactions to break the deadlock.
application to reattempt the transaction after a short delay.
in the same order to reduce the likelihood of deadlocks.
SQL & Databases SQL Server Tutorial · SQL
In stored procedures, you control transaction behavior using the following:
transaction.
wrong.
Example:
BEGIN TRANSACTION;
IF (some_condition)
BEGIN
COMMIT; -- Commit if condition is true
END
ELSE
BEGIN
ROLLBACK; -- Rollback if condition is false
END
Normalization & Database Design
SQL & Databases SQL Server Tutorial · SQL
Normalization is the process of organizing a database to reduce redundancy and
dependency by dividing large tables into smaller, manageable tables and defining
relationships between them. This process aims to improve the structure of the database by
minimizing the chances of data anomalies (insertion, update, and deletion anomalies).
SQL & Databases SQL Server Tutorial · SQL
Normal forms are guidelines used to organize a relational database schema. Each form
addresses a different kind of redundancy or dependency.
has a unique identifier (Primary Key).
functionally dependent on the primary key.
part of a composite primary key).
(non-key attributes depending on other non-key attributes).
removed.
multi-valued attributes.
losing data.
SQL & Databases SQL Server Tutorial · SQL
Denormalization is the process of intentionally introducing redundancy into a database by
merging tables or adding redundant data to reduce the complexity of database queries,
improve read performance, and simplify the schema.
normalization (e.g., in OLAP systems or reporting).
stored redundantly to reduce query times.
SQL & Databases SQL Server Tutorial · SQL
multi-valued or repeating groups) and each row has a unique identifier (Primary Key).
must depend on the entire primary key (i.e., there should be no partial
dependencies).
Example:
attributes like CourseName only depend on CourseID would violate 2NF because
CourseName is partially dependent on the composite key. You would separate this
into two tables (one for Courses and one for Students).
SQL & Databases SQL Server Tutorial · SQL
Referential integrity ensures that relationships between tables are consistent. Specifically,
it ensures that a foreign key in one table must match a primary key or a unique key in
another table. This prevents invalid references from being made.
ON DELETE RESTRICT to define how changes in parent tables affect related
child tables.
Example:
table. If you try to delete a customer that has associated orders, referential integrity
will prevent the delete unless actions like CASCADE are specified.
SQL & Databases SQL Server Tutorial · SQL
Data redundancy occurs when the same piece of data is stored in multiple places, which
can lead to inconsistencies and wasted storage. To avoid redundancy:
SQL & Databases SQL Server Tutorial · SQL
How does it differ from a primary key?
A composite key is a combination of two or more columns in a table that can uniquely
identify each record in the table. It is used when a single column is not sufficient to uniquely
identify a row.
Example: A table storing student-course enrollments might use a composite key
consisting of StudentID and CourseID to uniquely identify each enrollment record.
uniquely identifies each record in a table. It can be a single column or a composite
of multiple columns, but it must be unique for each row.
SQL & Databases SQL Server Tutorial · SQL
An Entity-Relationship Diagram (ERD) is a graphical representation of entities and their
relationships to each other within a database. It is used to visualize the structure of a
database and how tables (entities) relate to one another.
ERDs help in the conceptual design phase of a database, outlining entities, relationships,
and keys before implementation.
SQL & Databases SQL Server Tutorial · SQL
How is it different from a natural key?
A surrogate key is an artificial, system-generated key used to uniquely identify a record in a
table. It has no business meaning and is typically a number (e.g., auto-incremented ID).
identify records.
natural keys.
SQL & Databases SQL Server Tutorial · SQL
Designing a database schema for a large e-commerce application involves careful
consideration of data requirements, scalability, and normalization. Key entities and
relationships to consider:
SQL & Databases SQL Server Tutorial · SQL
MongoDB is a NoSQL document-oriented database that stores data in flexible,
semi-structured documents rather than in rows and columns like SQL databases. Unlike
SQL databases, which rely on rigid schemas, MongoDB uses a schema-less approach
where each document can have different fields and structures.
Key differences:
transactions for consistency.
flexibility, scalability, and ease of replication but may sacrifice some consistency in
distributed environments.
SQL & Databases SQL Server Tutorial · SQL
Advantages:
datasets across distributed clusters.
during development.
tolerance.
Disadvantages:
suitable for all applications (though it supports ACID transactions in some cases).
transactions, working with them is more complex compared to SQL.
inconsistency if not properly managed.
SQL & Databases SQL Server Tutorial · SQL
How does it differ from rows in
SQL databases?
A document in MongoDB is a record represented as a JSON-like object (BSON format)
that contains field-value pairs. It can have a flexible structure, meaning each document in a
collection may contain different fields and data types.
Differences from SQL Rows:
a document is more flexible and can vary in structure.
store complex, nested data structures (arrays, sub-documents).
SQL & Databases SQL Server Tutorial · SQL
databases within the same instance.
but don’t have a fixed schema.
SQL & Databases SQL Server Tutorial · SQL
Create:
db.collection.insertOne({ name: "Alice", age: 25 });
db.collection.insertMany([{ name: "Bob", age: 30 }, { name:
"Charlie", age: 35 }]);
Read:
db.collection.find({ age: { $gt: 30 } });
db.collection.findOne({ name: "Alice" });
Update:
db.collection.updateOne({ name: "Alice" }, { $set: { age: 26 } });
db.collection.updateMany({ age: { $lt: 30 } }, { $set: { status:
"young" } });
Delete:
db.collection.deleteOne({ name: "Alice" });
db.collection.deleteMany({ age: { $lt: 30 } });
SQL & Databases SQL Server Tutorial · SQL
How is it different from SQL indexes?
Indexing in MongoDB is a mechanism to improve query performance by reducing the
amount of data the system needs to scan. MongoDB creates indexes on fields that are
queried frequently.
Differences from SQL indexes:
hashed indexes, geospatial indexes, and text indexes.
indexes can be dynamic, allowing indexing on any field within a document.
queries.
SQL & Databases SQL Server Tutorial · SQL
The $in operator is used to match values in a specified array. It checks if the value of a field
is equal to any value in the provided array.
Example:
db.collection.find({ age: { $in: [25, 30, 35] } });
This query finds all documents where the age field is 25, 30, or 35.
SQL & Databases SQL Server Tutorial · SQL
high availability and data redundancy by replicating data across multiple servers. If
the primary server goes down, one of the secondaries can be promoted to primary
automatically.
(shards) based on a shard key. Each shard holds a portion of the data, and a
mongos router directs queries to the correct shard. Sharding helps manage large
datasets by distributing the load.
SQL & Databases SQL Server Tutorial · SQL
find(): Returns a cursor to all documents that match the query. You can iterate over the
results using .forEach() or convert them to an array with .toArray().
Example:
db.collection.find({ age: { $gt: 30 } });
findOne(): Returns the first document that matches the query, or null if no document is
found.
Example:
db.collection.findOne({ name: "Alice" });
SQL & Databases SQL Server Tutorial · SQL
How do you use
it?
The Aggregation Framework in MongoDB is used to perform complex data processing
tasks such as grouping, filtering, sorting, and reshaping documents.
It uses a pipeline of stages to process documents:
Example:
db.collection.aggregate([
{ $match: { status: "active" } }, // Filter documents
{ $group: { _id: "$age", count: { $sum: 1 } } }, // Group by age
and count occurrences
{ $sort: { count: -1 } } // Sort by count in descending order
]);
SQL & Databases SQL Server Tutorial · SQL
You can use the updateOne(), updateMany(), or replaceOne() methods to update data.
Example:
db.collection.updateOne({ name: "Alice" }, { $set: { age: 27 } });
SQL & Databases SQL Server Tutorial · SQL
MongoDB provides multi-document transactions starting with version 4.0. This allows you
to execute multiple operations in a transaction, ensuring ACID properties (Atomicity,
Consistency, Isolation, Durability) across multiple documents and collections.
Example:
const session = client.startSession();
try {
session.startTransaction();
db.collection1.updateOne({ _id: 1 }, { $set: { status: "completed"
} }, { session });
db.collection2.updateOne({ _id: 2 }, { $set: { status: "shipped" }
}, { session });
session.commitTransaction();
} catch (error) {
session.abortTransaction();
} finally {
session.endSession();
SQL & Databases SQL Server Tutorial · SQL
Data modeling in MongoDB refers to the design of how data will be stored, organized, and
accessed in the database. Since MongoDB is schema-less, data modeling involves deciding
how to structure documents, collections, and their relationships (embedded vs. referenced
documents) to balance performance, scalability, and ease of querying.
SQL & Databases SQL Server Tutorial · SQL
In MongoDB, relationships can be handled in two ways:
one-to-many relationships).
Example: A blog post with comments as an embedded array.
references (best for many-to-many or large datasets).
Example: A customer document may reference an order document by storing the
order’s _id in the customer document.
SQL & Databases SQL Server Tutorial · SQL
A document schema defines the structure, rules, and validations for documents in a
collection. MongoDB is schema-less by default, but you can enforce schema validation rules
using MongoDB schema validation.
Example:
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: { bsonType: "string" },
email: { bsonType: "string" }
});
SQL & Databases SQL Server Tutorial · SQL
Data validation in MongoDB can be implemented using JSON Schema or custom validation
rules to ensure data consistency.
Example (using JSON Schema):
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["product_name", "price"],
properties: {
product_name: { bsonType: "string" },
price: { bsonType: "double", minimum: 0 }
});
SQL & Databases SQL Server Tutorial · SQL
MongoDB Atlas is a fully-managed cloud database service provided by MongoDB Inc. It
offers:
SQL & Databases SQL Server Tutorial · SQL
Database Security
SQL & Databases SQL Server Tutorial · SQL
Database security refers to the practices, tools, and measures used to protect a database
from unauthorized access, misuse, modification, or destruction of its data. It ensures the
confidentiality, integrity, and availability (often referred to as the CIA triad) of the data stored
within the database.
Why it's important:
information, financial data).
users.
threats like ransomware or DDoS attacks.
SQL & Databases SQL Server Tutorial · SQL
Common database security risks include:
not properly validated.
access controls.
leaking or modifying data.
making it unavailable to legitimate users.
accessible to unauthorized users.
SQL & Databases SQL Server Tutorial · SQL
SQL Injection is a type of attack where an attacker inserts or manipulates malicious SQL
code into a query, which can compromise the database. It usually happens when user input
is improperly sanitized or validated.
Prevention techniques:
Use Prepared Statements/Parameterized Queries: This ensures that user input is treated
as data, not executable code.
$stmt = $pdo->prepare('SELECT * FROM users WHERE username =
:username AND password = :password');
$stmt->execute(['username' => $username, 'password' => $password]);
lengths, and ranges.
input is properly escaped.
to perform their tasks.
attacks.
SQL & Databases SQL Server Tutorial · SQL
Role-Based Access Control (RBAC) is a method for restricting system access to
authorized users based on roles. Each role defines a set of permissions (what actions can
be performed on which database objects).
Steps to implement RBAC:
SQL & Databases SQL Server Tutorial · SQL
Stored Procedures can help improve database security by encapsulating business logic
and SQL statements in precompiled code, making it harder for attackers to inject malicious
code.
Roles in database security:
database level, preventing malicious input from being executed.
permissions to execute specific procedures rather than direct access to the
underlying tables.
to the end-user, reducing the attack surface.
and compliance purposes.
Example: Instead of allowing users to execute arbitrary INSERT or UPDATE statements, you
can give them permission to execute a specific stored procedure that does the necessary
validation and modification of data.
CREATE PROCEDURE update_salary(IN emp_id INT, IN new_salary DECIMAL)
BEGIN
IF new_salary > 0 THEN
UPDATE employees SET salary = new_salary WHERE id = emp_id;
END IF;
END;
SQL & Databases SQL Server Tutorial · SQL
Encryption is essential for protecting sensitive data both at rest (on disk) and in transit
(during communication).
SQL Server:
Transparent Data Encryption (TDE): Encrypts data at rest without requiring application
changes.
CREATE DATABASE ENCRYPTION KEY;
ALTER DATABASE MyDatabase SET ENCRYPTION ON;
Column-Level Encryption: For encrypting specific columns.
CREATE CERTIFICATE MyCertificate WITH SUBJECT = 'My Certificate';
CREATE SYMMETRIC KEY MySymmetricKey WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE MyCertificate;
OPEN SYMMETRIC KEY MySymmetricKey DECRYPTION BY CERTIFICATE
MyCertificate;
PostgreSQL:
pgcrypto extension provides functions for encrypting data.
SELECT pgp_sym_encrypt('Sensitive Data', 'encryption_key');
MySQL:
Encryption Functions: MySQL provides functions like AES_ENCRYPT and AES_DECRYPT.
SELECT AES_ENCRYPT('Sensitive Data', 'encryption_key');
SELECT AES_DECRYPT(encrypted_data, 'encryption_key');
For all databases, consider using SSL/TLS for encrypting data in transit.
SQL & Databases SQL Server Tutorial · SQL
Backup and restore security involves ensuring that backup files are stored securely and
that access to backup data is tightly controlled.
Steps for Secure Backup:
SQL & Databases SQL Server Tutorial · SQL
There are three primary types of database backups:
SQL & Databases SQL Server Tutorial · SQL
SQL Server:
To back up a database in SQL Server, you can use the BACKUP DATABASE command.
BACKUP DATABASE MyDatabase TO DISK = 'C:\Backups\MyDatabase.bak';
BACKUP LOG MyDatabase TO DISK = 'C:\Backups\MyDatabase_log.trn';
PostgreSQL:
In PostgreSQL, you can use the pg_dump command for backing up the database.
pg_dump mydatabase > /path/to/backup/mydatabase.sql
For backing up with compression or other options:
pg_dump -Fc mydatabase > /path/to/backup/mydatabase.dump
For transactional backups, you can use WAL (Write-Ahead Logging) archiving, typically
managed through archive_mode and archive_command settings in the
postgresql.conf.
MySQL:
In MySQL, you can use the mysqldump command for backing up the database.
mysqldump -u username -p mydatabase > /path/to/backup/mydatabase.sql
For binary logging (transaction logs), MySQL uses binlog:
[mysqld]
log-bin=mysql-bin
SQL & Databases SQL Server Tutorial · SQL
SQL Server:
To restore a full backup in SQL Server:
RESTORE DATABASE MyDatabase FROM DISK = 'C:\Backups\MyDatabase.bak';
RESTORE LOG MyDatabase FROM DISK = 'C:\Backups\MyDatabase_log.trn';
To restore a database to a specific point in time (using point-in-time recovery), you would
restore the full backup and apply transaction logs.
RESTORE DATABASE MyDatabase FROM DISK = 'C:\Backups\MyDatabase.bak';
RESTORE LOG MyDatabase FROM DISK = 'C:\Backups\MyDatabase_log.trn'
WITH STOPAT = '2023-09-14T15:30:00'; -- Restore to a specific time
PostgreSQL:
To restore a backup from a pg_dump:
psql -U username -d mydatabase < /path/to/backup/mydatabase.sql
For binary dump (pg_dump -Fc):
pg_restore -U username -d mydatabase /path/to/backup/mydatabase.dump
MySQL:
To restore a MySQL database:
mysql -u username -p mydatabase < /path/to/backup/mydatabase.sql
For restoring binary logs:
mysqlbinlog /path/to/binlog/mysql-bin.000001 | mysql -u username -p
SQL & Databases SQL Server Tutorial · SQL
Point-in-time recovery (PITR) allows you to restore a database to a specific moment in
time, which can be crucial in scenarios where:
How it works:
after the full backup until the specified point in time.
SQL Server Example:
RESTORE DATABASE MyDatabase FROM DISK = 'C:\Backups\MyDatabase.bak';
RESTORE LOG MyDatabase FROM DISK = 'C:\Backups\MyDatabase_log.trn'
WITH STOPAT = '2023-09-14T15:30:00'; -- Restore up to a specific
time
PostgreSQL Example:
To enable point-in-time recovery, you need to restore a base backup, then use WAL
(Write-Ahead Logging) archives to apply changes until the desired point.
recovery_target_time.
SQL & Databases SQL Server Tutorial · SQL
Automating backups ensures that backups are performed regularly and without manual
intervention. You can use the following methods:
SQL & Databases SQL Server Tutorial · SQL
Database replication is the process of copying and maintaining database objects in multiple
databases to ensure high availability and fault tolerance.
Types of Replication:
SQL & Databases SQL Server Tutorial · SQL
Database scaling refers to increasing a database's ability to handle more workload—either
by increasing the resources available to a single instance or distributing the load across
multiple instances.
SQL & Databases SQL Server Tutorial · SQL
Sharding and partitioning are techniques used to distribute data across multiple servers or
tables to improve performance and scalability.
SQL & Databases SQL Server Tutorial · SQL
A read replica is a copy of a database that is used to offload read-only queries from the
primary database (master). It is particularly useful for handling high read traffic and
improving database scalability.
can focus on write operations, reducing the load on the master.
operations.
serve read-heavy queries, while writes are only made to the master database.
Note: Read replicas are usually asynchronous, meaning there can be a slight delay in
replication. For critical real-time reads, this might not be suitable.
SQL & Databases SQL Server Tutorial · SQL
Database caching involves storing frequently accessed data in a faster storage layer (e.g.,
memory) so that future requests for the same data can be served more quickly, reducing the
need to query the database repeatedly.
requested, the cache can provide instant access to commonly requested
data.
Redis or Memcached) makes it accessible in nanoseconds, compared to the
millisecond access time of traditional disk-based databases.
improving the overall user experience.
Example: Frequently accessed user profiles in a web application can be cached using
Redis, so that subsequent requests don't have to query the database again.
SQL & Databases SQL Server Tutorial · SQL
Monitoring database performance is crucial for identifying bottlenecks and ensuring optimal
functioning. The following methods are commonly used:
SQL & Databases SQL Server Tutorial · SQL
A connection pool is a cache of database connections that are maintained so that
connections can be reused when future requests to the database are made. Instead of
opening and closing a new connection each time a query is executed, the application can
reuse existing connections from the pool.
establishing new connections, leading to faster query execution.
the database, the pool avoids overloading the database with too many open
connections.
requests without overwhelming the database. The pool can be scaled by
adjusting the maximum number of connections based on the workload.
Example: A connection pool size can be set to 100, meaning up to 100 connections to the
database can be active at once, with others waiting in line for an available connection.
SQL & Databases SQL Server Tutorial · SQL
Query optimization is the process of improving the efficiency of SQL queries to reduce
resource consumption and improve response time. The goal is to make sure that queries are
executed using the most efficient execution plan possible.
operations, improving overall system performance.
resource contention in high-traffic applications.
selecting all columns.
replace subqueries with joins when possible.
vs. OUTER JOIN).
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
Database design patterns are general solutions to recurring problems that arise in
database schema design. Some common patterns include:
SQL & Databases SQL Server Tutorial · SQL
Event sourcing is a pattern where the state of an application is determined by a sequence
of events, rather than storing the current state directly in the database.
entity (event) is stored as an immutable event in an event store. The state can be
reconstructed by replaying the events.
requiring full audit logs, and systems that need to capture historical data changes.
SQL & Databases SQL Server Tutorial · SQL
A materialized view is a database object that stores the results of a query physically, unlike
a regular view, which computes its result dynamically.
keep the data up to date.
retrieve the precomputed values instead of performing costly aggregation on
the fly.
SQL & Databases SQL Server Tutorial · SQL
Multi-tenancy refers to a single instance of a database serving multiple tenants (clients or
organizations) while keeping their data isolated.
Approaches:
SQL & Databases SQL Server Tutorial · SQL
A time-series database (TSDB) is optimized for storing, querying, and managing
time-stamped data (data associated with timestamps), often used for tracking events or
metrics over time.
etc.
particular hour or day).
SQL & Databases SQL Server Tutorial · SQL
Managing and versioning database schema changes is essential in keeping track of updates
and ensuring consistency across different environments (development, staging, production).
Approaches:
SQL & Databases SQL Server Tutorial · SQL
Sharding is the process of breaking a large database into smaller, more manageable pieces
(shards), each of which is stored on a different server.
queries.
cost-effective or possible.
region, etc.).
or cluster.
Example: In an e-commerce platform, you could shard user data based on geographic
region. Users from the US might be stored in one shard, while users from Europe are stored
in another.
SQL & Databases SQL Server Tutorial · SQL
Data migration involves transferring data between systems or platforms, often when
changing database engines or moving to the cloud.
Steps:
SQL & Databases SQL Server Tutorial · SQL
The CAP theorem (Consistency, Availability, Partition Tolerance) states that in a
distributed database system, it is impossible to simultaneously guarantee all three of the
following:
SQL & Databases SQL Server Tutorial · SQL
Eventual consistency is a consistency model used in distributed systems where updates to
data will propagate and eventually become consistent across all nodes, but not necessarily
immediately.
eventually, that update will be propagated to all other nodes.
converge to a consistent state over time.
databases (Cassandra, DynamoDB) and systems dealing with high
availability and massive scale.
SQL & Databases SQL Server Tutorial · SQL
The DISTINCT keyword is used to return only unique values in the result set, removing any
duplicate rows.
Example:
SELECT DISTINCT Country FROM Customers;
This will return a list of unique countries from the Customers table.
SQL & Databases SQL Server Tutorial · SQL
The CASE statement is SQL’s way of handling if-else logic in queries. It allows you to return
different values based on certain conditions.
Example:
SELECT Name,
CASE
WHEN Age < 18 THEN 'Minor'
WHEN Age >= 18 AND Age < 60 THEN 'Adult'
ELSE 'Senior'
END AS AgeGroup
FROM Employees;
SQL & Databases SQL Server Tutorial · SQL
The UNION operator combines the result sets of two or more SELECT queries into a single
result set and removes duplicate records. All SELECT queries must have the same number
of columns with compatible data types.
Example:
SELECT Name FROM Employees
UNION
SELECT Name FROM Customers;
SQL & Databases SQL Server Tutorial · SQL
Review the concept and prepare a concise verbal explanation with a real project example.
SQL & Databases SQL Server Tutorial · SQL
regardless of the string's length.
to store the string.
Example:
CREATE TABLE Example (
fixed_char CHAR(10),
variable_char VARCHAR(10)
SQL & Databases SQL Server Tutorial · SQL
The LIMIT clause is used to specify the number of records returned by a SELECT query. It is
commonly used to restrict the number of rows, especially for pagination.
Example:
SELECT * FROM Employees LIMIT 5;
This will return only the first 5 rows from the Employees table.
SQL & Databases SQL Server Tutorial · SQL
NULL represents the absence of a value in a column. It is not the same as an empty string or
zero.
value) or IFNULL().
Example:
SELECT Name, IFNULL(Salary, 0) FROM Employees;
SQL & Databases SQL Server Tutorial · SQL
and does not log individual row deletions.
transactions).
Example:
DELETE FROM Employees WHERE Age < 18; -- Deletes only specific rows
TRUNCATE TABLE Employees; -- Deletes all rows
SQL & Databases SQL Server Tutorial · SQL
An Index is a database object that speeds up the retrieval of rows from a table by creating a
data structure (often a B-tree). Indexes improve the performance of SELECT queries but can
slow down INSERT, UPDATE, and DELETE operations.
Example:
CREATE INDEX idx_employee_name ON Employees(Name);
SQL & Databases SQL Server Tutorial · SQL
The ACID properties ensure reliable processing of database transactions: