CS3481-DBMS LM
CS3481-DBMS LM
Table of Contents
8 TRIGGERS
COMMANDS) AIM:
SQL commands are grouped into four major categories depending on their
functionality. They are as follows:
These SQL commands are used for creating, modifying, and dropping the
structure of database objects. The commands are CREATE, ALTER, DROP, RENAME,
and TRUNCATE.
These SQL commands are used for storing, retrieving, modifying, and
deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.
These SQL commands are used for managing changes affecting the data.
These commands are COMMIT, ROLLBACK, and SAVEPOINT.
These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.
CREATE
ALTER
DROP
TRUNCATE
RENAME
PROCEDURE
STEP 1: Start
STEP 2: Create the table with its essential attributes.
STEP 3: Execute different Commands and extract information from the table.
STEP 4: Stop
SQL COMMANDS
ALTER TABLE tablename RENAME COLUMN old column name TO new column
name;
QUERY: 01
Q1. Write a query to create a table employee with empno, ename, designation, and
salary.
QUERY: 01
Table created.
QUERY: 02
Q2. Write a query to display the column name and datatype of the table employee.
Q3. Write a query for create a new table from an existing table with all the fields.
QUERY: 03
SQL> CREATE TABLE EMP1 AS SELECT * FROM EMP;
Table created.
SQL> DESC
EMP1
Name Null? Type
----------------------------------------- --------
------------------ EMPNO NUMBER(4)
ENAME VARCHAR(10)
DESIGNATIN VARCHAR(10)
SALARY NUMBER(8,2)
QUERY: 04
Q4. Write a query to create a table from an existing table with selected fields.
Syntax
SQL> CREATE TABLE <TARGET TABLE NAME> SELECT EMPNO, ENAME
FROM <SOURCE TABLE NAME>;
QUERY: 04
SQL> CREATE TABLE EMP2 AS SELECT EMPNO, ENAME FROM EMP;
Table created.
QUERY: 06
Q6. Write a Query to Alter the column EMPNO NUMBER (4) TO EMPNO NUMBER(6).
QUERY: 06
SQL>ALTER TABLE EMP MODIFY EMPNO NUMBER (6);
Table altered.
QUERY: 07
Q7. Write a Query to Alter the table employee with multiple columns (EMPNO,
ENAME.)
QUERY: 07
SQL>ALTER TABLE EMP MODIFY EMPNO INT (7),MODIFY ENAME
VARCHAR(12));
Table altered.
QUERY: 08
QUERY: 08
QUERY: 09
Table altered.
SQL> DESC EMP;
Name Null? Type
----------------------------------------- --------
---------------------------- EMPNO NUMBER(7)
ENAME VARCHAR(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR(6)
DOB DATE
DOJ DATE
QUERY: 10
Q10. Write the query to change the table name emp as employee
QUERY: 11
Q11. Write the query to change the column name empno to eno of the table
employee
SQL> ALTER TABLE employee RENAME COLUMN EMPNO TO ENO;
REMOVE /
DROP QUERY:
12
QUERY: 13
QUERY: 14
These SQL commands are used for storing, retrieving, modifying, and
deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.
INSERT- This is used to add one or more rows to a table. The values
are separated by commas and the data types char and date are enclosed
in apostrophes. The values must be entered in the same order as they are
defined.
PROCEDURE:
STEP 1: Start.
STEP 2: Create the table with its essential attributes.
STEP 3: Insert the record into table.
STEP 4: Update the existing records into the
table. STEP 5: Delete the records in to the table.
SQL COMMANDS
INSERT
QUERY: 01
Q1. Write a query to insert the records in to employee.
1 row
created.
SELECT
QUERY: 02
QUERY: 02
UPDATE
QUERY: 04
Q1. Write a query to update the records from employee.
Syntax for update Records from the table:
QUERY: 04
SQL> UPDATE EMP SET SALARY=16000 WHERE EMPNO=101;
1 row updated.
UPDATE MULTIPLE
COLUMNS QUERY: 05
Q5. Write a query to update multiple records from employee.
QUERY: 05
DELETE
QUERY: 06
Q5. Write a query to delete records from employee.
Result:
Thus the DDL, DML commands are executed in MySQL and verified
successfully.
EX: NO: 3 CREATION OF TABLES WITH CONSTRAINTS
AIM:
To execute and verify the SQL commands for adding constraints.
MySQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a
table. This ensures the accuracy and reliability of the data in the
table. If there is any violation between the constraint and the data
action, the action is aborted.
PROCEDURE:
STEP 1: Start.
STEP 2: Create the table with its essential attributes.
STEP 3: Add the constraint as a column level and table level
STEP 4: check all the constraints with specified conditions.
Create table1:
mysql> create table emp(empno int(3),empname varchar(20),age int(3),deptno
int(3),salary float(7,2),phno int(5));
PRIMARY KEY
Q1: create the department table with the primary key as a table
level constraint.
Q2: Alter the employee table with the primary key as a column
level constraint.
DEFAULT CONSTRAINT:
UNIQUE CONSTRAINT
Q6: create a unique constraint for the column phone number and
check the constraint
Q7:
Q10:
primary key
check
not null
unique
dropping constraints
Result:
Thus the MySQL statements for executing constraints are executed
successfully.
EX: NO: 3 WHERE CLAUSE CONDITIONS AND IMPLEMENT
AGGREGATE FUNCTIONS
AIM:
To execute and verify the SQL commands using where clause conditions
and implement aggregate functions.
PROCEDURE:
Create table 2:
mysql> select empname,empid from emp where salary between 20000 and 40000;
Q8: display the employee details having employee id greater than 103 and
department number 4.
Q10: display the employee details that are not in 102 and 104
Create table 2:
Q3:Display the company name which one having more than one employee.
mysql> insert into works values(105,'wipro','bangalore',30000);
Query OK, 1 row affected (0.03 sec)
Q10: Display company name which one is having less sum of salary compared
to others
mysql> select companyname from works group by companyname having
sum(salary)<=all(select sum(salary)from works group by companyname);
+-------------+
| companyname |
+-------------+
| infosis |
+-------------+
AIM:
SUB-QUERY:
A sub-query is a SQL query nested inside a larger query. A Sub Query can also be called a
Nested/Inner Query.
1. SELECT CLAUSE
2. FROM CLAUSE
3. WHERE CLAUSE
CREATE TABLE 1:
+ + + + +
+ + + + +
| 1 | ASHI | 16 | 10000 |
| 2 | ANI | 18 | 20000 |
| 3 | BISMI | 17 | 15000 |
+ + + + +
CREATE TABLE 2:
+ + + +
+ + + +
| 3 | 17 | 15000 |
| 1 | 16 | 10000 |
| 4 | 16 | 20000 |
+ + + +
A sub-query in a WHERE clause can be used to qualify a column against a set of rows.
SYNTAX:
mysql> SELECT * FROM REPORT WHERE EMPID IN(SELECT EMPID FROM EMP
WHERE EMPNAME='BISMI');
+ + + +
+ + + +
| 3 | 17 | 15000 |
+ + + +
SYNTAX:
+ + +
| EMPNAME | AGE |
+ + +
| ASHI | 16.0000 |
| BISMI | 17.0000 |
+ + +
+ + + + +
+ + + + +
| 1 | ASHI | 16 | 10000 |
+ + + + +
SYNTAX:
+ + +
| EMPID | MAX(SALARY) |
+ + +
| 2| 20000 |
| 3| 15000 |
+ + +
JOINS:
The USING clause specifies which columns to test for equality when two tables are
joined.
SYNTAX:
+ + + + + + +
+ + + + + + +
+ + + + + + +
JOIN USING ON CLAUSE:
ON clause can be used to join columns that have different names. Use the ON
clause to specify conditions orspecify columns to join.
SYNTAX:
+ + + + +
+ + + + +
| BISMI | 3 | 17 | 15000 |
| ASHI | 1 | 16 | 10000 |
+ + + + +
Result:
Thus the where clause conditions using MySQL statements are verified and
executed successfully.
EX: NO: 5 NATURAL, EQUI AND OUTER JOIN OPERATIONS
AIM:
To Query the Database Table and explore natural, equi and outer join operations.
CREATE TABLE 1:
CREATE TABLE 2:
+ + + + + + +
+ + + + + + +
+ + + + + + +
+ + + + + + +
+ + + + + + +
+ + + +
+ + + +
| Ajay | Chennai | 11 |
| Vijay | Banglore | 12 |
| Sujay | Chennai | 13 |
| Jay | Madurai | 14 |
+ + + +
+ + + +
| 11 | IT | 20000 |
| 12 | CSE | 20020 |
| 13 | IT | 20050 |
| 14 | CSE | 20000 |
+ + + +
A natural join is a type of join operation that creates an implicit join by combining tables
based on columns with the same name and data type
Syntax:
+ + + + + +
+ + + + + +
MySQL CROSS JOIN is used to combine all possibilities of the two or more
tables and returns the result that contains every row from all contributing tables.
The CROSS JOIN is also known as CARTESIAN JOIN, which provides the
Cartesian product of all associated tables.
Syntax:
+ + + + + + +
+ + + + + + +
+ + + + + + +
The MySQL Inner Join is used to returns only those results from the tables
that match the specified condition and hides other rows and columns. MySQL assumes it
as a default Join, so it is optional to use the Inner Join keyword with the query.
Syntax:
+ + + + + + +
+ + + + + + +
The LEFT JOIN returns all the rows from the table on the left even if no
matching rows have been found in the table on the right. Where no matches have been
found in the table on the right, NULL is returned.
Syntax:
+ + + + + + +
+ + + + + + +
RIGHT JOIN is obviously the opposite of LEFT JOIN. The RIGHT JOIN returns all the
columns from the table on the right even if no matching rows have been found in the
table on the left. Where no matches have been found in the table on the left, NULL is
returned.
Syntax:
+ + + + + + +
+ + + + + + +
+ + + + + + +
Result:
Thus the MYSQL commands to execute the natural, equi and outer join
operations are executed and verified successfully.
EX: NO: 6 PROCEDURES AND USER DEFINED FUNCTIONS
AIM:
1. Create tables.
2. Create procedures and functions.
3. Call procedures and functions to perform listed operations
4. Report the answers.
PROCEDURE:
Syntax:
1. Write a pl/sql program to find the sum &avg marks of all the student
using procedures.
STUD
RollNo Name M1 M2 M3
Create Table1:
-> begin
-> end
-> &&
mysql> delimiter ;
->&&
Call Procedure:
->&&
Out PUT:
2. Write a pl/sql program to find the product of 3 numbers in a procedure using in &
out parameter.
Create Procedure:
-> begin
-> end
-> &&
mysql> delimiter ;
->&&
->&&
->&&
Output:
@ans
36
Inserting record:
Create Function:
-> BEGIN
-> END
-> &&
Calling Function:
-> &&
Result:
Thus the procedures user defined function were created and executed
successfully.
EX: NO: 7 DCL AND TCL COMMANDS
AIM:
To create and execute complex transactions and realize DCL and TCL commands.
1. Create table.
2. Perform DCL and TCL commands.
3. Execute different user privileges.
4. Report the answers.
DCL (Data Control Language):
DCL includes commands such as GRANT and REVOKE which mainly deal
with the rights, permissions, and other controls of the database system.
START TRANSACTION:
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)
CREATE SAVEPOINT:
mysql> savepoint s1;
Query OK, 0 rows affected (0.01 sec)
UPDATE TABLE
COMMIT TRANSACTION:
mysql> commit;
Query OK, 0 rows affected (0.16 sec)
DCL (Data Control Language):
CREATE DATABASE:
mysql>create database employ;
Query ok..
CURRENT USER:
Result:
Thus the TCL and DCL commands were executed and verified successfully.
EX: NO: 8 TRIGGERS
AIM:
To develop and execute a Trigger for Before and After update, Delete, Insert
operations on a table
Trigger:
Types Of Triggers:
Before: Before triggers are fired before the DML statement is actually executed.
After: After triggers are fired after the DML statement has finished execution.
For each row: It specifies that the trigger fires once per row.
For each statement: This is the default trigger that is invoked. It specifies that
the trigger fires once per statement.
:new
:old
These two variables retain the new and old values of the column updated in the database.
The values in these variables can be used in the database triggers for data manipulation.
Snytax:
CREATE TRIGGER <trigger name> <trigger time > <trigger event> ON <table
name> FOR EACH ROW <trigger body>;
Every trigger associated with a table has a unique name and function based on
two factors:
Delete Triggers
Alternatively, use:
Procedure:
1. Create a table called person with name and age for columns.
3. Create a table called person_archive with name, age, and time columns:
The BEFORE INSERT trigger gives control over data modification before
committing into a database table..
Create a BEFORE INSERT trigger to check the age value before inserting
data into the person table:
delimiter //
CREATE TRIGGER person_bi BEFORE INSERT
ON person
FOR EACH ROW
IF NEW.age < 18 THEN
SIGNAL SQLSTATE '50001' SET MESSAGE_TEXT = 'Person must be older
than 18.';
END IF; //
delimiter ;
Inserting data activates the trigger and checks the value of age before
committing the information:
INSERT INTO person VALUES ('John', 14);
The console displays the descriptive error message. The data does not insert
into the table because of the failed trigger check.
The AFTER INSERT trigger is useful when the entered row generates a
value needed to update another table.
Inserting a new row into the person table does not automatically update the
average in the average_age table. Create an AFTER INSERT trigger on
the person table to update the average_age table after insert:
delimiter //
CREATE TRIGGER person_ai AFTER INSERT
ON person
FOR EACH ROW
UPDATE average_age SET average = (SELECT AVG(age) FROM person); //
delimiter ;
Inserting a new row into the person table activates the trigger:
If there is an age restriction for the person table before inserting data, the age
restriction should also exist before updating information. Without
the BEFORE UPDATE trigger, the age check trigger is easy to avoid.
Nothing restricts editing to a faulty value.
Add a BEFORE UPDATE trigger to the person table with the same body as
the BEFORE INSERT trigger:
delimiter //
CREATE TRIGGER person_bu BEFORE UPDATE
ON person
FOR EACH ROW
IF NEW.age < 18 THEN
SIGNAL SQLSTATE '50002' SET MESSAGE_TEXT = 'Person must be older than
18.';
END IF; //
delimiter ;
Updating the age to a value less than 18 displays the error message, and the
information does not update.
Any successful updates to the age data in the table person should also update
the intermediate average value calculated in the average_age table.
delimiter //
CREATE TRIGGER person_au AFTER UPDATE
ON person
FOR EACH ROW
UPDATE average_age SET average = (SELECT AVG(age) FROM person); //
delimiter ;
Updating existing data changes the value in the person table:
Updating the table person also updates the average in the average_age table.
delimiter //
CREATE TRIGGER person_bd BEFORE DELETE
ON person
FOR EACH ROW
INSERT INTO person_archive (name, age)
VALUES (OLD.name, OLD.age); //
delimiter ;
Deleting data from the table person archives the data into
the person_archive table before deleting:
The BEFORE DELETE trigger is useful for logging any table change
attempts.
Create an AFTER DELETE Trigger
The AFTER DELETE triggers maintain information updates that require the
data row to disappear before making the updates.
delimiter //
CREATE TRIGGER person_ad AFTER DELETE
ON person
FOR EACH ROW
UPDATE average_age SET average = (SELECT AVG(person.age) FROM person); //
delimiter ;
Deleting a record from the table person updates the average_age table with
the new average:
Without the AFTER DELETE trigger, the information does not update
automatically.
Result:
Thus the Trigger for Before and After update, Delete, Insert operations were
executed successfully.
.
EX: NO: 9 VIEWS AND INDEXES
AIM:
To create view and index for database tables with a large number of records.
.
VIEWS
OBJECTIVE:
PROCEDURE
STEP 1: Start
STEP 2: Create the table with its essential attributes.
STEP 3: Insert attribute values into the table.
STEP 4: Create the view from the above created table.
STEP 5: Execute different Commands and extract information from the View.
STEP 6: Stop
SQL COMMANDS
CREATION OF TABLE
DESCRIPTION OF TABLE:
DISPLAY VIEW:
mysql>SELECT * FROM EMPLOYEE;
CREATION OF VIEW
DISPLAY VIEW:
SQL> SELECT * FROM EMPVIEW;
INSERTION INTO
VIEW INSERT
STATEMENT:
SYNTAX:
DELETION OF VIEW:
DELETE STATEMENT:
SYNTAX:
UPDATE STATEMENT:
SYNTAX:
DROP A VIEW:
SYNTAX:
MYSQL> DROP VIEW <VIEW_NAME>
EXAMPLE:
Note: Updating a table with indexes takes more time than updating a table without
(because the indexes also need an update). So you should only create indexes on
columns (and tables) that will be frequently searched against.
CREATE INDEX
Syntax
To access the query plan for the SELECT query, execute the following:
After executing the above statement, the index is created successfully. Now, run
the below statement to see how MySQL internally performs this query.
DROPPING INDEXES
Result:
Thus the views and indexes created on person table was executed successfully.
EX: NO: 10 CREATION OF XML DATABASE AND VALIDATION USING
XML SCHEMA
AIM:
To Create a XML database and validation using XML schema.
Procedure:
<?xml version="1.0">
<xs:schema xmlns:xs="http://www.w3.org/2001/XML Schema">
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="first_name" type="xs:string/>
<xs:element name="last_name" type="xs:string/>
<xs:element name="weight">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:float">
<xs:attribute name="scale"
type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
6. Copy first few lines of code in first box and the generated code in the second box.
RESULT:
Thus the creation of XML database and validation using XML schema was
executed successfully.
Ex no: 11
CREATE DOCUMENT, COLUMN AND GRAPH BASED
DATA USING NOSQL DATABASE TOOLS
Date:
AIM:
To create a document-based NoSQL database using MongoDB, with columns and graphs,
and populate it with sample data.
NOSQL :
NOSQL (Not Only SQL) is a type of database that does not use the traditional relational
model that has been used in traditional SQL databases. Instead, NoSQL databases use a non-
relational approach for data storage and retrieval. They are designed to handle large amounts of
unstructured, semi-structured, and structured data, including text, images, videos, and social
media data.
NoSQL databases are often used in big data and real-time web applications, where high
performance and scalability are essential. Some popular examples of NoSQL databases include
MongoDB, Cassandra, Couchbase, and Apache HBase.
VIEW DATABASE:
In MongoDB, a view is a virtual collection that presents the results of a pre-defined
aggregation pipeline as if it were a collection of documents. Views do not store data
themselves but rather provide a read-only representation of the data in one or more underlying
collections.
CREATING DATABASE:
In the mongo shell, you can create a database with the help of the following command. This
command actually switches you to the new database if the given name does not exist and if the
given name exists, then it will switch you to the existing database. Now at this stage, if you use
the show command to see the database list where you will find that your new database is not
present in that database list because, in MongoDB, the database is actually created when you
start entering data in that database.
SYNTAX:
use database_name
CREATING COLLECTION:
In MongoDB, a collection is a grouping of MongoDB documents, similar to a table in a
relational database. To create a collection in MongoDB, you can use the db.createCollection()
method.
SYNTAX:
db.createCollection(name, options)
INSERTMANY COMMAND:
insertMany is a method in MongoDB that allows you to insert multiple documents into
a collection at once. The method takes an array of documents as its argument, and inserts
each document as a separate document in the collection.
SYNTAX:
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
DOCUMENT VIEW:
GRAPHICAL VIEW:
Step 1: Open MongoDB Compass Application.
Step 4: Click the collection -> ADD DATA -> Insert document. Add fields to the
document and click Insert.
In MongoDB, we can find a single document using the findOne() method, This method
returns the first document that matches the given filter query expression.
SYNTAX:
db.collection_name.findOne ()
SYNTAX:
db.collection_name.find().pretty()
SYNTAX:
SYNTAX:
db.collection_name.deleteOne({})
DROPPING A COLLECTION:
In MongoDB, a collection is a group of MongoDB documents that are stored together.
Dropping a collection in MongoDB means permanently deleting the entire collection and all of
its contents from the database.
SYNTAX:
db.collection_name.drop()
DROP A DATABASE:
In MongoDB, databases hold collections of documents. On a single MongoDB server, we
can run multiple databases. when you install MongoDB some databases are automatically
generated to use. many times you need to delete some database when the database is no longer
used.
db.dropDatabase() the command is used to drop an existing database. This command will
delete the currently selected database. If you have not selected any database, then it will delete
the default ‘test’ database.
SYNTAX:
db.dropDatabase()
RESULT:
Thus create a document-based NoSQL database using MongoDB, with columns and graphs,
and populate it with sample data.