Coding Interview QuestionsInterview Questions and Answers

New 90 Databases Interview Questions

Table of Contents

Introduction

Databases play a crucial role in organizing and managing data efficiently. If you’re preparing for a database interview, it’s important to have a good understanding of key concepts. Common interview questions often cover topics such as database architecture, normalization, SQL queries, indexing, and transaction management. You may also be asked about different types of databases like relational, NoSQL, and graph databases. Additionally, understanding database security, backup and recovery processes, and performance optimization techniques is beneficial. Remember to familiarize yourself with these fundamental concepts to confidently tackle database-related interview questions and demonstrate your proficiency in handling data effectively.

Basic Questions

1. What is a database?

A database is a structured collection of data that is organized and managed in a way that allows for efficient storage, retrieval, and manipulation of data. It serves as a centralized repository for storing and managing data for various applications.

2. What is the difference between a database and a DBMS?

A database is the actual repository where data is stored, while a DBMS (Database Management System) is software that provides an interface to interact with the database. DBMS handles tasks like data storage, retrieval, security, and ensures data integrity. Examples of DBMS are MySQL, Oracle, and SQL Server.

3. What is SQL?

SQL (Structured Query Language) is a programming language used to manage relational databases. It enables users to interact with databases by defining, manipulating, and querying the data. Here’s a simple SQL query to retrieve data from a table:

SQL
SELECT * FROM customers WHERE age > 18;

4. What is a primary key?

A primary key is a unique identifier for each record in a database table. It ensures that each row in the table is uniquely identifiable. In SQL, the primary key is defined when creating a table, and it must have unique and non-null values. Example:

SQL
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    name VARCHAR(50),
    age INT
);

5. What is a foreign key?

A foreign key is a field in a table that refers to the primary key of another table. It establishes a relationship between two tables and helps maintain referential integrity. Example:

SQL
CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    order_date DATE,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

6. What is normalization?

Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity. It involves breaking down a database into smaller, well-structured tables to avoid data anomalies. There are different levels of normalization, such as 1NF, 2NF, 3NF, etc.

7. What is an index?

An index is a database object that enhances the speed of data retrieval operations on a table. It works like an index in a book, allowing the database engine to quickly locate specific data based on indexed columns. Indexes are crucial for optimizing query performance. Example:

SQL
CREATE INDEX idx_lastname ON employees (last_name);

8. What is a transaction?

A transaction is a sequence of one or more database operations that are executed as a single unit. It ensures that either all the operations within the transaction are completed successfully, or none of them are applied at all. Transactions follow the ACID properties (Atomicity, Consistency, Isolation, Durability).

9. What is ACID in the context of databases?

ACID is an acronym that represents the four essential properties of a database transaction:

  • Atomicity: A transaction is treated as a single unit of work, either all operations succeed, or none of them take effect.
  • Consistency: A transaction takes the database from one consistent state to another consistent state. All integrity constraints are maintained.
  • Isolation: Each transaction is isolated from others, ensuring that the operations of one transaction do not interfere with another.
  • Durability: Once a transaction is committed, its changes are permanent and survive system failures.

10. What is a view?

A view is a virtual table created from one or more tables in the database. It does not contain actual data but is defined by a query. Views allow users to simplify complex queries, restrict data access, and present data in a more user-friendly manner. Example:

SQL
CREATE VIEW active_orders AS
SELECT * FROM orders WHERE status = 'active';

11. What is a stored procedure?

A stored procedure is a precompiled and stored collection of SQL statements that perform specific functions. It allows developers to encapsulate complex logic on the database server and call it from applications. Stored procedures help promote code reusability and enhance security. Example:

SQL
CREATE PROCEDURE GetEmployeeById(IN empId INT)
BEGIN
    SELECT * FROM employees WHERE employee_id = empId;
END;

12. What is a trigger?

A trigger is a database object that is automatically executed in response to specific events, such as INSERT, UPDATE, or DELETE operations on a table. Triggers enable the enforcement of business rules, maintain data integrity, and perform actions automatically. Example:

SQL
CREATE TRIGGER update_stock
AFTER INSERT ON sales
FOR EACH ROW
BEGIN
    UPDATE products
    SET stock = stock - NEW.quantity
    WHERE product_id = NEW.product_id;
END;

13. What is data integrity?

Data integrity refers to the accuracy, consistency, and reliability of data stored in a database. It ensures that the data is correct and valid throughout its lifecycle and adheres to defined rules, constraints, and relationships.

14. What is the difference between a clustered and non-clustered index?

A clustered index determines the physical order of data in a table, and there can be only one clustered index per table. Non-clustered indexes, on the other hand, do not affect the physical order of data and can have multiple indexes per table.

15. What is a database transaction log?

A database transaction log is a record of all the modifications made to the database. It includes a chronological list of committed transactions, which helps in recovering the database to a specific point in time in case of system failures.

16. What is the difference between a join and a subquery?

A join combines rows from two or more tables based on related column values. It is used to retrieve data from multiple tables simultaneously. A subquery is a query embedded within another query and is used to retrieve data that will be used in the main query’s condition.

Example of a JOIN:

SQL
SELECT customers.name, orders.order_id
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id;

Example of a Subquery:

SQL
SELECT name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders WHERE total_amount > 100);

17. What is the difference between OLTP and OLAP?

OLTP (Online Transaction Processing) is designed for handling real-time transactional operations, like data insertion, updates, and deletions. It is optimized for high throughput and low response times. OLAP (Online Analytical Processing), on the other hand, is designed for complex analytical queries, data mining, and reporting. It focuses on performance for read-heavy operations.

18. What is a NoSQL database?

A NoSQL database is a non-relational database that provides a flexible and scalable approach to store and retrieve data. Unlike traditional SQL databases, NoSQL databases do not use a fixed schema and are often used for large-scale distributed systems and unstructured data.

19. What is data warehousing?

Data warehousing is the process of collecting, storing, and managing data from various sources to support business intelligence and reporting activities. Data from different databases and applications are consolidated into a central repository called a data warehouse, where it can be analyzed and used for decision-making.

20. What is database normalization and why is it important?

Database normalization is the process of organizing data in a database to reduce redundancy and ensure data integrity. It involves breaking down a large table into smaller, well-structured tables, eliminating data duplication, and establishing relationships between them using primary and foreign keys.

Normalization is crucial because it:

  • Reduces data redundancy, which saves storage space and ensures consistency.
  • Improves data integrity by avoiding update anomalies.
  • Enhances database performance by optimizing query execution.
  • Makes the database easier to maintain and modify.

Intermediate Questions

1. What is a database index, and why is it important?

