0% found this document useful (0 votes)
24 views18 pages

Dbms th-2

The document provides an extensive overview of SQL commands, constraints, operators, transaction properties, concurrency control, and distributed databases. It explains various SQL concepts such as data types, joins, aggregate functions, and special operators, along with examples for clarity. Additionally, it discusses concurrency control issues, the Two-Phase Commit Protocol, and the importance of distributed transparency in database systems.

Uploaded by

unnatibariya046
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views18 pages

Dbms th-2

The document provides an extensive overview of SQL commands, constraints, operators, transaction properties, concurrency control, and distributed databases. It explains various SQL concepts such as data types, joins, aggregate functions, and special operators, along with examples for clarity. Additionally, it discusses concurrency control issues, the Two-Phase Commit Protocol, and the importance of distributed transparency in database systems.

Uploaded by

unnatibariya046
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Sure, let's break down each of these questions:

1.​ SQL Commands:​

CREATE: This command is used to create a new table, view, index, or other database object.
Example:​
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50)
);

○​

ALTER: ALTER is used to modify an existing database object like a table. Example:​
ALTER TABLE employees ADD COLUMN salary DECIMAL(10,2);

○​

DROP: DROP is used to delete an existing database object like a table or index. Example:​
DROP TABLE employees;

○​

DELETE: DELETE is used to remove rows from a table based on certain conditions. Example:​
DELETE FROM employees WHERE id = 1;

○​

COMMIT: COMMIT is used to permanently save any changes made during the current
transaction. Example:​
COMMIT;

○​
2.​ SQL Constraints: SQL constraints are rules enforced on data columns to ensure data
integrity. Some common constraints include:​

○​ PRIMARY KEY: Ensures uniqueness of each row in a table.


○​ FOREIGN KEY: Enforces referential integrity between two tables.
○​ UNIQUE: Ensures uniqueness of values in a column.
○​ NOT NULL: Ensures a column cannot have NULL values.
3.​ SQL Operators:​
LIKE: Used to search for a specified pattern in a column. Example:​
SELECT * FROM employees WHERE name LIKE 'J%';

○​

BETWEEN: Used to select values within a range. Example:​


SELECT * FROM products WHERE price BETWEEN 10 AND 100;

○​

IN: Used to specify multiple values in a WHERE clause. Example:​


SELECT * FROM employees WHERE department IN ('HR', 'Finance');

○​
4.​ Logical Operators: SQL uses logical operators to combine conditions:​

AND: Retrieves rows where all conditions are true. Example:​


SELECT * FROM employees WHERE department = 'IT' AND salary > 50000;

○​

OR: Retrieves rows where at least one condition is true. Example:​


SELECT * FROM employees WHERE department = 'HR' OR department = 'Finance';

○​

NOT: Negates a condition. Example:​


SELECT * FROM employees WHERE NOT department = 'IT';

○​
5.​ Transaction Properties:​

○​ Atomicity: Ensures that either all operations within a transaction are completed
or none are.
○​ Consistency: Ensures that the database remains in a valid state before and
after the transaction.
○​ Isolation: Ensures that transactions operate independently of each other.
○​ Durability: Ensures that once a transaction is committed, its changes are
permanent even in case of system failure.

Here are the answers to your questions:

6. What is concurrency control, and what are its objectives?


Concurrency control is a database management technique that ensures transactions are
executed in a way that maintains database consistency and integrity when multiple transactions
occur simultaneously.

Objectives of Concurrency Control:

●​ Maintain Consistency: Ensures that the database remains consistent despite


concurrent transactions.
●​ Avoid Conflicts: Prevents issues like lost updates, dirty reads, and uncommitted data
access.
●​ Ensure Isolation: Guarantees that transactions do not interfere with each other.
●​ Improve Performance: Allows concurrent execution while maintaining efficiency.

7. What are the different levels of lock granularity? Explain with example

Lock granularity refers to the level at which database locking is applied to control concurrent
access.

Types of Lock Granularity:

1.​ Database-Level Lock: Locks the entire database.


