Dbms Lab Record Final - Print-1
Dbms Lab Record Final - Print-1
TECHNOLOGY
PRACTICAL RECORD
Name : ………………………………………………………..
Semester : …………………………………………………….…...
Course : ……………………………………….
…………………
DHANALAKSHMI SRINIVASAN
UNIVERSITY
Name : ……………………………………………
Department : ……………………………………………
Semester : ……………………………………………
Certified that this is a Bonafide Record of the Practical work done for the
above course in Laboratory during the period …..………………………..
……………………………………………………………
AIM
To study the database creation, Data definition commands, Data manipulation commands for
inserting, deleting ,updating and retrieving tables and Transaction Control statements from
the database.
DESCRIPTION
It is used to communicate with database. It is used to:
Create an object
Select an
object The commands used are:
Create
Select
mysql -u your_username -p
You'll be prompted to enter your password.
Step 2: Create a Database
Once connected, you can create a new database using the CREATE DATABASE statement:
Syntax:
Example:
Description: To view the table /shows the description of the table / format of the table
Syntax: Desc <table name>;
Example:
Desc employee:
The most commonly used SQL command is SELECT statement. The SQL SELECT
statement is used to query or retrieve data from a table in the database. A query may retrieve
information from specified columns or from all of the columns in the table. To create a
simple SQL SELECT Statement, you must specify the column(s) name and the table name.
The whole query is called SQL SELECT Statement.
Syntax:
table-name is the name of the table from which the information is retrieved.
column_list includes one or more columns from which data is retrieved.
The code within the brackets is optional.
Example:
SELECT empno,ename FROM employee;
RESULT:
Thus the database was created and the SQL queries to retrieve information from the database
was executed successfully.
Exp.No:2 PERFORMING INSERTION, DELETION, MODIFYING, ALTERING,
Date: UPDATING AND VIEWING RECORDS BASED ON CONDITION.
AIM:
To performing Insertion,Deletion,Modifying,Altering,Updating and Viewing records
based on condition.
Inserting the data directly to a table. Syntax for SQL INSERT is:
col1, col2,...colN -- the names of the columns in the table into which you want
to insert data.
NOTE:
1) When adding a new row, you should ensure the datatype of the value and the
column matches
2) You follow the integrity constraints, if any, defined for the table.
The most commonly used SQL command is SELECT statement. The SQL SELECT
statement is used to query or retrieve data from a table in the database. A query may retrieve
information from specified columns or from all of the columns in the table. To create a
simple SQL SELECT Statement, you must specify the column(s) name and the table name.
The whole query is called SQL SELECT Statement.
table-name is the name of the table from which the information is retrieved.
column_list includes one or more columns from which data is retrieved.
The code within the brackets is optional.
UPDATE table_name
SET column_name1 = value1,
column_name2 = value2, ...
[WHERE condition]
NOTE: In the Update statement, WHERE clause identifies the rows that get affected.
If you do not include the WHERE clause, column values for all the rows get affected.
NOTE: The WHERE clause in the sql delete command is optional and it identifies the
rows in the column that gets deleted. If you do not include the WHERE clause all the rows in
the table is deleted, so be careful while writing a DELETE query without WHERE clause.
The SQL TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
Syntax to TRUNCATE a table:
For Example: To delete all the rows from employee table, the query would be like,
DELETE Statement: This command deletes only the rows from the table based on the
condition given in the where clause or deletes all the rows from the table if no condition is
specified. But it does not free the space containing the table.
TRUNCATE statement: This command is used to delete all the rows from the table and free
the space containing the table.
The SQL DROP command is used to remove an object from the database. If you drop a table,
all the rows in the table is deleted and the table structure is removed from the database. Once
a table is dropped we cannot get it back, so be careful while using DROP command. When a
table is dropped all the references to the table will not be valid.
If a table is dropped, all the relationships with other tables will no longer be valid, the
integrity constraints will be dropped, grant or access privileges on the table will also be
dropped, if want use the table again it has to be recreated with the integrity constraints, access
privileges and the relationships with other tables should be established again. But, if a table is
truncated, the table structure remains the same, therefore any of the above problems will not
exist.
1) Adding a column
PROGRAM:
mysql> SELECT * FROM Customers WHERE NOT Country = 'india' AND NOT
Country = 'US';
Empty set (0.00 sec)
mysql> SELECT * FROM Customers WHERE NOT Country = 'US';
+ + + + + + +
| CustID | CustName | Phonenumber | Address | city | country |
+ + + + + + +
| 111 | aaa | 1234567890 | h street | dgl | india |
| 222 | bbb | 1234567891 | a street | karur | india |
| 333 | ccc | 1234567892 | b street | trichy | india |
+ + + + + + +
3 rows in set (0.00 sec)
RESULT:
Thus, the SQL queries to performing insertion, deletion, modifying, altering, updating and
viewing records based on condition were executed successfully.
Exp.No:3 CREATION OF VIEWS, SYNONYMS, SEQUENCE, INDEXES,
Date: SAVE POINT
AIM:
To Study the Creation of Views, Synonyms, Sequence, Indexes and Save point.
VIEWS:
A view is the tailored presentation af data contained in one or more table and can also
be said as restricted view to the datas in the tables. A view is a “virtual table” or a “stored
query” which takes the output of a query and treats it as a table. The table upon which a view
is created is called as base table.
A view is a logical table based on a table or another view. A view contains no data of
its own but is like a window through which data from tables can be viewed or changed. The
tables on which a view is based are called base tables. The view is stored as a SELECT
statement in the data dictionary
Advantages of a view:
a. Additional level of table security.
Syntax:
Create [or replace ] view <view name> [column alis names] as <query> [with <options>
conditions];
Types of view:
INDEX
Indexes (or Keys) can be created on selected column(s) to facilitate fast search. Without
index, a "SELECT * FROM products WHERE productID=x" needs to match with
the productID column of all the records in the products table. If productID column is indexed
(e.g., using a binary tree), the matching can be greatly improved (via the binary tree search).
You should index columns which are frequently used in the WHERE clause; and
as JOIN columns.
The drawback about indexing is cost and space. Building and maintaining indexes require
computations and memory spaces. Indexes facilitate fast search but deplete the performance
on modifying the table (INSERT/UPDATE/DELETE), and need to be justified.
Nevertheless, relational databases are typically optimized for queries and retrievals, but NOT
for updates.
In MySQL, the keyword KEY is synonym to INDEX.
In MySQL, indexes can be built on:
1. a single column (column-index)
2. a set of columns (concatenated-index)
3. on unique-value column (UNIQUE INDEX or UNIQUE KEY)
4. on a prefix of a column for strings (VARCHAR or CHAR), e.g., first 5 characters.
There can be more than one indexes in a table. Index are automatically built on the
primary- key column(s).
You can build index via CREATE TABLE, CREATE INDEX or ALTER TABLE.
SEQUENCE
A sequence in MySQL is an arrangement of integers generated in the ascending order (1,
2, 3, and so on) on specific demand. Sequences are used in the databases to generate unique
numbers. Many applications require each row of a table to contain a distinct value, such as
student roll number in student_table, employee numbers in HR, customer ID in CRM, etc. To
fulfill this type of arrangement, we use sequences that provide an easy way to generate them.
MySQL does not provide any built-in function to create a sequence for a table's rows or
columns. But we can generate it via SQL query. In this article, we are going to describe how
to create a sequence in MySQL using SQL query.
The simplest way for creating a sequence in MySQL is by defining the column
as AUTO_INCREMENT during table creation, which should be a primary key column.
The following are the rules which should be considered when we use the
AUTO_INCREMENT attribute for the column:
o We can create only one AUTO_INCREMENT column in each table, and the data
type of this column is an integer.
o The AUTO_INCREMENT column should also have either PRIMARY or
UNIQUE KEY indexing.
o The AUTO_INCREMENT column must contain NOT NULL However, MySQL
automatically adds the NOT NULL constraint to the column implicitly when we
set the column as an AUTO_INCREMENT attribute.
MySQL does not have a native sequence object like some other databases (e.g., Oracle).
Instead, you can use the AUTO_INCREMENT attribute for columns to achieve a
similar effect.
CREATE TABLE mytable (
id INT AUTO_INCREMENT PRIMARY KEY,
data VARCHAR(255)
);
Increment by
Specify the interval between the sequence numbers.
Value can be positive or negative but can’t be zero.
If the value is POSITIVE it is INCREMENT SEQUENCE.
If the value is NEGATIVE it is DECREMENT SEQUENCE.
Default increment is 1.
Start with n
Specify the starting value of sequence.
Default value is 1.
Min value
Specify the min value of sequence.
No min value
Specify a minimum value of 1 for ascending sequence.
-1026 for descending sequence.
Max value
Specify the max value of sequence.
No max value
Specify the maximum value of 1027 for ascending sequence.
-1 for descending sequence.
Cycle
Specify the sequence will continue to generate value after reaching either maximum or
minimum value.
No cycle
Specify sequence can’t generate value after reaching max or min value. Default is
NO CYCLE.
Cache
Cache is a buffer.
It specifies the No. of integer to keep in memory.
Default cache is 20.
Minimum cache is 2.
Order
This guarantees that sequence Numbers are generated in the order of request.
No order
This does not guarantee that sequence Numbers are generated in the order of request.
EXAMPLE:
mysql> CREATE TABLE Insects (
-> Id INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY (id),
-> Name VARCHAR(30) NOT NULL,
-> Type VARCHAR(30) NOT NULL,
-> Origin VARCHAR(30) NOT NULL
-> );
ERROR 1046 (3D000): No database
selected mysql> show databases;
+-------------------+
| Database |
+-------------------+
| information_schema |
| employee |
| mysql |
| performance_schema |
| sakila |
| sys |
| testdb |
| world |
+-------------------+
8 rows in set (0.01 sec)
SYNONYM
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures and other database objects.
We can avoid the entry of SCHEMA.
DML operation performed on synonym will affect the table.
The main functionality of synonym is to access the database objects between different
schemas without using the schema names.
In MySQL, there is no direct support for synonyms as it exists in some other database
systems like Oracle. However, you can achieve similar functionality using views or
by creating an alias for a table or a column.
Using Views:
You can create a view that selects data from a table and then use the view as if it were a synonym.
-- Create a view as a synonym
CREATE VIEW my_synonym AS
SELECT column1, column2
FROM my_table
WHERE condition;
SAVEPOINTS
In MySQL, you can use savepoints within transactions to create points that you can roll back to if
needed. Savepoints are particularly useful when you want to perform partial rollbacks within
a transaction. Here's an example:
-- Start a transaction
START TRANSACTION;
-- Create a savepoint
SAVEPOINT my_savepoint;
Explanation:
1. START TRANSACTION: Begins a new transaction.
2. SAVEPOINT my_savepoint: Creates a savepoint with the name
my_savepoint. This allows you to roll back to this point within the transaction.
3. ROLLBACK TO my_savepoint: Rolls back the transaction to the savepoint named
my_savepoint. This will undo changes made after the savepoint.
4. COMMIT: If everything is as expected and you want to make the
changes permanent, you can commit the transaction.
To use the COMMIT statement at the end of your transaction if you want to make the
changes permanent. If you encounter issues or want to discard the changes made after a
savepoint, you can use ROLLBACK TO my_savepoint.
RESULT:
Thus the SQL queries for Views, Synonyms, Sequence, Indexes and Save point. were
executed successfully.
Exp.No:4 CREATING AN EMPLOYEE DATABASE TO SET VARIOUS
Date: CONSTRAINTS.
Aim:
To create an employee database to set various constraints.
SQL Constraints are the rules applied to a data columns or the complete table to limit the type
of data that can go into a table. When you try to perform any INSERT, UPDATE, or
DELETE operation on the table, RDBMS will check whether that data violates any existing
constraints and if there is any violation between the defined constraint and the data action, it
aborts the operation and returns an error.
We can define a column level or a table level constraints.
Primary Key Constraint: this ensures all rows have a unique value
and cannot be NULL, often used as an identifier of a table’s row.
Foreign Key Constraint: this ensures that values in a column (or
several columns) match values in another table’s column/s.
Unique Constraint: this ensures all rows have a unique value.
Not Null Constraint: this ensures a value cannot be NULL.
Check Constraint: this ensures a value meets a specific condition.
We can create constraints on a table at the time of a table creation using the CREATE
TABLE statement, or after the table is created, we can use the ALTER TABLE statement to
create or delete table constraints.
RESULT:
Thus the employee database to set various constraints were created and executed
successfully.
Exp.No:5
CREATING RELATIONSHIP BETWEEN THE DATABASES.
Date:
Aim:
To create the relationship between the databases.
In MySQL, databases do not directly have relationships with each other. Relationships are
established between tables within the same database using foreign key constraints. However,
if you want to establish a relationship between tables in different databases, you can fully
qualify the table names when defining foreign key constraints.
Here's an example:
RESULT:
Thus, the relationship between databases has been created.
Exp.No:6
STUDY OF PL/SQL
Date:
Aim:
To study the basics of PL/SQL.
RESULT:
Thus the fundamentals of PL/SQL were studied
Exp.No:7 WRITE A PL/SQL BLOCK TO SATISFY SOME CONDITIONS
Date: BY ACCEPTING INPUT FROM THE USER
AIM:
To implement the PL/SQL block that satisfy some conditions by accepting input from
the user.
DELIMITER //
SET no1 = a;
SET no2 =
b;
DELIMITER ;
Sum:12
DELIMITER //
DELIMITER ;
DELIMITER //
WHILE n > 0 DO
SET r = n % 10;
SET rev = (rev * 10) + r;
SET n = TRUNCATE(n / 10);
END WHILE;
DELIMITER ;
-- Call the stored procedure with input values
CALL reverse_number(12345);
OUTPUT:
Enter value for n:
1235 old 8: n:=&n;
new 8: n:=1235;
reverse is 5321
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL programs were written and executed to accept the input from the
users.
Exp.No:8 WRITE A PL/SQL BLOCK THAT HANDLES ALL TYPES OF
Date: EXCEPTIONS
SET a = &a;
SET b =
&b;
IF b = 0 THEN
SIGNAL divide_zero SET MESSAGE_TEXT = 'b could not be zero';
ELSE
SET c = a / b;
SELECT CONCAT('Division is ', c) AS result;
END IF;
END //
DELIMITER
OUTPUT
b could not be zero.
For the customer relation Customers(ID, Name, Age Address, Salary). Write a PL/SQL
block to input customerid and display address and salary. Use exception to display “ No
such customer” when data not found.
DELIMITER //
EXCEPTION
WHEN ex_invalid_id THEN
SELECT 'ID must be greater than zero!' AS
result; WHEN no_such_customer THEN
SELECT 'No such customer!' AS result;
WHEN OTHERS THEN
SELECT 'Error!' AS result;
END //
DELIMITER ;
RESULT
Hence, the PL/SQL block for handling all types of exceptions were executed
successfully.
Exp.No:9
CREATION OF PROCEDURES
Date:
Aim :
To create stored procedures to encapsulate a series of SQL statements into a
reusable and callable routine
DELIMITER ;
Let's break down the syntax:
DELIMITER //: This changes the statement delimiter to // temporarily. This
is necessary because the default delimiter is ;, and procedures contain
multiple SQL statements.
CREATE PROCEDURE procedure_name: This declares the start of the
procedure definition, where procedure_name is the name you want to give
to your stored procedure.
(parameter1 datatype, parameter2 datatype, ...): This is where you can define
input parameters for your stored procedure. Each parameter consists of a
name and a data type.
BEGIN and END: These keywords enclose the body of the stored
procedure, where you can write one or more SQL statements.
//: This is the custom delimiter that we set at the beginning. It marks the end
of the stored procedure definition.
DELIMITER ;: This changes the statement delimiter back to the default
(;). Here's an example of a simple stored procedure that selects data from a table:
sqlCopy code
DELIMITER //
CREATE PROCEDURE GetEmployee(IN employee_id INT)
BEGIN
SELECT * FROM employees WHERE id = employee_id;
END //
DELIMITER ;
In this example, the GetEmployee stored procedure takes an employee_id as input and
selects all columns from the employees table where the id matches the provided
parameter.
To call the stored procedure, you can use the following syntax:
CALL GetEmployee(123);
Replace 123 with the actual employee ID you want to retrieve.
PROCEDURES – SYNTAX
create or replace procedure (argument {in,out,inout} datatype ) {is,as} variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block; end;
In this example:
1. A new database MyDatabase is created (if it doesn't already exist), and it is
selected for use.
2. A table named ITItems is created with columns ItemID, ItemName, ItemType, and
Quantity. The ItemID column is designated as the primary key.
3. Sample data is inserted into the ITItems table.
4. The SELECT * FROM ITItems; statement is used to display the contents of the
ITItems table.
RESULT:
Hence, the procedure for the sample database has been created for the tables.
Exp.No:10
CREATION OF DATABASE TRIGGERS AND FUNCTIONS
Date:
Creating a Trigger:
-- Create a table
CREATE TABLE IF NOT EXISTS MyTable (
ID INT PRIMARY KEY,
Data VARCHAR(255),
LastUpdated TIMESTAMP
);
-- Create a trigger
DELIMITER //
CREATE TRIGGER update_timestamp
BEFORE UPDATE ON MyTable
FOR EACH ROW
SET NEW.LastUpdated = NOW();
//
DELIMITER ;
In this example:
A table named MyTable is created with columns ID, Data, and LastUpdated.
The update_timestamp trigger is created. It fires before an update operation
on MyTable and sets the LastUpdated column to the current timestamp.
Creating a Function:
Here's an example of creating a simple function that calculates the square of a number:
-- Create a function
DELIMITER //
CREATE FUNCTION CalculateSquare(input_number INT)
RETURNS INT
BEGIN
DECLARE result INT;
SET result = input_number * input_number;
RETURN result;
END //
DELIMITER ;
In this example:
The CalculateSquare function is created. It takes an integer parameter input_number,
calculates the square, and returns the result.
RESULT:
Hence, the function and trigger for the sample database is created and executed successfully.