A database index is a data structure that improves the speed of data retrieval operations on a database table. It acts like a roadmap that allows the database management system (DBMS) to locate the rows in a table more efficiently. Without an index, the DBMS would need to scan the entire table to find the requested data, which can be slow and resource-intensive, especially for large tables.

An index is important because it significantly enhances query performance by reducing the number of disk I/O operations required to locate specific rows. It works by creating a sorted data structure (usually a B-tree) that contains a copy of selected columns from the table, along with pointers to the corresponding rows. When a query includes the indexed columns in its search criteria, the DBMS can quickly navigate the index to find the relevant rows, minimizing the need for full table scans.

Example (using SQL syntax):
Let’s create an index on the “email” column of a “users” table.

SQL
CREATE INDEX idx_users_email ON users (email);

2. What is normalization in database design?

Normalization is a process in database design that organizes data in a relational database to eliminate redundancy and improve data integrity. It involves breaking down a large table into smaller, more manageable tables, and defining relationships between them. The main goal of normalization is to reduce data duplication and ensure that each piece of data is stored in one place only (avoiding update anomalies).

There are several normal forms (1NF, 2NF, 3NF, etc.), each representing a higher level of data organization and reducing different types of data redundancies. By achieving higher normal forms, a database becomes more efficient, flexible, and easier to maintain.

Example:
Consider a denormalized “orders” table that includes both customer details and order items.

SQL
-- Denormalized table
CREATE TABLE orders (
  order_id INT PRIMARY KEY,
  customer_name VARCHAR(50),
  customer_email VARCHAR(100),
  item_name VARCHAR(50),
  item_price DECIMAL(10, 2)
);

To normalize this table, we would create separate tables for customers and order items, and link them through foreign keys.

SQL
CREATE TABLE customers (
  customer_id INT PRIMARY KEY,
  customer_name VARCHAR(50),
  customer_email VARCHAR(100)
);

CREATE TABLE order_items (
  order_item_id INT PRIMARY KEY,
  order_id INT,
  item_name VARCHAR(50),
  item_price DECIMAL(10, 2),
  FOREIGN KEY (order_id) REFERENCES orders(order_id)
);

3. What are the different types of database relationships?

There are mainly four types of database relationships in the context of relational databases:

  1. One-to-One (1:1): In this type of relationship, one row in one table is associated with only one row in another table, and vice versa. It is less common in databases due to the potential for data redundancy.
  2. One-to-Many (1:N): In a one-to-many relationship, a row in one table can be related to multiple rows in another table, but each row in the second table is related to only one row in the first table.
  3. Many-to-One (N:1): This is the opposite of the one-to-many relationship. Multiple rows in one table are related to a single row in another table.
  4. Many-to-Many (N:N): In a many-to-many relationship, multiple rows in one table can be related to multiple rows in another table. To implement this relationship, an intermediary table (also known as a junction or associative table) is used to link the two main tables.

Example (using SQL syntax):
Consider a one-to-many relationship between “departments” and “employees” tables, where one department can have multiple employees, but an employee belongs to only one department.

SQL
CREATE TABLE departments (
  department_id INT PRIMARY KEY,
  department_name VARCHAR(50)
);