○​ Example: LOCK DATABASE mydb;
2.​ Table-Level Lock: Locks an entire table.
○​ Example: LOCK TABLE employees IN EXCLUSIVE MODE;
3.​ Page-Level Lock: Locks a page in memory that contains records.
4.​ Row-Level Lock: Locks a specific row in a table.

Example:​
SELECT * FROM employees WHERE id = 1 FOR UPDATE;

○​
5.​ Column-Level Lock: Locks a specific column in a table.

8. Explain concurrency control with stamping methods.

Timestamp-based concurrency control assigns unique timestamps to each transaction to


maintain serializability.

Types of Timestamp Ordering:

1.​ Basic Timestamp Ordering:


○​ Every transaction gets a timestamp (TS).
○​ If TS(T1) < TS(T2), T1 executes first to maintain order.
2.​ Strict Timestamp Ordering:
○​ Ensures strict execution order, avoiding conflicts.
3.​ Optimistic Timestamp Ordering:
○​ Transactions execute without restrictions and are validated before committing.

Example:

●​ T1 (timestamp = 100) writes to record R.


●​ T2 (timestamp = 200) wants to read R.
●​ T2 is allowed since it follows TS(T1) < TS(T2).

9. What are Distributed Database and Distributed Processing? Explain


using a Diagram.

Distributed Database:

A distributed database is a collection of interconnected databases that are spread across


multiple locations.

Distributed Processing:

Distributed processing refers to the use of multiple computers to process data stored in a
distributed database.

Example Diagram:

[ User 1 ] <---> [ Server 1 (DB1) ]


[ User 2 ] <---> [ Server 2 (DB2) ]
[ User 3 ] <---> [ Server 3 (DB3) ]

Each server holds a portion of the database, and users can access data from any server.

10. Explain Two-Phase Commit Protocol.

The Two-Phase Commit (2PC) Protocol ensures that a distributed transaction is either
committed fully or aborted across multiple databases.

Phases:

1.​ Prepare Phase:


○​ The coordinator asks all participating databases if they can commit the
transaction.
○​ Each participant responds with "Yes" (prepared) or "No" (abort).
2.​ Commit Phase:
○​ If all say "Yes," the coordinator sends a commit message.
○​ If any say "No," the coordinator sends a rollback message.

Example Scenario:

1.​ A bank transfers money between two branches.


2.​ Both databases must confirm the transaction before committing.
3.​ If one fails, the transaction is rolled back to maintain consistency.

11. What is Distributed Transparency? List and explain different types of


distributed transparency

Distributed Transparency refers to the ability of a distributed database system to hide the
complexities of data distribution from users, making it appear as a single unified system.

Types of Distributed Transparency:

1.​ Access Transparency:​

○​ Users can access data without knowing where it is stored.


○​ Example: A user queries SELECT * FROM employees;, but the table is
distributed across multiple servers.
2.​ Location Transparency:​

○​ Users don’t need to know the physical location of the data.


○​ Example: Data might be stored in different branches of a bank, but users access
it as if it is in one place.
3.​ Replication Transparency:​

○​ Users don’t need to know if data is replicated across multiple locations.


○​ Example: If a copy of customer data exists in multiple servers, the system
automatically manages updates.
4.​ Fragmentation Transparency:​

○​ Users don’t need to know if data is divided into fragments.


○​ Example: An orders table might be split by region, but queries retrieve data
seamlessly.
5.​ Failure Transparency:​

○​ The system continues to operate despite failures.


○​ Example: If one database server fails, another takes over without the user
noticing.

12. Explain SPSD and MPMD.

SPSD (Single Program Single Data)

●​ A single program processes a single dataset.


●​ Example: A simple payroll system that processes salaries for one employee at a time.

MPMD (Multiple Program Multiple Data)

●​ Multiple programs run simultaneously, processing different datasets.


●​ Example: A large-scale banking system handling multiple customer transactions across
different locations.

13. Explain aggregate functions with example.

Aggregate functions perform calculations on multiple rows and return a single value.

Common Aggregate Functions:


SUM(): Returns the sum of values.​
SELECT SUM(salary) FROM employees;

1.​

AVG(): Returns the average value.​


SELECT AVG(price) FROM products;

2.​

COUNT(): Returns the number of rows.​


SELECT COUNT(*) FROM employees;

3.​

