0% found this document useful (0 votes)
6 views13 pages

Dbms Answer

The document outlines SQL schema change statements, including CREATE, ALTER, DROP, RENAME, TRUNCATE, and COMMENT, along with examples for each. It also explains data manipulation commands like INSERT, DELETE, and UPDATE, and discusses correlated nested queries, JOINs, GROUP BY, triggers, views, and design guidelines for relational schemas. Additionally, it covers functional dependencies, normal forms (2NF, 3NF, BCNF), ACID properties, and the need for concurrency control in databases.

Uploaded by

bhavya
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)
6 views13 pages

Dbms Answer

The document outlines SQL schema change statements, including CREATE, ALTER, DROP, RENAME, TRUNCATE, and COMMENT, along with examples for each. It also explains data manipulation commands like INSERT, DELETE, and UPDATE, and discusses correlated nested queries, JOINs, GROUP BY, triggers, views, and design guidelines for relational schemas. Additionally, it covers functional dependencies, normal forms (2NF, 3NF, BCNF), ACID properties, and the need for concurrency control in databases.

Uploaded by

bhavya
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/ 13

1Describe the following with examples for each.

i) SQL Schema change statements

In SQL (Structured Query Language), schema change statements are used to modify the structure of a database schema, which
includes changing tables, columns, constraints, indexes, and other objects. These statements fall under the Data Definition Language
(DDL) category.

Below is a detailed explanation of the main SQL schema change statements:

1. CREATE

Used to create new database objects like tables, views, indexes, schemas, etc.

Syntax:

CREATE TABLE table_name (


column1 datatype constraints,
column2 datatype constraints,
...
);

Example:

CREATE TABLE employees (


emp_id INT PRIMARY KEY,
name VARCHAR(100),
salary DECIMAL(10, 2)
);

2. ALTER

Used to modify an existing database object, such as a table or column. It is the most common schema change command.

Common Use Cases of ALTER:

a. Add a Column:

ALTER TABLE table_name


ADD column_name datatype;

Example:

ALTER TABLE employees


ADD department VARCHAR(50);

b. Modify a Column:

ALTER TABLE table_name


MODIFY column_name new_datatype;

Note: In some databases like PostgreSQL, use ALTER COLUMN.

Example (MySQL):

ALTER TABLE employees


MODIFY salary DECIMAL(12, 2);

c. Rename a Column:

ALTER TABLE table_name


RENAME COLUMN old_name TO new_name;
Example:

ALTER TABLE employees


RENAME COLUMN name TO full_name;

d. Drop a Column:

ALTER TABLE table_name


DROP COLUMN column_name;

Example:

ALTER TABLE employees


DROP COLUMN department;

3. DROP

Used to delete an entire database object, such as a table, view, index, or even the entire schema.

a. Drop a Table:

DROP TABLE table_name;

Example:

DROP TABLE employees;

4. RENAME

Used to rename a table or other database object.

Syntax

ALTER TABLE old_table_name


RENAME TO new_table_name;

Example:

ALTER TABLE employees


RENAME TO staff;

5. TRUNCATE

Not exactly a schema change, but often discussed with DDL commands. It deletes all records from a table but retains the structure.

Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE employees;

6. COMMENT

Used to add descriptions to tables, columns, etc. Useful for documentation.

Example:

COMMENT ON COLUMN employees.salary IS 'Annual salary in USD';


7. CREATE INDEX and DROP INDEX

Used to manage indexes, which improve query performance but also affect the schema design.

Create Index:

CREATE INDEX idx_name ON table_name (column1);

Drop Index:

DROP INDEX idx_name ON table_name;

ii) INSERT, DELETE, and UPDATE statements in SQL


In SQL, three commands can be used to modify the database: INSERT, DELETE, and
UPDATE.
The INSERT Command

 INSERT is used to add a single tuple to a relation. We must specify the relation name and a
list of values for the tuple.
 While adding values for all the columns of the table, need not specify the column names in
the SQL query. The values should be listed in the same order in which the corresponding
attributes were specified in the CREATE TABLE command.
 The INSERT INTO syntax would be as follows:

INSERT INTO table_name VALUES (value1, value2, value3, ...);


For example, to add a new tuple to the EMPLOYEE relation shown.
INSERT INTO EMPLOYEE VALUES ( ‘Richard’, ‘K’, ‘Marini’, ‘653298653’, ‘1962-
12-30’, ’98 Oak Forest, Katy, TX’, ‘M’, 37000, ‘653298653’, 4 );

The DELETE Command

 The DELETE command removes tuples from a relation. The WHERE clause, selects the
tuples to be deleted. Tuples are explicitly deleted from only one table at a time.
 The deletion propagates to tuples in other relations if referential triggered actions(on delete
cascade) are specified in the referential integrity constraints of the DDL.
 A missing WHERE clause specifies that all tuples in the relation are to be deleted;
however, the table remains in the database as an empty table. The DROP TABLE command
to remove the table definition.
Example:
DELETE FROM EMPLOYEE
WHERE Lname=‘Brown’;

The UPDATE Command


 The UPDATE command is used to modify attribute values of one or more selected Tuples,
the WHERE clause in the UPDATE command selects the tuples to be modified from a
single relation.
 Updating a primary key value may propagate to the foreign key values of tuples in other
relations if such a referential triggered action(on update cascade) is specified in the
referential integrity constraints of the DDL.
 An additional SET clause in the UPDATE command specifies the attributes to be modified
and their new values.
For example
UPDATE PROJECT SET Plocation = ‘Bellaire’, Dnum = 5 WHERE Pnumber=10;

2. Explain the following with examples for each.


i) Correlated Nested Queries

Definition:

A correlated nested query (also called a correlated subquery) is a subquery that depends on the outer
query for its values. It is executed repeatedly, once for each row selected by the outer query.

Key Characteristics:

 Uses a value from the outer query inside the subquery.


 Cannot run independently.
 Commonly used for row-wise comparisons.

Example: Find employees who earn more than the average salary of their department

Tables:

 employees(emp_id, name, salary, dept_id)

SQL Query:

SELECT name, salary, dept_id


FROM employees e1
WHERE salary >
(
SELECT AVG(salary)
FROM employees e2
WHERE e1.dept_id = e2.dept_id
);

ii) To List the Names of Managers Who Have at Least One Dependent

Assumed Table Structures:

 employees(emp_id, name, manager_id)


 dependents(dep_id, emp_id, dep_name)
SELECT DISTINCT e.name
FROM employees e
WHERE e.emp_id IN
(
SELECT manager_id
FROM employees
WHERE emp_id IN
(
SELECT emp_id
FROM dependents
)
);

Explanation:

The innermost subquery:


SELECT emp_id FROM dependents returns employee IDs who have at least one dependent.

The middle subquery:


SELECT manager_id FROM employees WHERE emp_id IN (...) fetches the manager IDs of those employees
who have dependents.

The outer query:


SELECT name FROM employees WHERE emp_id IN (...) retrieves the names of managers who manage at
least one employee with a dependent.

3. With examples Explain the following:

i) Join in SQL

A JOIN in SQL is used to combine rows from two or more tables based on a related column between them
(usually a foreign key relationship).

Types of JOINs:

Type Description

INNER JOIN Returns only the matching rows between the tables

LEFT JOIN Returns all rows from the left table and matching rows from the right

RIGHT JOIN Returns all rows from the right table and matching rows from the left

FULL JOIN Returns all rows when there is a match in one of the tables

Example: INNER JOIN


Query:
Tables:
SELECT e.name, d.dept_name
employees(emp_id, name, dept_id) FROM employees e
departments(dept_id, dept_name) INNER JOIN departments d
ON e.dept_id = d.dept_id;
ii) GROUP BY
GROUP BY is used to group rows that have the same values in specified columns. It is commonly used with
aggregate functions like COUNT(), SUM(), AVG(), MIN(), MAX().

Example: Total salary by department

Table:

employees(emp_id, name, salary, dept_id)

Query:

SELECT dept_id, SUM(salary) AS total_salary


FROM employees
GROUP BY dept_id;

HAVING Clause

HAVING is used to filter the results of groups created by GROUP BY. It's like a WHERE clause, but for groups (not
individual rows).

Example: Departments with total salary > 100,000

SELECT dept_id, SUM(salary) AS total_salary


FROM employees
GROUP BY dept_id
HAVING SUM(salary) > 100000;

4. Explain Triggers in SQL with examples

A trigger is a stored procedure in a database that automatically executes (fires) in response to certain events
on a particular table or view.

Think of it as an automatic action that happens when you INSERT, UPDATE, or DELETE data.

Triggers Used:

 Automatically enforcing business rules


 Validating data
 Maintaining audit logs
 Performing automatic calculations or updates
 Cascading changes across tables

Trigger Events:

A trigger can be set to fire:

 BEFORE an operation (before insert/update/delete)


 AFTER an operation (after insert/update/delete)
 INSTEAD OF an operation (mainly for view)

Syntax (Generic):

CREATE TRIGGER trigger_name


{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- trigger logic here
END;

Example : Audit Trigger – Log all deletions from employees table

Tables:

 employees(emp_id, name, salary)


 employee_audit(emp_id, deleted_at)

SQL Trigger:

CREATE TRIGGER trg_employee_delete


AFTER DELETE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit(emp_id, deleted_at)
VALUES (OLD.emp_id, NOW());
END;

5. What is VIEW? And explain the concept of Views in SQL with examples

Views in SQL are virtual tables based on the result of an SQL query. They do not store data themselves but
provide a way to look at and manipulate the result of a query as if it were a table.

Example:

CREATE VIEW HighSalaryEmployees AS


SELECT EmpID, EmpName, Salary
FROM Employees
WHERE Salary > 50000;

In this example, a view called HighSalaryEmployees is created based on the result of a query that selects
employees with a salary greater than 50,000. Once the view is created, you can query it as if it were a table:

SELECT * FROM HighSalaryEmployees;

Benefits of Views:

1. Simplicity: They simplify complex queries by encapsulating them in a view.


2. Security: You can restrict access to certain data by allowing users to query a view instead of the base table.
3. Data Abstraction: Views provide an abstraction layer over the database schema.

3aExplain Informal design guidelines for relation schema with examples

● Making sure that the semantics of the attributes is clear in the schema
● Reducing the redundant information in tuples
● Reducing the NULL values in tuples
● Disallowing the possibility of generating spurious tuples

Making sure that the semantics of the attributes is clear in the schema

 Definition: Relation attributes should have clear real-world meanings.


 Importance: A well-designed relation schema is easier to explain and interpret.
 Example: The EMPLOYEE schema clearly represents employee data, with attributes like name and
department number, indicating an implicit relationship with the DEPARTMENT schema.
 Guideline: Design schemas to ensure each relation corresponds to a single entity or relationship to avoid
semantic ambiguity.

Reducing the redundant information in tuples


 Redundancy: Grouping attributes can lead to repeated information across tuples, wasting space.
 Anomalies:
 Insertion Anomalies: Difficulty adding new data (e.g., a new employee) without needing to fill in
all department details.
 Deletion Anomalies: Removing a record can unintentionally lose essential data (e.g., deleting the
last employee removes department info).
 Modification Anomalies: Changes require updates in multiple places, risking inconsistencies.
 Guideline: Structure schemas to prevent these anomalies.

Reducing the NULL values in tuples


 Problem: Excessive NULL values can complicate understanding andoperations.
 Guideline: Minimize attributes with frequent NULL values and consider separate relations for those
attributes to maintain clarity.

Disallowing the possibility of generating spurious tuples


 Concern: Poorly designed relations can lead to unexpected tuples in results when joining or querying.
 Example: Combining multiple entities or relationships can create tuple that do not accurately represent
the intended relationships.
 Guideline: Ensure design avoids configurations that could lead to spurious data.

6. What are Functional Dependencies? And explain the following Normal forms
with relation example for each. i) 2NF ii) 3NF iii) BCNF
A functional dependency (FD) is a relationship between two sets of attributes in a relation (table). It expresses
a constraint between attributes such that:

If two rows have the same value for attribute A, they must have the same value for attribute B.

This is written as: A → B (A functionally determines B)

i) Second Normal Form (2NF)

A relation is in 2NF if:

1. It is already in First Normal Form (1NF).


2. It has no partial dependency (i.e., no non-prime attribute depends on part of a composite primary
key).

Example:

Table: StudentCourse

student_id course_id student_name course_name

101 C1 Alice Math

101 C2 Alice Physics

102 C1 Bob Math


ii) Third Normal Form (3NF)
A relation is in 3NF if:

1. It is in 2NF.
2. There is no transitive dependency (i.e., non-prime attribute should not depend on another non-prime
attribute).

Example:

Table: Employee

emp_id emp_name dept_id dept_name

1 Alice D1 Sales

2 Bob D2 HR

3 Carol D1 Sales

iii) Boyce-Codd Normal Form (BCNF)


A relation is in BCNF if:

1. It is in 3NF.
2. For every non-trivial functional dependency X → Y, X must be a super key.

Example:

Table: ProfessorSubject

prof_id subject department

P1 Math Science

P2 Physics Science

P1 Math Science

7. Explain ACID properties with examples

The ACID properties ensure that database transactions are processed reliably.
They are:
1. Atomicity: Ensures that all operations within a transaction are completed. If any part of the transaction
fails, the entire transaction is rolled back, and the database remains unchanged.
Example: If a bank transfer transaction debits one account but fails to credit another, the entire transaction
is reversed.
2. Consistency: Ensures that a transaction brings the database from one valid state to another. The
database must meet all the rules and constraints after the transaction.
Example: If a transaction violates any constraints, such as a foreign key constraint, the database should be
rolled back.
3. Isolation: Ensures that transactions are executed in isolation from one another. Intermediate results of a
transaction are not visible to other transactions until the transaction is committed.
Example: If two users try to update the same account balance simultaneously, isolation ensures that both
transactions are handled in a serializable manner.
4. Durability: Ensures that once a transaction is committed, it remains so, even in the event of a system
crash. The results of the transaction are permanently stored in the database.
Example: Once a bank transfer transaction is committed, it is reflected in the database even if the system
crashes immediately afterward.

8. Why Concurrency control is needed? Demonstrate with an example

Concurrency control is essential in a database management system (DBMS) to ensure the consistency,
integrity, and isolation of data when multiple transactions are executed concurrently.

When multiple users or applications access and modify the database at the same time, problems like data
inconsistency, lost updates, dirty reads, or uncommitted data can occur. Concurrency control mechanisms
help prevent these issues.

Example Demonstrating the Need for Concurrency Control

Scenario: Bank Account Transfer

Assume a bank database with a table Accounts having the following record:

Account_No Balance

1001 5000

Two transactions, T1 and T2, are executed concurrently:

 T1: Withdraws ₹1000 from account 1001


 T2: Deposits ₹500 into account 1001

Without Concurrency Control (Interleaved Execution)


Step Transaction T1 Transaction T2

1 Read Balance = 5000

2 Read Balance = 5000

3 Balance = 5000 - 1000 = 4000

4 Balance = 5000 + 500 = 5500

5 Write Balance = 4000

6 Write Balance = 5500

Final Balance = 5500, but it should be 4500.

This is a case of lost update problem, where the update from T1 is overwritten by T2.
With Concurrency Control (Serial Execution)

Either:

 T1 executes fully first, then T2:


Final Balance = (5000 - 1000) + 500 = 4500

Or:

 T2 executes fully first, then T1:


Final Balance = (5000 + 500) - 1000 = 4500

In both serial executions, data integrity is preserved.

9. Explain the Two-phase locking protocol used for concurrency control.

Concurrency control ensures correct execution of multiple transactions occurring simultaneously without
violating data integrity. One major approach is locking, where access to data items is controlled using locks.

1. Types of Locks and System Lock Tables

Locks are variables associated with data items to indicate whether a transaction can access them.

Binary Locks

 States: Each lock has two states:


o 0 (unlocked)
o 1 (locked)
 Locking Rules:
o Each item X has an associated LOCK(X) value.
o If LOCK(X) = 1, the item is already in use and cannot be accessed.
o If LOCK(X) = 0, the transaction can access the item by setting LOCK(X) = 1.
 Operations:
o lock_item(X): Lock the item X.
o unlock_item(X): Unlock the item X.
 Limitation: Only one transaction can access the item at a time—even for read-only operations, which is
unnecessarily restrictive.

Shared/Exclusive Locks (Read/Write Locks)

To allow greater concurrency, the multiple-mode lock approach is used. This allows:

 Multiple transactions to read an item simultaneously (shared/read lock)


 Only one transaction to write to the item (exclusive/write lock)

States of LOCK(X):

 Unlocked
 Read-locked (Shared Lock): Multiple transactions can read.
 Write-locked (Exclusive Lock): Only one transaction can read/write.
Locking Rules

A transaction must:

1. Acquire a lock before access:


o read_lock(X) before read_item(X)
o write_lock(X) before write_item(X)
2. Release the lock after use:
o unlock(X) after finishing with item X
3. Respect lock state:
o Cannot acquire a lock it already holds unless conversion is allowed.

Conversion of Locks

To improve flexibility, lock conversions are permitted:

 Upgrading (Shared → Exclusive):


o A transaction that holds a read lock on X can request a write lock on X.
o Allowed only if no other transaction holds a read lock on X.
 Downgrading (Exclusive → Shared):
o A transaction that holds a write lock on X can downgrade to a read lock, allowing others to also
read X.

Two-Phase Locking Protocol (2PL)

To maintain serializability, transactions must follow two phases:

1. Growing Phase:
o Can acquire any number of locks.
o No unlocks allowed.
2. Shrinking Phase:
o Can release locks.
o No new locks allowed.

10. What is document based NOSQL systems? basic operations CRUD in


MongoDB
A Document-Based NoSQL system is a type of NoSQL database that stores data in the form of
documents, typically using JSON (JavaScript Object Notation) or BSON (Binary JSON) format.

CRUD Operations in MongoDB

CRUD stands for:

 Create
 Read
 Update
 Delete

MongoDB uses a JavaScript-like syntax in its queries and operations.

1. Create (Insert)

 Insert one document:

db.students.insertOne({
name: "Alice",
age: 21,
course: "Computer Science"
});

 Insert multiple documents:

db.students.insertMany([
{ name: "Bob", age: 22, course: "Math" },
{ name: "Charlie", age: 20, course: "Physics" }
]);

2. Read (Query)

 Find one document:

db.students.findOne({ name: "Alice" });

 Find all documents:

db.students.find({});

 Find with condition:

db.students.find({ age: { $gt: 20 } });

3. Update

 Update one document:

db.students.updateOne(
{ name: "Alice" },
{ $set: { age: 22 } }
);

 Update multiple documents:

db.students.updateMany(
{ course: "Math" },
{ $set: { grade: "A" } }
);

4. Delete

 Delete one document:

db.students.deleteOne({ name: "Alice" });

 Delete multiple documents:

db.students.deleteMany({ age: { $lt: 21 } });

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