CREATE TABLE employees (
  employee_id INT PRIMARY KEY,
  employee_name VARCHAR(50),
  department_id INT,
  FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

4. What is a primary key, and why is it important?

A primary key is a unique identifier for each row in a database table. It ensures that each record can be uniquely identified and distinguishes one row from another. The primary key must have the following properties:

  1. Uniqueness: Each value in the primary key column must be unique, and no two rows can have the same primary key value.
  2. Non-null: The primary key value cannot be NULL, as it must be present for every row.
  3. Immutability: The primary key value should not change over the lifetime of a row. If it needs to be updated, it is usually better to create a new row and update the other attributes instead.

The primary key is important because it provides a fast and efficient way to access individual rows and establish relationships between tables (e.g., through foreign keys). It also enforces data integrity, as it prevents duplicate or NULL values in the key column.

Example (using SQL syntax):
Let’s define a primary key for the “employees” table from the previous question.

SQL
CREATE TABLE employees (
  employee_id INT PRIMARY KEY,
  employee_name VARCHAR(50),
  department_id INT,
  FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

5. What is a foreign key?

A foreign key is a column or a set of columns in a table that establishes a link between data in two related tables. It represents a relationship between the data in the current table (child table) and the data in another table (parent table). The foreign key in the child table refers to the primary key in the parent table.

The foreign key constraint ensures that the values in the foreign key column(s) of the child table must either match the values in the primary key column(s) of the parent table or be NULL. This constraint maintains data integrity and prevents inconsistencies in the relational database.

Foreign keys are essential for enforcing referential integrity, allowing developers to create relationships and navigate between related data across multiple tables.

Example (using SQL syntax):
Continuing from the previous example, let’s add a foreign key to the “employees” table, linking it to the “departments” table.

SQL
CREATE TABLE employees (
  employee_id INT PRIMARY KEY,
  employee_name VARCHAR(50),
  department_id INT,
  FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

6. What is a join in SQL, and what are the different types of joins?

A join in SQL is used to combine rows from two or more tables based on a related column between them. It allows you to retrieve data from multiple tables in a single result set. Joins are fundamental for querying and retrieving information that spans across multiple tables in a relational database.

There are several types of joins in SQL:

  1. INNER JOIN: This is the most common type of join. It returns only the rows that have matching values in both tables. Rows with no match in either table are excluded from the result set.
SQL
-- Example INNER JOIN
SELECT employees.employee_id, employees.employee_name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;
  1. LEFT JOIN (or LEFT OUTER JOIN): This join returns all the rows from the left table and the matched rows from the right table. If there is no match in the right table, NULL values are included in the result set.
SQL
-- Example LEFT JOIN
SELECT employees.employee_id, employees.employee_name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;
  1. RIGHT JOIN (or RIGHT OUTER JOIN): This join returns all the rows from the right table and the matched rows from the left table. If there is no match in the left table, NULL values are included in the result set.
SQL
-- Example RIGHT JOIN
SELECT employees.employee_id, employees.employee_name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;
  1. FULL JOIN (or FULL OUTER JOIN): This join returns all the rows when there is a match in either the left or right table. If there is no match, NULL values are included for the columns from the table with no match.
SQL
-- Example FULL JOIN
SELECT employees.employee_id, employees.employee_name, departments.department_name
FROM employees
FULL JOIN departments ON employees.department_id = departments.department_id;

7. What is a subquery?

A subquery, also known as a nested query or inner query, is a query nested within another SQL statement. It allows you to use the result of one query as a part of another query. Subqueries can be used in various SQL clauses, such as SELECT, FROM, WHERE, and HAVING.

Subqueries are helpful when you need to filter data based on the results of another query or perform operations on the subsets of data. They provide a way to break down complex problems into simpler steps.

Example:
Let’s use a subquery to find employees who earn more than the average salary in their department.

SQL
SELECT employee_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees GROUP BY department_id);

8. What is the difference between UNION and UNION ALL?

UNIONUNION ALL
Combines result sets and removes duplicate rowsCombines result sets without removing duplicates
Performs a distinct operation on the result setDoes not perform a distinct operation
Slower as it requires duplicate eliminationFaster, as it retains all rows, including duplicates
Syntax: SELECT columns FROM table1 UNION SELECT columns FROM table2;Syntax: SELECT columns FROM table1 UNION ALL SELECT columns FROM table2;

9. What is ACID in database transactions?

ACID is an acronym that represents the four essential properties of a reliable database transaction:

  1. Atomicity: Atomicity ensures that a transaction is treated as a single unit of work, meaning it either executes in its entirety or not at all. If any part of the transaction fails, the whole transaction is rolled back, and the database returns to its original state.
  2. Consistency: Consistency ensures that a transaction takes the database from one valid state to another. The database must satisfy a set of integrity constraints before and after the transaction execution. If a transaction violates any constraint, it is rolled back, and the database remains unchanged.
  3. Isolation: Isolation ensures that concurrent transactions do not interfere with each other. Each transaction operates as if it is the only one running, preventing data inconsistencies caused by concurrent operations. Isolation levels, such as Read Uncommitted, Read Committed, Repeatable Read, and Serializable, define the extent of this isolation.
  4. Durability: Durability guarantees that once a transaction is committed, its changes are permanent and survive any subsequent failures, such as power outages or crashes. Committed data is stored in non-volatile storage, ensuring its availability even in the event of system failures.

10. What is a stored procedure?

A stored procedure is a precompiled and stored collection of SQL statements that perform specific tasks on a database. It is similar to a function in programming languages and is often used to encapsulate and execute complex database operations. Stored procedures are stored on the database server and can be called from client applications or other stored procedures.

Benefits of stored procedures include:

  1. Improved Performance: Since stored procedures are precompiled, they can execute more efficiently than ad-hoc SQL queries, reducing the amount of data transmitted over the network.
  2. Code Reusability: Stored procedures promote code reusability, as they can be called from multiple applications or other stored procedures.
  3. Security: Permissions can be granted to execute a stored procedure while restricting direct access to underlying tables, providing a security layer.
  4. Easier Maintenance: Changes to complex SQL logic can be made within the stored procedure without requiring changes in the application code.

Example (using SQL Server syntax):
Let’s create a simple stored procedure that retrieves employee details based on the department.

SQL
CREATE PROCEDURE GetEmployeesByDepartment
    @departmentId INT
AS
BEGIN
    SELECT employee_id, employee_name, department_id
    FROM employees
    WHERE department_id = @departmentId;
END;

To execute the stored procedure:

SQL
EXEC GetEmployeesByDepartment @departmentId = 1;

11. What is a trigger?

A trigger is a database object that automatically executes a set of SQL statements in response to specific events, such as INSERT, UPDATE, DELETE, or other data manipulation operations on a table. Triggers are used to enforce business rules, maintain data integrity, and automate certain tasks without requiring explicit manual execution.

Triggers are defined to be associated with a particular table and are activated whenever the specified event occurs on that table. They can execute SQL statements both before and after the triggering event.

Example (using SQL Server syntax):
Let’s create a trigger that automatically updates the “last_updated” timestamp column in the “employees” table whenever a row is updated.

SQL
CREATE TRIGGER UpdateLastUpdated
ON employees
AFTER UPDATE
AS
BEGIN
    UPDATE employees
    SET last_updated = GETDATE()
    WHERE employee_id IN (SELECT DISTINCT employee_id FROM INSERTED);
END;

In this example, the trigger will update the “last_updated” column with the current date and time whenever an UPDATE operation is performed on the “employees” table.

12. What is a transaction deadlock, and how can it be resolved?

A transaction deadlock occurs when two or more transactions are blocked, each waiting for a resource that is locked by another transaction. This circular waiting scenario leads to a standstill where no transaction can proceed, causing a deadlock.

To resolve a transaction deadlock, the database management system needs to detect the deadlock and take corrective action. The common methods to handle deadlocks are:

  1. Timeouts: Set a timeout value for transactions. If a transaction cannot acquire the required locks within the specified timeout, it is automatically rolled back, breaking the deadlock.
  2. Deadlock Detection and Resolution: The DBMS detects deadlocks periodically and identifies the transactions involved in the deadlock. It then selects one or more transactions to be rolled back to resolve the deadlock. The selection criteria may involve factors like transaction size or priority.
  3. Deadlock Prevention: This approach involves careful design of transactions and the application to ensure that deadlocks cannot occur. It may include acquiring locks in a specific order, using higher isolation levels, or limiting transaction duration.
  4. Deadlock Avoidance: The DBMS analyzes the transaction’s lock requests and determines whether granting a lock will lead to a deadlock. If a potential deadlock is detected, the transaction is delayed until the requested locks are available.

13. What are database indexes, and what are the different types of indexes?

Database indexes are data structures that improve the speed of data retrieval operations on a database table. They work like a roadmap, allowing the database management system (DBMS) to locate specific rows in a table more efficiently. Indexes are created on one or more columns of a table, and they contain a sorted copy of the indexed column data along with pointers to the corresponding rows.

Different types of indexes include:

  1. Single-Column Index: This is the most common type of index and is created on a single column of a table.
SQL
CREATE INDEX idx_column_name ON table_name (column_name);
  1. Composite Index: A composite index is created on multiple columns. It is helpful when queries involve conditions on multiple columns simultaneously.
SQL
CREATE INDEX idx_column1_column2 ON table_name (column1, column2);
  1. Unique Index: A unique index enforces the uniqueness of values in the indexed column(s). It ensures that no two rows have the same values in the indexed column(s).
SQL
CREATE UNIQUE INDEX idx_unique_column ON table_name (column_name);
  1. Clustered Index: In some databases, the primary key automatically creates a clustered index. A clustered index determines the physical order of data in the table. Each table can have only one clustered index, and it significantly affects the performance of data retrieval.
SQL
-- Example of a primary key (which creates a clustered index)
ALTER TABLE table_name ADD CONSTRAINT pk_column PRIMARY KEY (column_name);
  1. Non-Clustered Index: Non-clustered indexes have a separate data structure from the table and include pointers to the actual rows. A table can have multiple non-clustered indexes.
SQL
CREATE INDEX idx_non_clustered_column ON table_name (column_name);

Indexes are essential for improving the performance of frequently executed queries, but they also come with a cost in terms of storage and maintenance. It is crucial to create indexes judiciously based on the query patterns and the overall database workload.

14. What is database replication?

Database replication is the process of copying and synchronizing data from one database (the source) to one or more replica databases (the targets). The purpose of database replication is to provide high availability, data redundancy, and disaster recovery capabilities.

Replication can be implemented in different configurations, including:

  1. Master-Slave Replication: In this configuration, there is one master database that handles write operations, and one or more slave databases that replicate the data from the master. Slaves are read-only and used for read-heavy operations, reducing the load on the master.
  2. Master-Master Replication: In a master-master configuration, multiple databases act as both masters and slaves. Each master can handle both read and write operations, and data changes made on any master are replicated to others.
  3. Multi-Level Replication: This involves multiple levels of replication, where data from a master database is replicated to intermediate databases, which, in turn, replicate to other databases. This configuration is useful for distributing data across different regions.

15. What is the difference between a clustered and non-clustered index?

Clustered IndexNon-Clustered Index
Determines the physical order of data in the tableHas a separate data structure from the table
Each table can have only one clustered indexA table can have multiple non-clustered indexes
Changes to the indexed columns affect the physical order of dataChanges to the indexed columns do not affect the physical order of data
Typically used on the primary key columnUsed on other frequently queried columns
Faster for retrieving large ranges of dataFaster for retrieving specific data based on indexed columns
Slower for data modification operations (INSERT, UPDATE, DELETE)Faster for data modification operations
Example: PRIMARY KEY constraint creates a clustered indexExample: CREATE INDEX idx_column ON table_name (column);

16. What is a database view?

A database view is a virtual table that is derived from the data in one or more underlying tables (base tables). It does not store any data itself; instead, it retrieves and displays data dynamically from the base tables. Views are defined by SQL queries, and their results are based on the current data in the underlying tables.

Views provide several benefits, including:

  1. Simplified Data Access: Views encapsulate complex queries and present a simplified and customized view of data to users, hiding the underlying table structure.
  2. Data Security: Views can restrict access to sensitive data by exposing only specific columns or rows to certain users or roles.
  3. Data Abstraction: Views can combine data from multiple tables and present it as a single virtual table, simplifying data access for users.

Example (using SQL syntax):
Let’s create a view that displays employee details for the “HR” department.

SQL
CREATE VIEW HR_Employees AS
SELECT employee_id, employee_name, department_id
FROM employees
WHERE department_id = 1;

To select data from the view:

SQL
SELECT * FROM HR_Employees;

17. What is database normalization and denormalization?

Database Normalization:
Database normalization is the process of organizing data in a relational database to eliminate data redundancy and improve data integrity. It involves breaking down a large table into smaller, more manageable tables and establishing relationships between them. The goal is to reduce data duplication and ensure that each piece of data is stored in one place only.

Normalization is achieved through different normal forms (1NF, 2NF, 3NF, etc.), each addressing specific data redundancy issues. By normalizing a database, it becomes more efficient, flexible, and easier to maintain.

Database Denormalization:
Database denormalization is the opposite process, where normalized tables are intentionally combined or aggregated to form larger, less normalized tables. Denormalization is done to improve query performance by reducing the number of joins needed for common queries. It can speed up read-heavy operations at the cost of some data redundancy.

Denormalization is often used in data warehousing and reporting scenarios, where fast data retrieval is crucial, and data modifications are less frequent.

The decision to normalize or denormalize a database depends on the specific requirements and use cases of the application.

18. What are database constraints?

Database constraints are rules or conditions defined on the columns of a database table to enforce data integrity and validity. Constraints prevent the insertion of invalid or inconsistent data into the database, ensuring that the data remains accurate and reliable. When a constraint is violated, the DBMS rejects the operation and returns an error.

Common types of database constraints include:

  1. Primary Key: Ensures the uniqueness and non-null property of a column or a combination of columns. It uniquely identifies each row in the table.
  2. Unique Key: Enforces the uniqueness of values in a column or a combination of columns but allows NULL values.
  3. Foreign Key: Establishes a relationship between two tables by linking a column or a set of columns in one table to the primary key of another table.
  4. Check Constraint: Applies a condition to limit the range of acceptable values for a column.
  5. Not Null Constraint: Ensures that a column cannot contain NULL values.
  6. Default Constraint: Assigns a default value to a column if no value is specified during an INSERT operation.

19. What is the difference between a primary key and a unique key?

Primary KeyUnique Key
Uniquely identifies each row in the tableEnforces uniqueness but allows NULL values
Has a NOT NULL constraintMay have NULL values
A table can have only one primary keyA table can have multiple unique keys
Typically used for identifying rows in the tableUsed to ensure the uniqueness of columns for data integrity
Automatically creates a clustered index (in some databases)Does not automatically create a clustered index
Example: CREATE TABLE table_name (column_name INT PRIMARY KEY, …);Example: CREATE TABLE table_name (column_name INT UNIQUE, …);

20. What is the role of the SQL SELECT statement?

The SQL SELECT statement is used to retrieve data from a database table or a combination of tables. It is one of the core SQL commands and forms the basis for querying and analyzing data in a relational database.

The basic syntax of the SELECT statement is as follows:

SQL
SELECT column1, column2, ...
FROM table_name;

The SELECT statement performs the following tasks:

  1. Projection: Specifies the columns to be retrieved from the table(s).
  2. Selection: Allows filtering rows based on specified conditions using the WHERE clause.
  3. Joining: Combines data from multiple tables using JOIN clauses.
  4. Aggregation: Calculates aggregate functions (e.g., SUM, COUNT, AVG) using GROUP BY and HAVING clauses.
  5. Sorting: Sorts the result set based on specified columns using the ORDER BY clause.

Advanced Questions

1. What is ACID in the context of database transactions?

ACID is an acronym that stands for Atomicity, Consistency, Isolation, and Durability. These are the four key properties that ensure the reliability and integrity of database transactions.

  • Atomicity: Atomicity ensures that a transaction is treated as a single, indivisible unit of work. Either all the operations within the transaction are successfully completed, or none of them take effect. If any part of the transaction fails, the entire transaction is rolled back to its initial state, leaving the database unchanged.
  • Consistency: Consistency ensures that a transaction brings the database from one valid state to another. It means that all the database constraints and rules are applied during the transaction, so the database remains in a consistent state before and after the transaction.
  • Isolation: Isolation ensures that multiple transactions can operate concurrently without interfering with each other. Each transaction is executed in isolation, as if it were the only transaction running on the database. This property prevents issues like dirty reads, non-repeatable reads, and phantom reads.
  • Durability: Durability guarantees that once a transaction is committed, its changes are permanent and will survive any subsequent failures, such as power outages or crashes. The changes made by committed transactions are stored safely and persistently in the database.

2. What is the difference between a clustered and a non-clustered index?

Clustered IndexNon-Clustered Index
A clustered index determines the physical order of data rows in a table.A non-clustered index does not alter the physical order of data rows; it creates a separate structure.
A table can have only one clustered index.A table can have multiple non-clustered indexes.
Because the data rows are stored in the order of the clustered index, it is more efficient for retrieval.Retrieval can be slightly slower compared to a clustered index because it involves an additional lookup.
When a new row is added to a table with a clustered index, it affects the physical order of the table.Inserting data does not impact the physical order of the table as it creates a separate index structure.
SQL Server automatically creates a clustered index on the primary key if one doesn’t already exist.SQL Server automatically creates a non-clustered index on the primary key if one doesn’t already exist.
Updating the columns included in the clustered index can be slower since it may require reordering the data.Updating the columns included in the non-clustered index is relatively faster as it doesn’t affect data order.

3. What is a composite key in a database?

A composite key is a key that consists of two or more columns in a database table. Unlike a single-column primary key, a composite key requires a combination of columns to uniquely identify each row in the table. It allows for more precise and specific identification of records by considering multiple attributes simultaneously.

For example, let’s say we have a table named “Employees” with columns “EmployeeID” and “DepartmentID.” If we want to ensure that each combination of EmployeeID and DepartmentID is unique, we can create a composite key on both columns. This means that the same EmployeeID can exist in multiple rows as long as it is associated with a different DepartmentID.

Here’s an example of creating a composite key in SQL:

SQL
CREATE TABLE Employees (
    EmployeeID INT,
    DepartmentID INT,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    -- Other columns
    PRIMARY KEY (EmployeeID, DepartmentID)
);

4. What are the different types of database relationships?

There are three main types of database relationships:

  1. One-to-One (1:1): In a one-to-one relationship, one record in a table is associated with only one corresponding record in another table, and vice versa. This relationship is less common, but it can be useful to split a large table into two separate ones for organizational or performance reasons.
  2. One-to-Many (1:N): In a one-to-many relationship, one record in a table is associated with multiple records in another table, but each record in the second table is associated with only one record in the first table. This is the most common type of relationship and is used to represent hierarchical or nested data.
  3. Many-to-Many (N:M): In a many-to-many relationship, multiple records in one table are associated with multiple records in another table. To represent such a relationship, an intermediate table, known as a junction or associative table, is used. It contains foreign keys from both tables and serves to link the related records together.

5. What is the difference between a subquery and a join in SQL?

SubqueryJoin
A subquery is a query nested within another query. It is enclosed within parentheses and is usually executed first, returning a result set to be used by the outer query.A join is used to combine rows from two or more tables based on a related column between them.
Subqueries are typically used to filter data, compute aggregates, or check conditions for a specific set of data.Joins are used to retrieve data from related tables by matching columns specified in the join condition.
Subqueries can be written within SELECT, INSERT, UPDATE, and DELETE statements.Joins can be written using different types, such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN, each providing different ways to combine the data.
Subqueries are executed first, and their results are then used by the outer query.Joins are executed at the same time as the main query, and the result set is constructed by combining the matching rows from the involved tables.
Subqueries are often used when working with aggregated data or when a query depends on the outcome of another query.Joins are used when you need to combine data from multiple tables based on common columns.

Example of a Subquery:

SQL
SELECT Name, DepartmentID
FROM Employees
WHERE DepartmentID IN (
    SELECT DepartmentID
    FROM Departments
    WHERE Location = 'New York'
);

Example of a Join:

SQL
SELECT Employees.Name, Departments.DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

6. What is database normalization and why is it important?

Database normalization is the process of organizing a database schema to reduce data redundancy and dependency, ensuring that data is stored efficiently and without anomalies. It involves breaking down a large table into smaller, related tables and defining relationships between them. The goal of normalization is to eliminate data duplication and improve data integrity, making it easier to maintain and query the database.

Normalization is important for the following reasons:

  • Data Integrity: By eliminating redundancy, normalization minimizes the risk of data inconsistencies and update anomalies. It ensures that each piece of data is stored in only one place, reducing the chance of conflicting information.
  • Efficient Storage: Normalized databases take up less disk space since data is stored in smaller tables without unnecessary duplication.
  • Query Performance: Normalization enables efficient querying as related data is stored together, reducing the need for complex joins in queries.
  • Ease of Maintenance: With a well-normalized database, changes to the data structure are simpler and less error-prone. Modifications only need to be made in one place.
  • Scalability: Normalized databases are more adaptable to future changes and expansions, making them more scalable.

7. What is denormalization and when is it appropriate to use?

Denormalization is the process of intentionally introducing redundancy into a database schema that has been previously normalized. It involves merging normalized tables or adding redundant data to improve performance or simplify certain types of queries. Denormalization is appropriate in scenarios where the performance gains outweigh the potential risks of data redundancy.

Denormalization is suitable in the following situations:

  • Improved Read Performance: In read-heavy applications, denormalization can be used to reduce the number of joins and simplify complex queries, resulting in faster data retrieval.
  • Aggregation and Reporting: For reporting purposes, denormalization can pre-calculate and store aggregated data, reducing the need for expensive computations during runtime.
  • Reduced Joins: In some cases, joins in a highly normalized schema can be resource-intensive. Denormalization can help reduce the number of joins required for common queries.
  • Caching: Denormalization can be used to store frequently accessed data in a cache, reducing the need to access the database for every request.

8. What is a database index and how does it improve query performance?

A database index is a data structure that improves the speed of data retrieval operations on a database table. It acts like a roadmap that helps the database engine quickly locate the rows that match specific search criteria, reducing the need for full-table scans and speeding up query performance.

When a database table is indexed, the database engine creates a separate data structure that holds a sorted copy of selected columns from the table. This data structure allows the database to jump directly to the location of the desired data, rather than scanning the entire table sequentially.

Benefits of using database indexes to improve query performance:

  • Faster Data Retrieval: Indexes significantly speed up SELECT queries by reducing the number of disk I/O operations and minimizing the amount of data that needs to be processed.
  • Efficient Searching: Queries that involve WHERE clauses, JOINs, and ORDER BY clauses can be performed more efficiently with the help of indexes.
  • Avoiding Full-Table Scans: Indexes allow the database to access only the relevant rows, even for large tables, avoiding the need to scan the entire table.
  • Optimized Aggregate Functions: Indexes can speed up aggregate functions like SUM, AVG, COUNT, etc., as the database can quickly locate the required data.

9. What is the difference between a primary key and a unique key?

Primary KeyUnique Key
A primary key is a column or a set of columns that uniquely identify each record in a table.A unique key is a column or a set of columns that enforce uniqueness but allow for NULL values.
There can be only one primary key in a table.There can be multiple unique keys in a table.
A primary key column cannot have NULL values.A unique key column allows for one NULL value (in case of single-column key) or multiple NULLs (in case of multi-column key).
A primary key automatically creates a clustered index in most database systems (if not already present).A unique key creates a non-clustered index by default (if not already present).
The primary key is typically used to establish relationships with foreign keys in related tables.The unique key is mainly used to enforce data integrity and ensure uniqueness in the column(s).

Example of a Primary Key:

SQL
CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    -- Other columns
);

Example of a Unique Key:

SQL
CREATE TABLE Students (
    StudentID INT,
    StudentEmail VARCHAR(100) UNIQUE,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    -- Other columns
);

10. What is the difference between a database index and a database view?

Database IndexDatabase View
A database index is a data structure that improves the speed of data retrieval on a specific table.A database view is a virtual table derived from one or more underlying tables.
An index is created to speed up SELECT, JOIN, and WHERE operations by efficiently locating data.A view is created to simplify complex queries, provide an additional level of security, or present data in a specific format.
Indexes are physical structures stored in the database, separate from the tables they index.Views are logical structures that do not store data; they are defined by a query and dynamically generate results.
The purpose of an index is to optimize read operations, improving query performance.Views can encapsulate complex logic and provide a simplified and consistent interface to users.
Indexes are transparent to users and applications; they are automatically used by the database engine.Views are visible to users as virtual tables and can be queried like regular tables.
Creating an index requires careful consideration, as it affects the database’s storage and performance.Creating a view involves defining the query that defines the view’s data and can include joins, filtering, and calculations.

Example of creating a Database Index:

SQL
CREATE INDEX idx_EmployeeLastName ON Employees (LastName);

Example of creating a Database View:

SQL
CREATE VIEW EmployeeView AS
SELECT EmployeeID, FirstName, LastName, DepartmentID
FROM Employees
WHERE DepartmentID = 1;

11. What is the difference between a stored procedure and a function in a database?

Stored ProcedureFunction
A stored procedure is a set of precompiled SQL statements that are stored in the database server.A function is a database object that contains a set of SQL statements and returns a single value.
Stored procedures can perform data manipulation, such as INSERT, UPDATE, DELETE, and SELECT queries.Functions can only return a single value, and they are primarily used to compute and return data.
Stored procedures may or may not return a value. If they do, the return value is optional.Functions are designed to return a value explicitly using the RETURN statement.
Stored procedures can have input parameters, output parameters, or both.Functions accept input parameters but cannot have output parameters.
Stored procedures can perform non-deterministic actions and execute procedural logicFunctions must be deterministic, meaning they always produce the same output for given input.
Stored procedures can be called using the EXECUTE or EXEC keywordFunctions are used within SQL statements and can be called from queries.

Example of a Stored Procedure:

SQL
CREATE PROCEDURE sp_GetEmployeeCount
AS
BEGIN
    SELECT COUNT(*) AS EmployeeCount FROM Employees;
END;

Example of a Function:

SQL
CREATE FUNCTION fn_GetEmployeeCount()
RETURNS INT
AS
BEGIN
    DECLARE @EmployeeCount INT;
    SELECT @EmployeeCount = COUNT(*) FROM Employees;
    RETURN @EmployeeCount;
END;

12. What is the difference between a left join and a right join in SQL?

Left JoinRight Join
A left join returns all the records from the left (or first) table and the matching records from the right (or second) table.A right join returns all the records from the right (or second) table and the matching records from the left (or first) table.
In a left join, if there is no match in the right table, the result will contain NULL values for the right table columns.In a right join, if there is no match in the left table, the result will contain NULL values for the left table columns.
The left join keyword is written as LEFT JOIN or LEFT OUTER JOIN.The right join keyword is written as RIGHT JOIN or RIGHT OUTER JOIN.
The left table is the one that appears before the LEFT JOIN keyword in the SQL query.The right table is the one that appears before the RIGHT JOIN keyword in the SQL query.
Left joins are commonly used to retrieve all records from one table and matching records from another table.Right joins are less common and are used to retrieve all records from the right table and matching records from the left table.

Example of a Left Join:

SQL
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
LEFT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Example of a Right Join:

SQL
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
RIGHT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

13. What is a materialized view and how is it different from a regular view?

A materialized view is a database object that stores the results of a query, allowing faster data retrieval by avoiding the need to recompute the query result every time it is accessed. It is a physical copy of the data obtained from a regular view or a complex query, and it is periodically refreshed to keep the data up-to-date.

The main difference between a materialized view and a regular view lies in how they store and maintain data:

Regular View:

  • A regular view is a virtual table that does not store data itself.
  • It is defined by a SQL query and is dynamically executed every time it is referenced.
  • The data presented by a regular view is always up-to-date as it reflects the current state of the underlying tables.

Materialized View:

  • A materialized view is a physical table that stores the query result as data.
  • It must be explicitly refreshed to update its data, either on-demand or according to a predefined schedule.
  • Materialized views are useful for improving query performance, especially when dealing with complex and time-consuming queries, by pre-computing and storing the results.

14. What is database sharding and how does it improve scalability?

Database sharding is a technique used to horizontally partition a large database into smaller, more manageable parts called shards. Each shard contains a subset of the data, and together, all the shards hold the entire dataset. The goal of sharding is to improve database scalability and performance by distributing the workload across multiple database instances or servers.

In a sharded database:

  • Data is distributed across multiple servers or nodes, allowing each shard to handle a portion of the total data.
  • Each shard operates independently and can be located on a separate physical server or cluster.
  • Queries and transactions are distributed across the shards, reducing the load on any individual server and improving overall performance.

Database sharding improves scalability in the following ways:

  1. Increased Data Handling Capacity: By distributing data across multiple shards, each shard can handle a smaller portion of the data, allowing the system to accommodate larger datasets and higher data volumes.
  2. Improved Query Performance: Sharding reduces the size of individual tables, which can improve query performance and response times, especially for read-heavy workloads.
  3. Better Horizontal Scaling: Adding new shards allows the database to scale horizontally by adding more servers, enabling it to handle more concurrent users and requests.
  4. Isolation of Data: Shards are isolated from each other, reducing the potential impact of failures on the overall system. A problem with one shard does not affect the other shards.

15. What is a database transaction deadlock and how can it be resolved?

A database transaction deadlock occurs when two or more transactions are waiting for each other to release resources, preventing any of the transactions from proceeding. It creates a deadlock situation where none of the involved transactions can make progress, leading to a system stall.

Deadlocks can happen in systems that use concurrent processing and involve multiple transactions that require exclusive access to shared resources (e.g., tables, rows, or locks). Deadlocks are typically caused by poorly designed application logic or incorrect handling of transactions.

To resolve a database transaction deadlock, there are several approaches:

  1. Timeouts: Set a timeout for transactions so that if a transaction is waiting for a resource for too long, it will be automatically rolled back, breaking the deadlock.
  2. Deadlock Detection and Resolution: Implement mechanisms that can detect deadlocks and automatically resolve them by selecting one of the transactions to be rolled back, freeing the resources, and allowing the other transaction(s) to proceed.
  3. Lock Hierarchy: Ensure that transactions acquire locks on resources in a consistent order to minimize the chances of circular dependencies.
  4. Transaction Reordering: Rework the application logic or queries to access resources in a consistent order, reducing the likelihood of deadlocks.
  5. Application-Level Handling: Modify the application to handle deadlock errors gracefully and retry the transaction or take appropriate actions to recover from the deadlock situation.

16. What is the purpose of database normalization beyond third normal form (3NF)?

The purpose of database normalization beyond the Third Normal Form (3NF) is to further refine the database schema to eliminate certain types of data anomalies that can still exist in 3NF-compliant databases. These higher levels of normalization (e.g., Boyce-Codd

Normal Form, Fourth Normal Form, and Fifth Normal Form) are essential for more complex databases and data models.

The benefits of normalization beyond 3NF include:

  1. Minimizing Data Redundancy: Higher normal forms ensure that data is stored efficiently, reducing the chances of duplicate information and potential data inconsistencies.
  2. Data Integrity and Accuracy: By eliminating anomalies like update, insertion, and deletion anomalies, data integrity is maintained, and the accuracy of information is ensured.
  3. Simpler Data Maintenance: Normalized databases are easier to maintain, as modifications to the data structure are localized and do not lead to cascading changes.
  4. Improved Query Performance: In some cases, higher normalization can lead to more efficient query execution, as tables are smaller, and joins can be simpler.
  5. Facilitating Complex Queries: Normalized databases can easily handle more complex queries due to the organized and structured nature of the data.

17. What are database constraints and why are they important?

Database constraints are rules and conditions applied to columns or tables in a database to maintain data integrity and enforce business rules. Constraints help ensure that data meets certain criteria, preventing the insertion of invalid or inconsistent data into the database.

Types of database constraints include:

  1. Primary Key: Ensures the uniqueness of a column or a set of columns, acting as a unique identifier for each record in the table.
  2. Foreign Key: Establishes a link between two tables by enforcing referential integrity, ensuring that values in one table’s column correspond to values in another table’s column.
  3. Unique Key: Ensures that the values in a column or a set of columns are unique, but unlike primary keys, unique keys allow for NULL values.
  4. Check Constraint: Applies a condition to a column, limiting the range of values that can be inserted or updated.
  5. Not Null Constraint: Ensures that a column cannot contain NULL values.
  6. Default Constraint: Sets a default value for a column if no value is provided during an insert operation.

Database constraints are important for several reasons:

  • Data Integrity: Constraints help maintain data accuracy and consistency, preventing the insertion of invalid or conflicting data.
  • Data Validation: Constraints validate the data before it is stored in the database, reducing the likelihood of data-related errors.
  • Referential Integrity: Foreign key constraints ensure that relationships between tables are maintained, preventing orphans or broken links.
  • Enforced Business Rules: Constraints enforce business rules and data requirements specified by the application, ensuring that the data adheres to predefined guidelines.
  • Data Security: Constraints can enhance data security by limiting the range of allowed values and preventing unauthorized access.

18. How does indexing impact insert, update, and delete operations in a database?

Indexing can have both positive and negative impacts on database insert, update, and delete operations:

Insert Operations:

  • Positive Impact: Indexes can slightly slow down insert operations since the database needs to update the index data structure whenever new records are inserted. However, the impact is generally not significant, especially for non-clustered indexes.
  • Negative Impact: If a table has many indexes, the overhead of maintaining multiple indexes during insert operations can be more noticeable and might affect overall performance.

Update Operations:

  • Positive Impact: For indexed columns used in WHERE clauses, updates can benefit from faster access to the data rows, leading to improved performance.
  • Negative Impact: Updating indexed columns can be slower, especially for clustered indexes, as the database may need to rearrange data to maintain the index’s sorting order.

Delete Operations:

  • Positive Impact: Similar to update operations, delete operations can benefit from faster access to data rows when using indexed columns in WHERE clauses.
  • Negative Impact: Deleting records from a table with indexes can be slower due to the additional overhead of updating the index data structure.

19. What is a database trigger and what are its use cases?

A database trigger is a special type of stored procedure that automatically executes in response to specific database events, such as INSERT, UPDATE, DELETE, or DDL (Data Definition Language) statements. Triggers are associated with tables and can be defined to fire either before or after the triggering event.

Use cases for database triggers include:

  1. Enforcing Data Integrity: Triggers can enforce complex business rules and data validation checks that go beyond what can be achieved using constraints. For example, a trigger can prevent certain data changes based on specific conditions.
  2. Auditing and Logging: Triggers can be used to create audit trails by automatically recording changes made to certain tables, including the old and new values.
  3. Synchronization: Triggers can help maintain data consistency across multiple related tables. For example, when an insert occurs in one table, a trigger can automatically insert related data in another table.
  4. Automated Calculations: Triggers can perform automated calculations or data transformations based on changes in the data.
  5. Security and Access Control: Triggers can be used to implement access controls, ensuring that only authorized users can perform certain actions on the database.
  6. Replication: Triggers can be used to capture changes made to a table and replicate those changes to another database or system.

20. Explain the concept of database replication and its benefits.

Database replication is the process of copying and maintaining data from one database (the source) to one or more databases (the replicas) in real-time or near-real-time. Replication is typically used to improve data availability, data distribution, and data redundancy.

Benefits of database replication include:

  1. Improved Data Availability: Replicas can be used as backups, ensuring that data remains accessible even if the primary database experiences downtime or failures.
  2. Load Balancing: Replicas can distribute read operations across multiple database instances, reducing the load on the primary database and improving overall system performance.
  3. Geographical Distribution: Replicas can be located in different geographical locations, allowing data to be closer to users and improving response times.
  4. Disaster Recovery: Replicas can act as disaster recovery solutions, providing a standby database that can quickly take over in case of a primary database failure.
  5. Reporting and Analytics: Replicas can be dedicated to reporting and analytics purposes, offloading read-heavy queries from the primary database.
  6. High Availability: Replication can improve the availability of critical data by allowing quick failover to a replica if the primary database becomes unavailable.

MCQ Questions

1. What is a database?

a) A collection of related data
b) A program that manages data
c) A language for creating tables
d) A hardware device for storing data
Answer: a) A collection of related data