MAX(): Returns the highest value.​


SELECT MAX(salary) FROM employees;
4.​

MIN(): Returns the lowest value.​


SELECT MIN(price) FROM products;

5.​

14. Explain Date and Time Functions.

Date and time functions allow operations on date/time values.

Common Functions:
CURRENT_DATE: Returns today’s date.​
SELECT CURRENT_DATE;

1.​

NOW(): Returns the current date and time.​


SELECT NOW();

2.​

DATE_ADD(): Adds a specified interval to a date.​


SELECT DATE_ADD('2024-03-18', INTERVAL 7 DAY);

3.​

DATE_SUB(): Subtracts a specified interval from a date.​


SELECT DATE_SUB('2024-03-18', INTERVAL 3 MONTH);

4.​

YEAR(), MONTH(), DAY(): Extracts parts of a date.​


SELECT YEAR('2024-03-18'); -- Returns 2024
SELECT MONTH('2024-03-18'); -- Returns 3

5.​

15. List types of Joins and explain any two with example.

Types of Joins:

1.​ INNER JOIN


2.​ LEFT JOIN (LEFT OUTER JOIN)
3.​ RIGHT JOIN (RIGHT OUTER JOIN)
4.​ FULL JOIN (FULL OUTER JOIN)
5.​ CROSS JOIN
6.​ SELF JOIN

Explanation with Example:

1. INNER JOIN (Most Common Join)

●​ Returns only matching rows from both tables.

Example:​
SELECT employees.id, employees.name, departments.dept_name
FROM employees
INNER JOIN departments ON employees.dept_id = departments.dept_id;

●​

2. LEFT JOIN (LEFT OUTER JOIN)

●​ Returns all rows from the left table and matching rows from the right table.

Example:​
SELECT employees.id, employees.name, departments.dept_name
FROM employees
LEFT JOIN departments ON employees.dept_id = departments.dept_id;

●​
○​ If an employee has no department, dept_name will be NULL.

16. Explain String Functions.

SQL String functions manipulate and process text data in a database.

Common String Functions:


UPPER() – Converts a string to uppercase.​
SELECT UPPER('hello'); -- Output: HELLO

1.​

LOWER() – Converts a string to lowercase.​


SELECT LOWER('HELLO'); -- Output: hello

2.​
LENGTH() – Returns the length of a string.​
SELECT LENGTH('SQL Query'); -- Output: 9

3.​

CONCAT() – Joins two or more strings.​


SELECT CONCAT('Hello', ' ', 'World'); -- Output: Hello World

4.​

SUBSTRING() – Extracts a portion of a string.​


SELECT SUBSTRING('Database', 1, 4); -- Output: Data

5.​

TRIM() – Removes leading and trailing spaces.​


SELECT TRIM(' SQL '); -- Output: SQL

6.​

17. Discuss following Special Operators giving example

i. LIKE (Pattern Matching)

●​ Used to search for a pattern in a column.

Example:​
SELECT * FROM employees WHERE name LIKE 'A%'; -- Names starting with 'A'

●​

ii. BETWEEN (Range Selection)

●​ Used to filter results within a range.

Example:​
SELECT * FROM products WHERE price BETWEEN 100 AND 500;

●​

iii. IN (Matches a List of Values)

●​ Used to check if a value exists in a given set.


Example:​
SELECT * FROM employees WHERE department IN ('HR', 'Finance', 'IT');

●​

iv. IS NULL (Checks for NULL Values)

●​ Used to find records with NULL values.

Example:​
SELECT * FROM employees WHERE manager_id IS NULL;

●​

v. EXISTS (Checks if a Subquery Returns Results)

●​ Used to check the existence of records in a subquery.

Example:​
SELECT * FROM employees WHERE EXISTS (SELECT * FROM departments WHERE
employees.dept_id = departments.dept_id);

●​

18. Discuss SQL Datatypes.

SQL data types define the type of data stored in a column.

Common SQL Data Types:

1.​ Numeric Data Types:​

○​ INT (Integer)
○​ FLOAT (Floating-point)
○​ DECIMAL(10,2) (Fixed decimal precision)
2.​ String Data Types:​

○​ VARCHAR(n) (Variable-length string)


