Rojbel dbms2
Rojbel dbms2
Rojbel dbms2
Submitted By:-
Department Of BCA,
P. K. Roy Memorial College, Dhanbad-826004.
INDEX
Sl.No. EXPERIMENTS PAGE DATE SIGNATURE
1. To create a DDL to perform creation of 3-5
table, alter, modify and drop column.
2. To study INSERT, UPDATE & DELETE 6 - 14
commands and implement them on the
database.
3. To study CALL, EXPLAIN CALL & 15 – 26
LOCK DML commands and implement
them on the database.
4. To study GRANT command and 27 – 30
implement them on the database.
5. To study REVOKE command and 31 - 36
implement them on the database.
EXPERIMENT NO: 1
AIM: To create a DDL to perform creation of table, alter, modify and drop column.
• DDL stands for data definition language. DDL Commands deal with the schema,
i.e., the table in which our data is stored.
• All the structural changes such as creation, deletion and alteration on the table can be
carried with the DDL commands in SQL.
DDL COMMANDS :-
1. The Create Table Command : - It defines each column of the table uniquely. Each
column has minimum of three attributes, a name , data type and size.
Syntax:
CREATE TABLE table_name (
<column1> <datatype>(<size>),
<column2> <datatype>(<size>),
<column3> <datatype>(<size>),
....
);
E.g.
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
OUTPUT : -
Syntax:
ALTER TABLE table_name ADD column_name datatype;
E.g.
OUTPUT : -
PersonID LastName FirstName Address City Email
Syntax:
ALTER TABLE table_name DROP COLUMN column_name;
E.g.
ALTER TABLE Customers DROP COLUMN Email;
OUTPUT : -
Syntax:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
E.g.
Sample Table “Persons” :-
OUTPUT : -
Syntax:
ALTER TABLE table_name RENAME COLUMN old_name TO new_name;
OUTPUT : -
Syntax:
TRUNCATE [TABLE] table_name;
E.g.
Sample Table : Student
ROLL_NO FIRST_NAME AGE
1 Ram 20
2 Abhi 21
3 Rahul 22
4 Tanu 19
QUERY : TRUNCATE TABLE Student;
OUTPUT :-
Empty set
NOTE : Truncate will only delete the data present in the table, but NOT the table’s
Structure.
4. Destroying tables.
Syntax:
DROP TABLE table_name;
E.g.
DROP TABLE Students;
NOTE : The DROP keyword will permanently delete the table ( Structure as well as Data
within it ).
AIM : To study INSERT, UPDATE & DELETE commands and implement them on the database.
• DML stands for Data Manipulation Language. Using DML commands in SQL, we
can make changes in the data present in tables.
• Whenever we wish to manipulate the data or fetch the data present in SQL tables, we
can use DML commands in SQL.
• DML commands in SQL will change the data, such as inserting new records,
deleting or updating existing records from the SQL tables. We can also retrieve all
the data from SQL tables according to our requirements.
DML COMMANDS : -
1. Insert Command : 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.
We can insert a row in the table by using SQL INSERT INTO command. There are two ways
to insert values in a table.
i. In the first method there is no need to specify the column name where the data will be
inserted, we need only their values.
Syntax:
INSERT INTO table_name VALUES (value1, value2, value3....);
ii. The second method specifies both the column name and values which you want to insert.
Syntax:
INSERT INTO table_name (column1, column2, column3....) VALUES (value1, value2,
value3.....);
Let's take an example of table which has five records within it.
1 ABHIRAM 22 ALLAHABAD
2 ALKA 20 GHAZIABAD
3 DISHA 21 VARANASI
4 ESHA 21 DELHI
5 MANMEET 23 JALANDHAR
Syntax:
INSERT INTO table_name [(column1, column2, .... column)]
SELECT column1, column2, .... Column N FROM table_name [WHERE condition];
Many times developers ask that is it possible to insert multiple rows into a single table in a
single statement. Currently, developers have to write multiple insert statements when they
insert values in a table. It is not only boring but also time-consuming.
Example :-
QUERY :-
CREATE TABLE student(ID INT, Name VARCHAR(20), Percentage INT, Location
VARCHAR(20), DateOfBirth DATE);
Now, we will write a single query to insert multiple records in the student table:
QUERY :-
INSERT INTO student(ID, Name, Percentage, Location, DateOfBirth) VALUES(1,
"Manthan Koli", 79, "Delhi", "2003-08-20"), (2, "Dev Dixit", 75, "Pune",
"19990617"), (3, "Aakash Deshmukh", 87, "Mumbai", "1997-09-12"), (4, "Aaryan
Jaiswal",
90, "Chennai", "2005-10-02"), (5, "Rahul Khanna", 92, "Ambala", "1996-03-04"), (6,
"Pankaj Deshmukh", 67, "Kanpur", "2000-02-02"), (7, "Gaurav Kumar", 84,
"Chandigarh", "1998-07-06"), (8, "Sanket Jain", 61, "Shimla", "1990-09-08"), (9,
"Sahil Wagh", 90, "Kolkata", "1968-04-03"), (10, "Saurabh Singh", 54, "Kashmir",
"1989-01-06");
The results show that all ten records are inserted successfully using a single query.
2. Update Command : It is used to alter the column values in a table. A single column may
be updated or more than one column could be updated.
UPDATE table_name
SET column_name = expression
WHERE conditions
Let's take an example: here we are going to update an entry in the source table.
SQL statement:
UPDATE students
SET User_Name = 'beinghuman'
WHERE Student_Id = '3'
Source Table:
Student_Id FirstName LastName User_Name
If we are going to update multiple fields, we should separate each field assignment with a
comma.
UPDATE students
SET User_Name = 'beserious', First_Name = 'Johnny'
WHERE Student_Id = '3'
UPDATE table_name
SET field1 = new-value1, field2 = new-value2,
[WHERE CLAUSE]
SQL UPDATE SELECT:
SYNTAX :-
UPDATE tableDestination
SET tableDestination.col = value
WHERE EXISTS (
SELECT col2.value
FROM tblSource
WHERE tblSource.join_col = tblDestination. Join_col
AND tblSource.Constraint = value)
We can update a single or multiple columns in SQL with SQL UPDATE query.
UPDATE students
SET student_id = 001
WHERE student_name = 'AJEET';
This SQL UPDATE example would update the student_id to '001' in the student table where
student_name is 'AJEET'.
UPDATE students
SET student_name = 'AJEET', ID = '101'
WHERE student_name = 'RAJU';
This SQL UPDATE statement will change the student name to 'AJEET' and ID to '101' where
the student name is 'RAJU'.
3. Delete command : After inserting row in a table we can also delete them if required. The
delete command consists of a from clause followed by an optional where clause.
Syntax:-
The following are the syntax that illustrates how to use the DELETE statement:
In the above statement, we have to first specify the table name from which we want to delete
data. Second, we have to specify the condition to delete records in the WHERE clause, which
is optional. If we omit the WHERE clause into the statement, this query will remove whole
records from the database table.
If we want to delete records from multiple tables using a single DELETE query, we must add
the JOIN clause with the DELETE statement.
If we want to delete all records from a table without knowing the count of deleted rows, we
must use the TRUNCATE TABLE statement that gives better performance.
Let us understand how the DELETE statement works in MySQL through various examples.
Here, we are going to use the "Employees" and "Payment" tables for the demonstration of
the DELETE statement. Suppose the Employees and Payment tables contain the following
data:
If we want to delete an employee whose emp_id is 107, we should use the DELETE
statement with the WHERE clause. See the below query:
After the execution of the query, it will return the output as below image. Once the record is
deleted, verify the table using the SELECT statement:
If we want to delete all records from the table, there is no need to use the WHERE clause with
the DELETE statement. See the below code and output:
In the above output, we can see that after removing all rows, the Employees table will be
empty. It means no records available in the selected table.
MySQL DELETE and LIMIT Clause :-
MySQL Limit clause is used to restrict the count of rows returns from the result set, rather
than fetching the whole records in the table. Sometimes we want to limit the number of rows
to be deleted from the table; in that case, we will use the LIMIT clause as follows:
It is to note that the order of rows in a MySQL table is unspecified. Therefore, we should
always use the ORDER BY clause while using the LIMIT clause.
For example, the following query first sorts the employees according to their names
alphabetically and deletes the first three employees from the table:
The JOIN clause is used to add the two or more tables in MySQL. We will add the JOIN
clause with the DELETE statement whenever we want to delete records from multiple tables
within a single query. See the below query:
RESULT : Thus studied INSERT, UPDATE & DELETE commands and implemented them
on the database.
EXPERIMENT NO. 3
AIM : To study INSERT, UPDATE & DELETE commands and implement them on the database.
• DML stands for Data Manipulation Language. Using DML commands in SQL, we
can make changes in the data present in tables.
• Whenever we wish to manipulate the data or fetch the data present in SQL tables, we
can use DML commands in SQL.
DML COMMANDS :-
1. Call Statement : Stored procedures are sub routines, segment of SQL statements which are
stored in SQL catalog. These procedures contain IN and OUT parameters, or both. They may
return result sets in case you use SELECT statements; they can return multiple resultsets.
The call statement of MySQL is used to invoke/call a stored procedure.
Syntax:
Suppose we have created a table named Emp in the database using the CREATE statement
and inserted three records in it as shown below −
mysql> CREATE TABLE Emp (Name VARCHAR(255), Salary INT, Location VARCHAR(255));
Assume we have created a stored procedure InsertData which accepts the name, salary and
location values and inserts them as a record into the above create (Emp) table.
DELIMITER //
Create procedure InsertData ( IN name VARCHAR(30), IN sal INT,
IN loc VARCHAR(45))
BEGIN
INSERT INTO Emp(Name, Salary, Location) VALUES (name, sal, loc);
END //
Once you call the procedure by passing the required values you can verify the contents of the
Emp table as shown below –
While calling a stored procedure that doesn’t accepts any arguments, we can omit the
parenthesis as shown below −
CALL procedure;
Assume we have created another procedure with name getData that retries the contents of the
table EMP −
DELIMITER //
END//
Since this procedure doesn’t accept arguments you can call this procedure by omitting the
parameters as shown below –
CALL getData;
NAME SALARY LOCATION
Raju 35000 Banglore
Raman 45000 Visakhapatnam
Rahman 55000 Hyderabad
2. Explain Call Statement : The EXPLAIN keyword is used to obtain information about
how our SQL databases execute the queries in MySQL. It is synonyms to the DESCRIBE
statement. In practice, the DESCRIBE keyword provides table structure information, whereas
the EXPLAIN keyword gives the query execution plan.
It can work with INSERT, SELECT, DELETE, UPDATE, and REPLACE queries.
From MySQL 8.0.19 and later versions, it can also work with TABLE statements. When we
use this keyword in queries, it will process the statement and provide the information about
each step in the execution plan, such as how tables are joined, the table's order, estimated
partitions, etc. It returns single or multiple rows that explain each part of the execution plan
and the order of execution.
Example
Suppose we have a table named "student_info" and "orders" in the sample database that
contains the following data:
If we want to show the execution plan of a SELECT statement, we can use the query as
below:
Output:
Sometimes we do not want to scan the whole table. In that case, we need to use the INDEX to
see the information based on a specified condition. Execute the below statement to create an
index in the student_info table:
Now, execute the following query to avoid the complete table scan in the database:
Output:
After execution, we will get the output like the below image:
It is a profiling tool for queries that shows information about where MySQL spends
time on query execution and why. It will plan the query, instrument it and execute it while
counting rows and measuring time spent at various points in the execution plan. When
execution finishes, it will print the plan and measurement instead of the query result.
A lock is a mechanism associated with a table used to restrict the unauthorized access of the
data in a table. MySQL allows a client session to acquire a table lock explicitly to cooperate
with other sessions to access the table's data. MySQL also allows table locking to prevent it
from unauthorized modification into the same table during a specific period.
A session in MySQL can acquire or release locks on the table only for itself. Therefore, one
session cannot acquire or release table locks for other sessions. It is to note that we must have
a TABLE LOCK and SELECT privileges for table locking.
Table Locking in MySQL is mainly used to solve concurrency problems. It will be used while
running a transaction, i.e., first read a value from a table (database) and then write it into the
table (database).
MySQL provides two types of locks onto the table, which are:
READ LOCK: This lock allows a user to only read the data from a table.
WRITE LOCK: This lock allows a user to do both reading and writing into a table.
Before understanding the table locking concept, first, we will create a new table named
"info_table" using the statement as follows:
In the above syntax, we have specified the table name on which we want to acquire a lock
after the LOCK TABLES keywords. We can specify the lock type, either READ or WRITE.
We can also lock more than one table in MySQL by using a list of comma-separated table's
names with lock types. See the below syntax:
UNLOCK TABLES;
LOCK TYPES
Let us understand the lock types in detail.
READ Locks
The following are the features of the READ lock:
At the same time, MySQL allows multiple sessions to acquire a READ lock for a
table. And all other sessions can read the table without acquiring the lock.
If the session holds the READ lock on a table, they cannot perform a write operation on
it. It is because the READ lock can only read data from the table. All other sessions that
do not acquire a READ lock are not able to write data into the table without releasing
the READ lock. The write operations go into the waiting states until we have not
released the READ lock.
Let us take an example to see how READ locks work in MySQL with the given scenario. We
will first connect to the database and use the CONNECTION_ID() function that gives the
current connection id in the first session as follows:
SELECT CONNECTION_ID();
Next, we will insert few rows into the info_table using the below statement:
Now, verify the data into the table using the below statement:
After that, we will try to insert a new record into the info_table as follows:
We will get the below output where MySQL issues the following message "Table
'info_table' was locked with a READ lock and can't be updated".
Thus, we can see that once the READ lock is acquired on to the table, we cannot write
data to the table in the same session.
Now, we will check how the READ lock work from a different session. First, we will
connect to the database and see the connection id:
Next, we will query data from the info_table that returns the output as follows:
In the above output, we can see that the insert operation from the second session is in
the waiting state. It is due to the READ lock, which is already acquired on the table by
the first session and has not been released yet.
We can see the detailed information about them using the SHOW PROCESSLIST
statement in the first session. See the below output:
Finally, we need to release the lock by using the UNLOCK TABLES statement in the
first session. Now, we are able to execute the INSERT operation in the second session.
Write Locks
The following are the features of a WRITE lock:
• It is the session that holds the lock of a table and can read and write data both from the
table.
• It is the only session that accesses the table by holding a lock. And all other sessions
cannot access the data of the table until the WRITE lock is released.
Let us take an example to see how WRITE locks works in MySQL with the given scenario. In
the first session, we will acquire a WRITE lock using the below statement:
The above statement worked. Now, we can verify the output using the SELECT statement:
Again, we will attempt to access (read/write) the table from the second session:
We can see that these operations are put into a waiting state. See the detailed information
about them using the SHOW PROCESSLIST statement:
Finally, we will release the lock from the first session. Now, we can execute the pending
operations.
• Read lock is similar to "shared" locks because multiple threads can acquire it at the
same time.
• Write lock is an "exclusive" locks because another thread cannot read it.
• We cannot provide read and write locks both on the table at the same time.
• Read lock has a low priority than Write lock, which ensures that updates are made as
soon as possible.
RESULT : Thus studied CALL, EXPLAIN & LOCK commands and implemented them
on the database.
EXPERIMENT NO: 4
Every user will have some pre-defined privileges; accordingly, the data can be accessed
by that particular user. Using the DCL commands in SQL, we can give privileges to the
user on the SQL database and tables, or we can also revoke the given privileges from
the user.
GRANT Command
The grant statement enables system administrators to assign privileges and roles to the
MySQL user accounts so that they can use the assigned permission on the database
whenever required.
Syntax:-
The following are the basic syntax of using the GRANT statement:
GRANT privilege_name(s)
ON object
TO user_account_name;
Parameter Explanation
Privilege Levels
Database
GRANT ALL It applies to all objects in the current database. We need to use
ON mydb.* the db_name.* syntax for applying this privilege. Here, a user
TO john@localhost; can query data from all tables in the given database.
GRANT DELETE
Table
ON mydb.employees
It applies on all columns in a specified table. We need to use
TO john@localhsot;
db_name.table_name syntax for assigning this privilege. Here, a
user can query data from the given table of the specified
database.
Column It applies on a single column of a table. Here, we must have to
GRANT SELECT (col1),
specify the column(s) name enclosed with parenthesis for each
INSERT (col1, col2),
privilege. The user can select one column, insert values in two
UPDATE (col2)
columns, and update only one column in the given table.
ON mydb.mytable
TO john@localhost;
Let us understand the GRANT privileges through the example. First, we need to create a new
user named "john@localhost" using the following statement:
Next, execute the SHOW GRANT statement to check the privileges assigned to
john@localhost using the following query:
SHOW GRANTS FOR john@localhost;
It will give the below output. Here, the USAGE means a user can log in to the database but
does not have any privileges.
If we want to assign all privileges to all databases in the current server to john@localhost,
execute the below statement:
Again, execute the SHOW GRANT statement to verify the privileges. After the successful
execution, we will get the below output. Here all privileges are assigned to all databases in the
current server to john@localhost.
RESULT : Thus studied GRANT command and implemented them on the database.
EXPERIMENT NO: 5
Every user will have some pre-defined privileges; accordingly, the data can be accessed
by that particular user. Using the DCL commands in SQL, we can give privileges to the
user on the SQL database and tables, or we can also revoke the given privileges from
the user.
REVOKE Command
The revoke statement enables system administrators to revoke privileges and roles to the
MySQL user accounts so that they cannot use the assigned permission on the database in the
past.
Syntax:-
The following are the basic syntax of using the REVOKE statement:
REVOKE privilege_name(s)
ON object
FROM user_account_name;
Parameter Explanation
user_account_name It determines the account name of the user from which we want to
revoke the access rights.
Privilege Levels
Column REVOKE SELECT (col1), INSERT (col1, col2), It applies to revoke privileges
UPDATE (col2) ON mydb.mytable from a single column of a table.
FROM john@localhost;
Let us understand the REVOKE privileges through the example. First, we need to create a
new user named "john@localhost" using the following statement:
Next, assign all privileges to all databases in the current server to john@localhost, using the
below statement:
Next, execute the SHOW GRANT statement to verify the privileges. In the output, we can see
that all privileges are assigned to all databases in the current server to john@localhost.
If we want to revoke all privileges assign to the user, execute the following statement:
We will get the output below where we can see that a user can log in to the database without
any privileges.
REVOKE selected privilege from a user account
Suppose we have provided grant privilege of SELECT, INSERT, and UPDATE command on
mystudentdb to the user with the following statement:
Finally, execute the REVOKE statement to remove UPDATE and INSERT privilege with the
below statement:
It will give the below output where only SELECT privilege is left.
First, we need to grant the proxy privilege to the user whom you want using the following
statement:
Finally, execute the REVOKE statement to remove proxy privilege from the user with the
below statement:
REVOKE PROXY ON 'peter@javatpoint' FROM 'john'@'localhost';
It will give the below output where proxy privilege is revoked successfully.
RESULT : Thus studied REVOKE command and implemented them on the database.