2. What is DBMS?

a) Database Management System
b) Data Backup and Management System
c) Digital Business Management System
d) Data Branch and Management Service
Answer: a) Database Management System

3. What is a primary key in a database?

a) A key used to unlock the database
b) A key that uniquely identifies a record in a table
c) A key used for encryption in a database
d) A key used for sorting records in a table
Answer: b) A key that uniquely identifies a record in a table

4. Which of the following is not a type of database model?

a) Relational model
b) Hierarchical model
c) Object-oriented model
d) Linear model
Answer: d) Linear model

5. What is SQL?

a) Structured Query Language
b) Simple Query Language
c) Sequential Query Language
d) Structured Query Logic
Answer: a) Structured Query Language

6. What is a foreign key in a database?

a) A key used for importing data from another database
b) A key used for connecting multiple databases
c) A key used for indexing records in a table
d) A key that refers to the primary key in another table
Answer: d) A key that refers to the primary key in another table

7. Which SQL command is used to retrieve data from a database?

a) INSERT
b) UPDATE
c) SELECT
d) DELETE
Answer: c) SELECT

8. What is normalization in database design?

a) Removing redundancy and ensuring data consistency
b) Splitting a database into multiple tables
c) Creating relationships between tables
d) Defining primary and foreign keys
Answer: a) Removing redundancy and ensuring data consistency

