0% found this document useful (0 votes)
3 views15 pages

dbms

Query optimization in DBMS is crucial for enhancing performance, efficient resource use, and faster response times, especially with large datasets. It involves selecting the most cost-effective execution plans and supports scalability. Additionally, the document discusses entity and referential integrity constraints, the disadvantages of Cartesian products, relational algebra operations, views, SQL types, triggers, and reasons for NULL values in databases.

Uploaded by

paulrohit85
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)
3 views15 pages

dbms

Query optimization in DBMS is crucial for enhancing performance, efficient resource use, and faster response times, especially with large datasets. It involves selecting the most cost-effective execution plans and supports scalability. Additionally, the document discusses entity and referential integrity constraints, the disadvantages of Cartesian products, relational algebra operations, views, SQL types, triggers, and reasons for NULL values in databases.

Uploaded by

paulrohit85
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/ 15

📌 Why Do We Need Query Optimization in DBMS?

Query Optimization is essential to make database queries run faster and use fewer
resources.

✅ Main Reasons:
1.​ Improve Performance​

○​ Optimized queries take less time to execute.​

○​ Useful especially when working with large datasets.​

2.​ Efficient Resource Use​

○​ Reduces CPU, memory, and disk I/O usage.​

3.​ Faster Response Time​

○​ Improves user experience, especially in real-time applications.​

4.​ Cost-Based Decision Making​

○​ DBMS chooses the cheapest query execution plan among alternatives.​

5.​ Scalability​

○​ Helps handle more users or larger data efficiently.​

🛠️ Example:
sql
CopyEdit
SELECT * FROM Orders WHERE CustomerID = 5;

●​ Without index: full table scan ❌​


●​ With index: direct row access ✅ → Faster!​

In short, query optimization ensures faster, cheaper, and better data retrieval.

📌 Entity Integrity & Referential Integrity Constraints


🔹 1. Entity Integrity Constraint
Definition:​
Ensures that the primary key of a table cannot be NULL.

Why important?

●​ It guarantees that each row in a table is uniquely identifiable.​

●​ Prevents having records without identity.​

Example:

sql
CopyEdit
CREATE TABLE Students (
RollNo INT PRIMARY KEY,
Name VARCHAR(50)
);

Here, RollNo cannot be NULL — ensures entity integrity ✅

🔹 2. Referential Integrity Constraint


Definition:​
Ensures that the foreign key in one table must match a primary key in another table (or be
NULL).

Why important?
●​ Maintains valid relationships between tables.​

●​ Prevents orphan records and ensures consistency.​

Example:

sql
CopyEdit
CREATE TABLE Enrollments (
RollNo INT,
CourseID VARCHAR(10),
FOREIGN KEY (RollNo) REFERENCES Students(RollNo)
);

Here, you cannot insert a RollNo in Enrollments unless it exists in Students.

✅ Importance Summary:
Constraint Purpose Prevents

Entity Integrity Unique identity for records NULL or duplicate primary keys

Referential Integrity Valid links between tables Orphan/invalid foreign keys

Let me know if you want this as a diagram or handwritten-style note!

4o

You said:
) What is the disadvantage of Cartesian product and how to recover from it?

ChatGPT said:

📌 Disadvantage of Cartesian Product in DBMS


Cartesian Product (also called cross join) returns every possible combination of rows from
two tables.

❌ Disadvantage:
●​ Produces a very large result set​
→ If Table A has m rows and Table B has n rows, result = m × n rows​

●​ Often meaningless without a proper WHERE or JOIN condition​

●​ Consumes more memory and time​

●​ Can slow down performance significantly​

💡 Example:
sql
CopyEdit
SELECT * FROM Students, Courses;

●​ If 100 students and 10 courses → Output = 1000 rows 😵​


●​ Most of them are not logically related​

✅ How to Recover from It:


Use proper JOIN conditions to limit the result:

sql
CopyEdit
SELECT * FROM Students
JOIN Enrollments ON Students.RollNo = Enrollments.RollNo;

OR

Use a WHERE clause to add condition:

sql
CopyEdit
SELECT * FROM Students, Courses
WHERE Students.CourseID = Courses.CourseID;
Summary:​
Avoid Cartesian product unless intended, and always use JOINs or WHERE conditions to
create meaningful results.

4o

You said:
. What do you mean by unary and binary operations in Relational algebra? Give example.

ChatGPT said:

📌 Unary and Binary Operations in Relational Algebra


🔹 Unary Operations
Operate on a single relation (table).

✅ Examples:
1.​ Selection (σ) – Picks rows that satisfy a condition​
σ(Dept = 'CSE')(Student)​

2.​ Projection (π) – Picks specific columns​


π(Name, RollNo)(Student)​

3.​ Rename (ρ) – Renames the relation or attributes​


ρ(S)(Student)​

🔹 Binary Operations
Operate on two relations.

✅ Examples:
1.​ Union (∪)​
Student ∪ Alumni​
2.​ Set Difference (−)​
Student − Alumni​

3.​ Cartesian Product (×)​


Student × Course​

4.​ Join (⨝)​


Student ⨝ Course​

✅ Summary Table:
Operation Type Operators Example

Unary Selection (σ), Projection (π) σ(Age > 18)(Student)

Binary Union (∪), Join (⨝), Product (×) Student ⨝ Enrollments

a) Theta (θ) Join

A theta join is a general join that combines tuples from two relations based on any condition
(θ).

θ can be: =, >, <, >=, <=, !=

Example:

sql
CopyEdit
R ⨝ (R.A < S.B) S

b) Database Models

Database models define the structure of a database.

Types:

1.​ Hierarchical Model – Tree-like structure (1-to-many)​


2.​ Network Model – Graph-like, allows many-to-many​

3.​ Relational Model – Tables (relations), most popular​

4.​ Object-Oriented Model – Stores objects with attributes and methods​

c) Inner Join vs Outer Join


Join Type Description

Inner Join Returns only matching rows from both


tables

Outer Join Returns matching + non-matching rows

Types of Outer Join:

●​ Left Outer Join – All rows from left + matches from right​

●​ Right Outer Join – All rows from right + matches from left​

●​ Full Outer Join – All rows from both sides, matching or not​

d) Tuple Relational Calculus (TRC)

TRC is a non-procedural query language based on logic.

It uses tuple variables to express what data to retrieve.

Syntax:

text
CopyEdit
{ t | P(t) }

Where t is a tuple and P(t) is a condition.

Example:
text
CopyEdit
{ t | t ∈ Student AND t.age > 18 }

e) Degree of Relationship

It refers to the number of entities involved in a relationship.

Types:

●​ Unary – One entity (e.g., employee manages employee)​

●​ Binary – Two entities (e.g., student enrolls in course)​

●​ Ternary – Three entities (e.g., doctor treats patient in hospital)​

Let me know if you want diagrams or handwritten-style notes for any of these!

4o

You said:
. Explain the terms View

ChatGPT said:

📌 View in DBMS
A View is a virtual table created by a query on one or more real tables.

It does not store data itself, but displays data from the base tables as defined in the query.

✅ Syntax:
sql
CopyEdit
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;
🔹 Example:
sql
CopyEdit
CREATE VIEW CS_Students AS
SELECT Name, RollNo
FROM Students
WHERE Dept = 'CSE';

This creates a view CS_Students showing only CSE students.

📝 Features:
●​ Can be used like a table in queries.​

●​ Automatically updates if base table data changes.​

●​ Can restrict access to sensitive data.​

✅ Advantages:
●​ Simplifies complex queries​

●​ Enhances security​

●​ Provides data abstraction​

Let me know if you want updateable vs non-updateable views too!

What are the differences between Embedded SQL and Dynamic SQL?

ChatGPT said:

📌 Difference Between Embedded SQL and Dynamic SQL


Feature Embedded SQL Dynamic SQL

Definition SQL statements are hardcoded SQL statements are constructed at


in host code runtime

When Parsed At compile time At runtime

Flexibility Less flexible (queries are fixed) More flexible (can build queries
dynamically)

Performance Faster (compiled once) Slightly slower (parsed/executed at


runtime)

Use Case Fixed queries known in advance When query structure depends on
user input

Example C, Java with embedded SQL PL/SQL, Java JDBC using


Language prepareStatement()

🔹 Example of Embedded SQL:


c
CopyEdit
EXEC SQL SELECT * FROM Students WHERE RollNo = 101;

🔹 Example of Dynamic SQL (PL/SQL):


sql
CopyEdit
EXECUTE IMMEDIATE 'SELECT * FROM Students WHERE RollNo = ' ||
user_input;

✅ Summary:
●​ Embedded SQL: Compile-time, static, efficient.​

●​ Dynamic SQL: Runtime, flexible, interactive applications.​

Let me know if you want examples in specific programming languages!

What is a trigger? How many types of trigger are there?


ChatGPT said:

📌 What is a Trigger in DBMS?


A trigger is a stored procedure in a database that automatically executes in response to
certain events (like INSERT, UPDATE, or DELETE) on a table or view.

✅ Why Use Triggers?


●​ To enforce business rules​

●​ For automatic validation​

●​ To maintain logs​

●​ To prevent invalid operations​

🔹 Types of Triggers:
Based on Action Time:

1.​ BEFORE Trigger​


Executes before the operation (insert/update/delete)​

2.​ AFTER Trigger​


Executes after the operation​

Based on Event:

1.​ INSERT Trigger​

2.​ UPDATE Trigger​

3.​ DELETE Trigger​


🔄 Combinations:
●​ BEFORE INSERT​

●​ AFTER UPDATE​

●​ BEFORE DELETE, etc.​

🔹 Example (MySQL):
sql
CopyEdit
CREATE TRIGGER log_update
AFTER UPDATE ON Students
FOR EACH ROW
INSERT INTO Logs (msg) VALUES ('Student data updated');

Let me know if you want examples for BEFORE triggers or multi-event triggers too!

4o

You said:
. List two reasons why 'null' values might be introduced into the database?

ChatGPT said:

📌 Two Reasons Why NULL Values Are Introduced in a Database:


1.​ Missing or Unknown Information​

○​ When the value is not yet known at the time of data entry.​

○​ Example: A student’s phone number is not provided yet.​

2.​ Not Applicable Information​

○​ When the attribute doesn’t apply to a particular record.​

○​ Example: "Spouse Name" for an unmarried employee.​


Types of Triggers in DBMS

✅ 1. DML Trigger (Data Manipulation Language Trigger)


🔹 What is it?
A DML Trigger is fired when a DML operation (INSERT, UPDATE, DELETE) is performed on
a table or view.

🔹 Purpose:
●​ To enforce business rules​

●​ To log changes to data​

●​ To validate input values​

🔹 Example Use Cases:


●​ Automatically insert a log entry when a row is deleted.​

●​ Prevent an update if a value violates a constraint.​

🔹 Example:
sql

CopyEdit

CREATE TRIGGER check_salary

BEFORE INSERT ON employees

FOR EACH ROW

BEGIN

IF NEW.salary < 0 THEN


SIGNAL SQLSTATE '45000'

SET MESSAGE_TEXT = 'Salary cannot be negative';

END IF;

END;

✅ 2. DDL Trigger (Data Definition Language Trigger)


🔹 What is it?
A DDL Trigger is fired in response to DDL statements such as:

●​ CREATE, ALTER, DROP, TRUNCATE, RENAME, GRANT, REVOKE, etc.​

🔹 Purpose:
●​ To monitor or prevent schema changes​

●​ To audit structure-level changes​

●​ To restrict unauthorized users from modifying database structure​

🔹 Example Use Cases:


●​ Log whenever a table is dropped.​

●​ Prevent users from altering a specific table.​

🔹 Example (in Oracle):


sql

CopyEdit

CREATE OR REPLACE TRIGGER ddl_logger

AFTER DDL ON DATABASE


BEGIN

INSERT INTO ddl_log_table (user_name, event_type, event_time)

VALUES (USER, ora_sysevent, SYSDATE);

END;

🔁 Comparison Table:
Feature DML Trigger DDL Trigger

Fires on INSERT, UPDATE, DELETE CREATE, ALTER, DROP, etc.

Works on Tables and Views Entire Schema / Database

Use Case Data validation, auditing Schema change logging,


prevention

Common in MySQL, Oracle, PostgreSQL Mostly Oracle and SQL Server

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