○​ CHAR(n) (Fixed-length string)
○​ TEXT (Large text data)
3.​ Date/Time Data Types:​

○​ DATE (YYYY-MM-DD)
○​ TIME (HH:MM:SS)
○​ DATETIME (YYYY-MM-DD HH:MM:SS)
4.​ Boolean Data Type:​

○​ BOOLEAN (Stores TRUE or FALSE)


5.​ Binary Data Types:​

○​ BLOB (Binary Large Object, stores images, files, etc.)

19. Differentiate between DROP and TRUNCATE command.


Feature DROP TRUNCATE

Definition Deletes the entire table, including Deletes all rows but keeps table
structure structure

Rollback No No
Possible?

Speed Slower, as it removes table Faster, as it only removes data


definition

Usage DROP TABLE employees; TRUNCATE TABLE employees;

20. Discuss SQL Operators.

SQL Operators are used in queries to perform comparisons and calculations.

Types of SQL Operators:

1.​ Arithmetic Operators: (+, -, *, /, %)​


Example:​
SELECT salary + 500 AS new_salary FROM employees;

○​
2.​ Comparison Operators: (=, !=, <, >, <=, >=)​

Example:​
SELECT * FROM products WHERE price > 1000;

○​
3.​ Logical Operators: (AND, OR, NOT)​

Example:​
SELECT * FROM employees WHERE salary > 50000 AND department = 'IT';

○​
4.​ Bitwise Operators: (&, |, ^, <<, >>)​

Example:​
SELECT 5 & 3; -- Output: 1 (Bitwise AND)

○​

21. What is a Transaction? Explain its Properties.

A transaction in SQL is a sequence of one or more database operations that are executed as a
single unit of work. Transactions ensure that the database remains consistent even in cases of
failures.

Properties of Transactions (ACID):

1.​ Atomicity:​

○​ Ensures all operations in a transaction are completed successfully or none at all.


○​ Example: Transferring money between two accounts must either debit and credit
both accounts or not happen at all.
2.​ Consistency:​

○​ Ensures the database remains in a valid state before and after the transaction.
○​ Example: A product’s stock count must be updated correctly when a purchase is
made.
3.​ Isolation:​

○​ Ensures transactions do not interfere with each other.


○​ Example: Two users ordering the last item in stock should not both succeed.
4.​ Durability:​

○​ Ensures that committed transactions are permanently stored, even in case of a


system crash.
○​ Example: Once a bank transfer is successful, it cannot be undone due to power
failure.

22. What is Concurrency Control? Explain Problems Faced Without


Concurrency Control.

Concurrency control ensures multiple transactions executing simultaneously do not interfere


with each other and maintain database integrity.

Problems Faced Without Concurrency Control:

1.​ Lost Update Problem:​

○​ Two transactions update the same data, and one update is lost.

Example:​
-- Transaction 1

UPDATE accounts SET balance = balance - 500 WHERE id = 1;

-- Transaction 2

UPDATE accounts SET balance = balance - 200 WHERE id = 1;

○​ If both transactions read the same balance and update it without considering the
other’s changes, one update is lost.
2.​ Dirty Read:​

○​ A transaction reads uncommitted data from another transaction.


○​ Example: If one transaction updates a salary but rolls back, another transaction
reading the uncommitted salary will get incorrect data.
3.​ Non-Repeatable Read:​

○​ A transaction reads the same row twice, but another transaction modifies it in
between.
Example:​
SELECT balance FROM accounts WHERE id = 1;

-- Another transaction updates the balance

SELECT balance FROM accounts WHERE id = 1;

○​ The values might be different.


4.​ Phantom Read:​

○​ A transaction reads a set of rows, but another transaction inserts/deletes rows in


between.
○​ Example: If a report is generated based on an employee count and another
transaction adds an employee before the report finishes, the count will be
inconsistent.

23. Explain Concurrency Control with Optimistic Methods.

Optimistic Concurrency Control (OCC) assumes transactions rarely conflict and allows them
to proceed without locks, verifying at the end if conflicts exist.

Phases of OCC:

1.​ Read Phase:


○​ The transaction reads data without locking it.
2.​ Validation Phase:
○​ Before committing, the system checks if another transaction has modified the
data.
3.​ Write Phase:
○​ If validation succeeds, changes are committed; otherwise, the transaction is
aborted and retried.

Example:

1.​ Transaction A reads a stock value of 50.


2.​ Transaction B also reads the stock value of 50 and sells 5 items.
3.​ Transaction B updates the stock to 45.
4.​ When Transaction A tries to update stock (assuming still 50), OCC detects the change
and aborts Transaction A.
24. What is Transaction Transparency? List and Explain Different Types of
Transaction Transparency.

Transaction Transparency ensures that distributed transactions are executed seamlessly as if


they were occurring on a single database.

Types of Transaction Transparency:

1.​ Distributed Transaction Transparency:​

○​ Ensures a transaction spanning multiple databases appears as a single


transaction.
○​ Example: Transferring money between banks using different databases.
2.​ Replication Transparency:​

○​ Ensures users do not know if data is being replicated across different locations.
○​ Example: Customer data available in different branches but appearing as a single
entity.
3.​ Fragmentation Transparency:​

○​ Ensures users do not need to know if data is stored in fragments across multiple
locations.
○​ Example: A product table is split by region, but users retrieve it as a whole.
4.​ Failure Transparency:​

○​ Ensures transactions are completed even if failures occur.


○​ Example: A power failure should not leave a bank transfer incomplete.

25. Explain the Following Set Operations with Example.

Set operations combine results from multiple queries.

i. UNION (Removes Duplicates)

●​ Combines two result sets and removes duplicates.

Example:​
SELECT city FROM customers

UNION

SELECT city FROM suppliers;

●​
ii. UNION ALL (Keeps Duplicates)

●​ Similar to UNION, but retains duplicate values.

Example:​
SELECT city FROM customers

UNION ALL

SELECT city FROM suppliers;

●​

iii. INTERSECT (Common Records)

●​ Returns only common rows between two queries.

Example:​
SELECT city FROM customers

INTERSECT

SELECT city FROM suppliers;

●​

iv. MINUS (Difference)

●​ Returns rows in the first query that do not exist in the second.

Example:​
SELECT city FROM customers

MINUS

SELECT city FROM suppliers;

●​
Here are the correct answers:

1.​ UNIQUE constraint ensures that all values in a column are unique.​

2.​ True – DDL stands for Data Definition Language.​

3.​ (a) DROP – The SQL keyword DROP is used to delete a Table structure.​

4.​ (b) % and _ – LIKE operator uses % (matches any sequence of characters) and _
(matches a single character) for pattern matching.​

5.​ True – A Transaction can be either completely committed or completely aborted


(Atomicity principle of ACID).​

6.​ Two-Phase Locking Protocol has Growing and Shrinking phase.​

7.​ (a) Transaction Log – Using Transaction Log, we can recover our database
transaction.​

8.​ (b) Data Processor – DP stands for Data Processor.​

9.​ True – Distributed processing requires a distributed database, but a distributed


database does not necessarily require distributed processing.​

10.​MPSD (Massively Parallel System Design)​

11.​False – TO_DATE function converts a string to a date format but does not return
today's date. (SYSDATE returns today’s date in SQL).​
Here are the correct answers:
12.​Cross join is also known as Cartesian Join.​

13.​False – UNION operator removes duplicate rows; UNION ALL includes duplicates.​

14.​True – The default order in ORDER BY clause is ascending (ASC).​

15.​NOT NULL constraint ensures that column’s value should not be NULL.​

16.​False – DML stands for Data Manipulation Language, not Data Multiplication
Language.​

17.​(D) DELETE – The SQL keyword DELETE is used to delete table’s content (Data).​
18.​(a) BETWEEN works similar to AND, and IN operator works similar to OR.​

19.​(b) Transaction Processor – TP stands for Transaction Processor.​

20.​The Data Processor is also known as Data Processing Unit (DPU).​

21.​SPSD (Single Processor Single Data).​

22.​True – SYSDATE function returns today’s date in SQL.​

23.​Cartesian Product of rows can be achieved using CROSS JOIN.​

24.​False – INTERSECT operator returns only common rows and removes duplicates.​

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy