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

Module III DBMS

The document discusses the basic components of SQL queries including SELECT, FROM, WHERE clauses. It also covers other SQL clauses like GROUP BY, HAVING, ORDER BY, JOIN and aggregation operators like COUNT, SUM, AVG, MIN, MAX.

Uploaded by

diwewe9515
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)
41 views13 pages

Module III DBMS

The document discusses the basic components of SQL queries including SELECT, FROM, WHERE clauses. It also covers other SQL clauses like GROUP BY, HAVING, ORDER BY, JOIN and aggregation operators like COUNT, SUM, AVG, MIN, MAX.

Uploaded by

diwewe9515
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

Form of basic SQL query in DBMS

The basic form of an SQL query, specifically when retrieving data, is composed of a
combination of clauses. The most elementary form of an SQL query for data retrieval
can be represented as
Syntax

SELECT [DISTINCT] column1, column2, ...


FROM tablename
WHERE condition;

Let's break it down:

1. SELECT Clause: This is where you specify the columns you want to retrieve. Use an
asterisk (*) to retrieve all columns.
2. FROM Clause: This specifies from which table or tables you want to retrieve the data.
3. WHERE Clause (optional): This allows you to filter the results based on a condition.
4. DISTINCT Clause (optional): is an optional keyword indicating that the answer should
not contain duplicates. Normally if we write the SQL without DISTINCT operator then it
does not eliminate the duplicates.

Here are the primary components of SQL queries:

 SELECT: Retrieves data from one or more tables.


 FROM: Specifies the table from which you're retrieving the data.
 WHERE: Filters the results based on a condition.
 GROUP BY: Groups rows that have the same values in specified columns.
 HAVING: Filters the result of a GROUP BY.
 ORDER BY: Sorts the results in ascending or descending order.
 JOIN: Combines rows from two or more tables based on related columns.
To provide a more holistic view, here are a few more SQL examples, keeping them as
basic as possible:

1. Retrieve all columns from a table:


Syntax

SELECT * FROM tablename;

2. Retrieve specific columns from a table:


Syntax

SELECT column1, column2 FROM tablename;

3. Retrieve data with a condition:


Syntax

SELECT column1, column2 FROM tablename WHERE column1 = 'value';

4. Sort retrieved data:


Syntax

SELECT column1, column2 FROM tablename ORDER BY column1 ASC;

UNION in DBMS
The UNION operator in DBMS is used to combine the result sets of two or
more SELECT statements. However, it will only select distinct values. The UNION
operator selects only distinct values by default. If you want to allow duplicate values,
you can use UNION ALL.
Here's the basic syntax:
Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

For instance, let's assume we have two tables, Customers and Suppliers, and we
want to find all cities where we have either a customer or a supplier. If the Customers
table has a column City and the Suppliers table also has a column City, we can use a
UNION to get a list of all cities:
Example:

SELECT City FROM Customers


UNION
SELECT City FROM Suppliers;

This would return a list of cities, with each city listed only once, even if it appears in both
the Customers and Suppliers tables.
Remember, the number and order of the columns, as well as the data types of the
corresponding columns, must be the same in all the SELECT statements that you're
combining with UNION.
If you wanted to include duplicates, you would use UNION ALL:
Example:

SELECT City FROM Customers


UNION ALL
SELECT City FROM Suppliers;

In this case, a city would be listed once for every time it appears in either the Customers
or Suppliers table.

INTERSECT in DBMS
he INTERSECT operator in a DBMS is used to combine two SELECT statements and
return only the records that are common to both.
The basic syntax of the INTERSECT clause in SQL is:
Syntax

SELECT column_name(s) FROM table1


INTERSECT
SELECT column_name(s) FROM table2;
For example, if you have two tables, Orders and Deliveries, and you want to find all
orders that have been delivered (assuming order_id is a common column), you could
write:
Example:

SELECT order_id FROM Orders


INTERSECT
SELECT order_id FROM Deliveries;

This would return a list of order_ids that appear in both the Orders and Deliveries
tables.

Here are some key points about the INTERSECT operator:

 The number and order of columns, and the data types in both the SELECT statements
should be the same.
 It removes duplicate rows from the result set.
 It returns records that are common to both the SELECT statement queries.

However, not all DBMSs support the INTERSECT operator. For example, MySQL does
not have a built-in INTERSECT operator, you can achieve the same result using a
combination of INNER JOIN, UNION, or EXISTS.
Here is an example of how to emulate INTERSECT using INNER JOIN:
Syntax

SELECT table1.id FROM table1


INNER JOIN table2 ON table1.id = table2.id;

This would also return ids that exist in both table1 and table2.

For example, if you have two tables, Orders and Deliveries, and you want to find all
orders that have been delivered (assuming order_id is a common column), you could
write:
Example:

SELECT o.order_id FROM Orders o


INNER JOIN
Deliveries d ON o.order_id = d.order_id