9. Which of the following is not a database management system?

a) Oracle
b) MySQL
c) Microsoft Excel
d) PostgreSQL
Answer: c) Microsoft Excel

10. What is the purpose of an index in a database?

a) To store large binary data
b) To speed up data retrieval
c) To enforce data integrity constraints
d) To define relationships between tables
Answer: b) To speed up data retrieval

11. What is a transaction in a database?

a) A unit of work performed on a database
b) A method for connecting to a database
c) A type of query language
d) A way to store data in a database
Answer: a) A unit of work performed on a database

12. Which SQL command is used to add data to a database?

a) INSERT
b) UPDATE
c) SELECT
d) DELETE
Answer: a) INSERT

13. What is the purpose of a view in a database?

a) To store large binary data
b) To speed up data retrieval
c) To define relationships between tables
d) To provide a virtual representation of data
Answer: d) To provide a virtual representation of data

14. Which SQL command is used to modify data in a database?

a)INSERT
b) UPDATE
c) SELECT
d) DELETE
Answer: b) UPDATE

15. What is a join in a database?

a) Combining data from multiple tables based on a related column
b) Combining data from multiple databases
c) Combining data from multiple fields in a table
d) Combining data from multiple columns in a table
Answer: a) Combining data from multiple tables based on a related column

16. What is ACID in the context of database transactions?

a) Atomicity, Consistency, Isolation, Durability
b) Availability, Compatibility, Integrity, Durability
c) Atomicity, Compatibility, Isolation, Durability
d) Availability, Consistency, Integrity, Durability
Answer: a) Atomicity, Consistency, Isolation, Durability

17. Which SQL command is used to delete data from a database?

a) INSERT
b) UPDATE
c) SELECT
d) DELETE
Answer: d) DELETE

18. What is a schema in a database?

a) A graphical representation of a database
b) A collection of database objects
c) A type of database model
d) A table in a database
Answer: b) A collection of database objects

19. Which SQL command is used to modify the structure of a database?

a) INSERT
b) UPDATE
c) ALTER
d) DELETE
Answer: c) ALTER

20. What is a stored procedure in a database?

a) A query that retrieves data from multiple tables
b) A predefined set of SQL statements stored in the database
c) A table that stores intermediate results during data processing
d) A way to enforce data integrity constraints
Answer: b) A predefined set of SQL statements stored in the database

21. What is a trigger in a database?

a) A type of SQL statement
b) A database backup mechanism
c) A program that automatically executes in response to certain events
d) A way to encrypt data in a database
Answer: c) A program that automatically executes in response to certain events

22. What is the purpose of a database index?

a) To enforce data integrity constraints
b) To define relationships between tables
c) To speed up data retrieval
d) To store large binary data
Answer: c) To speed up data retrieval