This would return a list of order_ids that appear in both the Orders and Deliveries
tables.
EXCEPT in DBMS
The EXCEPT operator in a DBMS is used to return the difference between
two SELECT statements. It returns the records from the first SELECT statement that
are not present in the second SELECT statement.
Here is the basic syntax of the EXCEPT clause in SQL:
Syntax

SELECT column_name(s) FROM table1


EXCEPT
SELECT column_name(s) FROM table2;

For example, if you have two tables, Orders and Deliveries, and you want to find all
orders that have not been delivered yet (assuming order_id is a common column), you
could write:
Example:

SELECT order_id FROM Orders


EXCEPT
SELECT order_id FROM Deliveries;

This would return a list of order_ids that appear in the Orders table but not in the
Deliveries table.

Here are some key points about the EXCEPT operator:

 The number and order of columns, and the data types in both SELECT statements
should match.
 It removes duplicate rows from the result set.
 It only returns records from the first SELECT statement that are not in the second
SELECT statement.

Just like the INTERSECT operator, all DBMSs does not support the EXCEPT operator.
MySQL doesn't support the EXCEPT operator directly, you can simulate EXCEPT using
a combination of LEFT JOIN or NOT EXISTS.
Here's how you might do it with LEFT JOIN:
Syntax

SELECT column_name(s) FROM table1


LEFT JOIN table2
ON table1.column_name = table2.column_name
WHERE table2.column_name IS NULL;

This query will return the rows from table1 where there is no matching row in table2 for
the specified column.
For example, if you have two tables, Orders and Deliveries, and you want to find all
orders that have not been delivered yet (assuming order_id is a common column), you
could write:
Example:

SELECT o.OrderID FROM Orders o


LEFT JOIN Deliveries d
ON o.OrderID = d.OrderID
WHERE d.OrderID IS NULL

This would return a list of OrderIDs that appear in the Orders table but not in the
Deliveries table.

Aggregation Operators in DBMS


In a DBMS, aggregation operators are used to perform operations on a group of values
to return a single summarizing value. The most common aggregation operators
include COUNT, SUM, AVG, MIN, and MAX.
Here are some examples of how you might use these operators:

COUNT
Returns the number of rows that matches a specified criterion.
Syntax
COUNT(expression)

Example:

SELECT COUNT(*) FROM Employees;

This query would return the total number of rows in the Employees table.

SUM
Returns the total sum of a numeric column.
Syntax
SUM(expression)

Example:

SELECT SUM(salary) FROM Employees;

This query would return the total sum of the salary column values in the Employees
table.

AVG
Returns the average value of a numeric column.
Syntax
AVG(expression)

Example:

SELECT AVG(salary) FROM Employees;

This query would return the average salary from the Employees table.

MIN
Returns the smallest value of the selected column.
Syntax
MIN(expression)

Example:

SELECT MIN(salary) FROM Employees;

This query would return the lowest salary from the Employees table.

MAX
Returns the largest value of the selected column.
Syntax
MAX(expression)

Example:
SELECT MAX(salary) FROM Employees;

This query would return the highest salary from the Employees table.

These aggregation operators are often used with the GROUP BY clause to group the
result-set by one or more columns. For example, to find the highest salary in each
department, you could write:
Example:

SELECT department_id, MAX(salary)


FROM Employees
GROUP BY department_id;

This query would return the highest salary for each department in the Employees table.

Complex Integrity Constraints in SQL


Integrity constraints in SQL are rules that help ensure the accuracy and reliability of
data in the database. They ensure that certain conditions are met when data is inserted,
updated, or deleted. While primary key, unique, and foreign key constraints are
commonly discussed and used, SQL allows for more complex constraints through the
use of CHECK and custom triggers. Here are some examples of complex integrity
constraints:

1. Using CHECK Constraints


Ensuring a range: You might want a column to only have values within a certain range.
Example:

CREATE TABLE Employees (


ID INT PRIMARY KEY,
Age INT CHECK (Age >= 18 AND Age <= 30)
);

Pattern matching: Ensure data in a column matches a particular format.


Example:

CREATE TABLE Students (


ID INT PRIMARY KEY,
Email VARCHAR(255) CHECK (Email LIKE '%@%.%')
);

2. Composite Primary and Foreign Keys


These are cases where the uniqueness or referential integrity constraint is applied over
more than one column.
Example:

CREATE TABLE OrderDetails (


OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID),
FOREIGN KEY (OrderID) REFERENCES Orders(OrderID),
FOREIGN KEY (ProductID) REFERENCES Products(ProductID)
);

3. Using Stored Procedures


Sometimes, instead of direct data manipulation on tables, using stored procedures can
help maintain more complex integrity constraints by wrapping logic inside the procedure.
For instance, you could have a procedure that checks several conditions before
inserting a record.

4. Using TRIGGERS
A trigger is a procedural code in a database that automatically executes in response to
certain events on a particular table or view. Essentially, triggers are special types of
stored procedures that run automatically when an INSERT, UPDATE, or DELETE
operation occurs.
A trigger is a predefined action that the database automatically executes in response to
certain events on a particular table or view. Triggers are typically used to maintain the
integrity of the data, automate data-related tasks, and extend the database
functionalities.

When implementing complex constraints, it's crucial to strike a balance. While they can
ensure data integrity, they can also add overhead to the database system and increase
the complexity of the schema and the operations performed on it. Proper documentation
and understanding of each constraint's purpose are essential.
Triggers and Active data bases in DBMS
Triggers and active databases are closely related concepts in the domain of DBMS.
Let's delve into what each of them means and how they are interconnected.

Triggers
A trigger is a predefined action that the database automatically executes in response to
certain events on a particular table or view. Triggers are typically used to maintain the
integrity of the data, automate data-related tasks, and extend the database
functionalities.
There are various types of triggers based on when they are executed:
BEFORE: Trigger is executed before the triggering event.
AFTER: Trigger is executed after the triggering event.
INSTEAD OF: Trigger is used to override the triggering event, primarily for views.

They can also be categorized by the triggering event:


INSERT: Trigger is executed when a new row is inserted.
UPDATE: Trigger is executed when a row is updated.
DELETE: Trigger is executed when a row is deleted.
Here's the basic syntax for creating a trigger in SQL, using MySQL as an
Syntax

CREATE TRIGGER trigger_name


trigger_time trigger_event
ON table_name FOR EACH ROW
trigger_body;

trigger_name: Name of the trigger.


trigger_time: BEFORE, AFTER, or INSTEAD OF.
trigger_event: INSERT, UPDATE, or DELETE.
table_name: The name of the table associated with the trigger.
trigger_body: The set of SQL statements to be executed.
Key Features of Triggers

1. Automatic Execution: Triggers run automatically in response to data modification


events. You don't have to explicitly call them.
2. Event-Driven: They are defined to execute before or after INSERT, UPDATE, and
DELETE events.
3. Transitional Access: Triggers can access the "old" (pre-modification) and "new" (post-
modification) values of the rows affected.

Example of a Trigger

Suppose we have an `Employees` table and we want to maintain an `AuditLog` table


that keeps a record of salary changes for employees.
Employees Table

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY,
Name VARCHAR(255),
Salary DECIMAL(10, 2)
);

AuditLog Table

CREATE TABLE AuditLog (


LogID INT AUTO_INCREMENT PRIMARY KEY,
EmployeeID INT,
OldSalary DECIMAL(10, 2),
NewSalary DECIMAL(10, 2),
ChangeDate DATETIME
);

Now, let's create a trigger that automatically inserts a record into the `AuditLog` table
whenever there's an update to the `Salary` column in the `Employees` table.
Trigger

mysql> DELIMITER //
mysql> CREATE TRIGGER AfterSalaryUpdate
AFTER UPDATE ON Employees
FOR EACH ROW
BEGIN
IF OLD.Salary != NEW.Salary THEN
INSERT INTO AuditLog (EmployeeID, OldSalary, NewSalary, ChangeDate)
VALUES (OLD.EmployeeID, OLD.Salary, NEW.Salary, NOW());
END IF;
END;
//
mysql> DELIMITER ;

How the Trigger Works

- The trigger is named `AfterSalaryUpdate`.


- It activates `AFTER` an `UPDATE` on the `Employees` table.
- It compares the old and new salary values. If there's a change (`OLD.Salary !=
NEW.Salary`), it inserts a new record into the `AuditLog` table with the details of the
change and the current date and time (`NOW()`).
With this trigger in place, every time an employee's salary is updated in the `Employees` table, an entry is
automatically added to the `AuditLog` table recording the change.

Active Databases
An active database is a database that uses triggers and other event-driven
functionalities. The term "active" signifies that the DBMS reacts automatically to
changes in data and predefined events. Triggers are a primary mechanism that makes
a database "active."

Key Features of Active Databases

1. Event-Condition-Action (ECA) Rule: This is the foundational concept of active


databases. When a specific event occurs, the database checks a particular condition,
and if that condition is met, an action is executed.
2. Reactive Behavior: The database can react to changes without external applications or
users having to intervene, thanks to the ECA rules.
3. Flexibility: Active databases provide more flexibility in data management and ensure
better data integrity and security.

Why are Active Databases Important?

 Integrity Maintenance: Active databases can enforce more complex business rules that
can't be enforced using standard integrity constraints.
 Automation: They can automate certain tasks, reducing manual interventions.
 Alerts: They can notify users or applications when specific conditions are met.

Relation between Triggers and Active Databases

Triggers are what give an active database its "active" nature. The ability of the database
to react to events automatically is primarily because of triggers that execute in response
to these events.
In essence, while "trigger" refers to the specific procedural code blocks that run in
response to events, "active database" refers to the broader capability of a DBMS to
support and use such event-driven functionalities.

Nested Queries in SQL


A nested query in SQL contains a query inside another query. The outer query will use the result of
the inner query. For instance, a nested query can have two SELECT statements, one on the inner
query and the other on the outer query.

You might also like