23. What is the difference between a primary key and a unique key in a database?

a) A primary key can have duplicate values, while a unique key cannot
b) A unique key can have duplicate values, while a primary key cannot
c) A primary key is used for sorting records, while a unique key is not
d) There is no difference between a primary key and a unique key
Answer: b) A unique key can have duplicate values, while a primary key cannot

24. What is a database transaction?

a) A unit of work performed on a database
b) A method for connecting to a database
c) A type of query language
d) A way to store data in a database
Answer: a) A unit of work performed on a database

25. What is a foreign key constraint in a database?

a) A rule that ensures data consistency between related tables
b) A key used for connecting multiple databases
c) A key used for indexing records in a table
d) A key that refers to the primary key in another table
Answer: a) A rule that ensures data consistency between related tables

26. Which SQL command is used to create a new table in a database?

a) INSERT
b) UPDATE
c) SELECT
d) CREATE
Answer: d) CREATE

27. What is the purpose of database normalization?

a) To remove redundancy and ensure data consistency
b) To combine multiple databases into a single database
c) To speed up data retrieval
d) To define relationships between tables
Answer: a) To remove redundancy and ensure data consistency

28. Which SQL command is used to drop a table from a database?

a) INSERT
b) UPDATE
c) SELECT
d) DROP
Answer: d) DROP

29. What is a view in a database?

a) A virtual representation of data based on a query
b) A backup copy of a database
c) A table that stores intermediate results during data processing
d) A way to enforce data integrity constraints
Answer: a) A virtual representation of data based on a query

30. What is the purpose of a database trigger?

a) To enforce data integrity constraints
b) To define relationships between tables
c) To automatically execute a program in response to certain events
d) To speed up data retrieval
Answer: c) To automatically execute a program in response to certain events

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button

Table of Contents

Index
Becoming a Full Stack Developer in 2023 How to Become a Software Engineer in 2023
Close

Adblock Detected

Please consider supporting us by disabling your ad blocker!