0% found this document useful (0 votes)
24 views28 pages

RDBMS Unit 1

The document discusses SQL transaction control commands and provides examples of INSERT, UPDATE, and DELETE commands. It explains how to insert, update, and delete data from database tables and specifies column values. It also covers the CREATE command and how to create databases and tables.

Uploaded by

gm767305
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)
24 views28 pages

RDBMS Unit 1

The document discusses SQL transaction control commands and provides examples of INSERT, UPDATE, and DELETE commands. It explains how to insert, update, and delete data from database tables and specifies column values. It also covers the CREATE command and how to create databases and tables.

Uploaded by

gm767305
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/ 28

UNIT-I

Advanced SQL
Transaction control
Transaction Control Language(TCL) commands are used to manage transactions in
the database.
Before moving forward with TCL commands, check these topics out first:

 DML commands
 DDL Commands

Data Manipulation Language (DML) statements are used for managing data
in database. DML commands are not auto-committed. It means changes
made by DML command are not permanent to database, it can be rolled
back.

Talking about the Insert command, whenever we post a Tweet on Twitter,


the text is stored in some table, and as we post a new tweet, a new record
gets inserted in that table.

INSERT command

Insert command is used to insert data into a table. Following is its general
syntax,

INSERT INTO table_name VALUES(data1, data2, ...)

Copy
Lets see an example,

Consider a table student with the following fields.

s_id name age

INSERT INTO student VALUES(101, 'Adam', 15);

Copy
The above command will insert a new record into student table.
1
s_id name age
101 Adam 15

Insert value into only specific columns

We can use the INSERT command to insert values for only some specific
columns of a row. We can specify the column names along with the values
to be inserted like this,

INSERT INTO student(id, name) values(102, 'Alex');

Copy
The above SQL query will only insert id and name values in the newly
inserted record.

Insert NULL value to a column

Both the statements below will insert NULL value into age column of
the student table.

INSERT INTO student(id, name) values(102, 'Alex');

Copy
Or,

INSERT INTO Student VALUES(102,'Alex', null);

Copy
The above command will insert only two column values and the other
column is set to null.

S_id S_Name age


101 Adam 15
102 Alex

2
Insert Default value to a column

INSERT INTO Student VALUES(103,'Chris', default)

Copy
S_id S_Name age
101 Adam 15
102 Alex
103 chris 14
Suppose the column age in our tabel has a default value of 14.

Also, if you run the below query, it will insert default value into the age
column, whatever the default value may be.

INSERT INTO Student VALUES(103,'Chris')

Using UPDATE SQL command


Let's take an example of a real-world problem. These days, Facebook
provides an option for Editing your status update, how do you think it
works? Yes, using the Update SQL command.

Let's learn about the syntax and usage of the UPDATE command.

UPDATE command

UPDATE command is used to update any record of data in a table. Following


is its general syntax,

UPDATE table_name SET column_name = new_value WHERE some_condition;

Copy
WHEREis used to add a condition to any SQL query, we will soon
study about it in detail.
Lets take a sample table student,
3
student_id name age
101 Adam 15
102 Alex
103 chris 14

UPDATE student SET age=18 WHERE student_id=102;

Copy
S_id S_Name age
101 Adam 15
102 Alex 18
103 chris 14
In the above statement, if we do not use the WHERE clause, then our update
query will update age for all the columns of the table to 18.

Updating Multiple Columns

We can also update values of multiple columns using a


single UPDATE statement.

UPDATE student SET name='Abhi', age=17 where s_id=103;

Copy
The above command will update two columns of the record which
has s_id 103.

s_id name age


101 Adam 15
102 Alex 18
103 Abhi 17

UPDATE Command: Incrementing Integer Value

4
When we have to update any integer value in a table, then we can fetch
and update the value in the table in a single statement.

For example, if we have to update the age column of student table every
year for every student, then we can simply run the
following UPDATE statement to perform the following operation:

UPDATE student SET age = age+1;

Copy
As you can see, we have used age = age + 1 to increment the value of age by 1.

NOTE: This style only works for integer values.


Using DELETE SQL command
When you ask any question in Studytonight's Forum it gets saved into a
table. And using the Delete option, you can even delete a question asked
by you. How do you think that works? Yes, using the Delete DML command.

Let's study about the syntax and the usage of the Delete command.

DELETE command

DELETE command is used to delete data from a table.

Following is its general syntax,

DELETE FROM table_name;

Copy
Let's take a sample table student:

s_id name age


101 Adam 15
102 Alex 18
103 Abhi 17

5
Delete all Records from a Table

DELETE FROM student;

Copy
The above command will delete all the records from the table student.

Delete a particular Record from a Table

In our student table if we want to delete a single record, we can use


the WHERE clause to provide a condition in our DELETE statement.

DELETE FROM student WHERE s_id=103;

Copy
The above command will delete the record where s_id is 103 from the
table student.

S_id S_Name age


101 Adam 15
102 Alex 18

Isn't DELETE same as TRUNCATE

TRUNCATE command is different from DELETE command. The delete command


will delete all the rows from a table whereas truncate command not only
deletes all the records stored in the table, but it also re-initializes the
table(like a newly created table).

For eg: If you have a table with 10 rows and an auto_increment primary
key, and if you use DELETE command to delete all the rows, it will delete all
the rows, but will not re-initialize the primary key, hence if you will insert
any row after using the DELETE command, the auto_increment primary key
6
will start from 11. But in case of TRUNCATE command, primary key is re-
initialized, and it will again start from 1.

 DDL COMMAND

SQL: create command


create is a DDL SQL command used to create a table or a database in
relational database management system.

Creating a Database

To create a database in RDBMS, create command is used. Following is the


syntax,1

CREATE DATABASE <DB_NAME>;

Copy

Example for creating Database

CREATE DATABASE Test;

Copy
The above command will create a database named Test, which will be an
empty schema without any table.

To create tables in this newly created database, we can again use


the create command.

Creating a Table

7
command can also be used to create tables. Now when we create a
create

table, we have to specify the details of the columns of the tables too. We
can specify the names and datatypes of various columns in
the create command itself.

Following is the syntax,

CREATE TABLE <TABLE_NAME>(

column_name1 datatype1,

column_name2 datatype2,

column_name3 datatype3,

column_name4 datatype4);

Copy
create table command will tell the database system to create a new table

with the given table name and column information.

Example for creating Table

CREATE TABLE Student(

student_id INT,

name VARCHAR(100),

age INT);

Copy
The above command will create a new table with name Student in the
current database with 3 columns, namely student_id, name and age. Where the
column student_id will only store integer, name will hold upto 100 characters
and age will again store only integer value.

8
If you are currently not logged into your database in which you want to
create the table then you can also add the database name along with table
name, using a dot operator .

For example, if we have a database with name Test and we want to create a
table Student in it, then we can do so using the following query:

CREATE TABLE Test.Student(

student_id INT,

name VARCHAR(100),

age INT);

Copy

Most commonly used datatypes for Table columns

Here we have listed some of the most commonly used datatypes used for
columns in tables.

Datatype Use
INT used for columns which will store integer values.
FLOAT used for columns which will store float values.
DOUBLE used for columns which will store float values.
VARCHAR used for columns which will be used to store characters and
integers, basically a string.
CHAR used for columns which will store char values(single character).
DATE used for columns which will store date values.
TEXT used for columns which will store text which is generally long in
length. For example, if you create a table for storing profile
information of a social networking website, then for about
me section you can have a column of type TEXT.

9
SQL: ALTER command
alter command is used for altering the table structure, such as,

 to add a column to existing table

 to rename any existing column

 to change datatype of any column or to modify its size.

 to drop a column from the table.

ALTER Command: Add a new Column

Using ALTER command we can add a column to any existing table. Following
is the syntax,

ALTER TABLE table_name ADD(

column_name datatype);

Copy
Here is an Example for this,

ALTER TABLE student ADD(

address VARCHAR(200));

Copy
The above command will add a new column address to the table student,
which will hold data of type varchar which is nothing but string, of length 200.

ALTER Command: Add multiple new Columns

Using ALTER command we can even add multiple new columns to any
existing table. Following is the syntax,
10
ALTER TABLE table_name ADD(

column_name1 datatype1,

column-name2 datatype2,

column-name3 datatype3);

Copy
Here is an Example for this,

ALTER TABLE student ADD(

father_name VARCHAR(60),

mother_name VARCHAR(60),

dob DATE);

Copy
The above command will add three new columns to the student table

ALTER Command: Add Column with default value

ALTERcommand can add a new column to an existing table with a default


value too. The default value is used when no value is inserted in the column.
Following is the syntax,

ALTER TABLE table_name ADD(

column-name1 datatype1 DEFAULT some_value);

Copy
Here is an Example for this,

ALTER TABLE student ADD(

dob DATE DEFAULT '01-Jan-99');

11
Copy
The above command will add a new column with a preset default value to
the table student.

ALTER Command: Modify an existing Column

ALTERcommand can also be used to modify data type of any existing


column. Following is the syntax,

ALTER TABLE table_name modify(

column_name datatype);

Copy
Here is an Example for this,

ALTER TABLE student MODIFY(

address varchar(300));

Copy
Remember we added a new column address in the beginning? The above
command will modify the address column of the student table, to now hold
upto 300 characters.

ALTER Command: Rename a Column

Using ALTER command you can rename an existing column. Following is the
syntax,

ALTER TABLE table_name RENAME

old_column_name TO new_column_name;

Copy

12
Here is an example for this,

ALTER TABLE student RENAME

address TO location;

Copy
The above command will rename address column to location.

ALTER Command: Drop a Column

ALTER command can also be used to drop or remove columns. Following is


the syntax,

ALTER TABLE table_name DROP(

column_name);

Copy
Here is an example for this,

ALTER TABLE student DROP(

address);

Copy
The above command will drop the address column from the table student.

Truncate, Drop or Rename a Table


We will learn about the various DDL commands which are used to re-define
the tables.

TRUNCATE command

TRUNCATE command removes all the records from a table. But this command
will not destroy the table's structure. When we use TRUNCATE command on a

13
table its (auto-increment) primary key is also initialized. Following is its
syntax,

Copy
Here is an example explaining it,

TRUNCATE TABLE student;

Copy
The above query will delete all the records from the table student.

In DML commands, we will study about the DELETE command which is also
more or less same as the TRUNCATE command. We will also learn about the
difference between the two in that tutorial.

DROP command

DROP command completely removes a table from the database. This


command will also destroy the table structure and the data stored in it.
Following is its syntax,

DROP TABLE table_name

Copy
Here is an example explaining it,

DROP TABLE student;

Copy
The above query will delete the Student table completely. It can also be
used on Databases, to delete the complete database. For example, to drop
a database,

DROP DATABASE Test;

Copy
The above query will drop the database with name Test from the system.

14
RENAME query

RENAME command is used to set a new name for any existing table.
Following is the syntax,

RENAME TABLE old_table_name to new_table_name

Copy
Here is an example explaining it.

RENAME TABLE student to students_info;

Copy
The above query will rename the table student to students_info.

These are used to manage the changes made to the data in a table by DML
statements. It also allows statements to be grouped together into logical
transactions.

COMMIT command

COMMITcommand is used to permanently save any transaction into the


database.

When we use any DML command like INSERT, UPDATE or DELETE, the changes
made by these commands are not permanent, until the current session is
closed, the changes made by these commands can be rolled back.

To avoid that, we use the COMMIT command to mark the changes as


permanent.

Following is commit command's syntax,

COMMIT;

15
Copy

ROLLBACK command

This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.

If we have used the UPDATE command to make some changes into the
database, and realise that those changes were not required, then we can
use the ROLLBACK command to rollback those changes, if they were not
commited using the COMMIT command.

Following is rollback command's syntax,

ROLLBACK TO savepoint_name;

Copy

SAVEPOINT command

SAVEPOINTcommand is used to temporarily save a transaction so that you


can rollback to that point whenever required.

Following is savepoint command's syntax,

SAVEPOINT savepoint_name;

Copy
In short, using this command we can name the different states of our data
in any table and then rollback to that state using the ROLLBACK command
whenever required.

Using Savepoint and Rollback

16
Following is the table class,

id name
1 Abhi
2 Adam
4 Alex
Lets use some SQL queries on the above table and see the results.

INSERT INTO class VALUES(5, 'Rahul');

COMMIT;

UPDATE class SET name = 'Abhijit' WHERE id = '5';

SAVEPOINT A;

INSERT INTO class VALUES(6, 'Chris');

SAVEPOINT B;

INSERT INTO class VALUES(7, 'Bravo');

SAVEPOINT C;

SELECT * FROM class;

Copy
NOTE: SELECT statement is used to show the data stored in the
table.
The resultant table will look like,

id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
17
Now let's use the ROLLBACK command to roll back the state of data to
the savepoint B.

ROLLBACK TO B;

SELECT * FROM class;

Copy
Now our class table will look like,

id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
Now let's again use the ROLLBACK command to roll back the state of data to
the savepoint A

ROLLBACK TO A;

SELECT * FROM class;

Copy
Now the table will look like,

id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
So now you know how the commands COMMIT, ROLLBACK and SAVEPOINT works.

Levels of Locking in DBMS

18
The locking in a database can be done at 4 levels, which start with the
database at the highest level and down via table and page to the row at the
lowest level.

 Database Level
 Table Level
 Page-Level
 Row Level
Before we discuss the levels of locking, we should know about the types of
locks or lock mode. So, there are 5 locks types in the locking and these are
discussed below :

 Exclusive (X) Lock-


This method of locking differentiates the locks based on their usage. This
also ensures that the data or information of a page will be reserved
exclusively for those transactions that used the exclusive lock. These locks
are applied on those resources only where a WRITE operation is
performed. These locks can be applied to a page only if there is no other
shared or exclusive type of lock is applied already.

 Shared (S) Lock –


This method of locking is applied only to the read operations. If this lock is
applied to any row or a page, then it will reserve that row or page for
the read operation. We can apply more than one lock on the same row or
the same page, but it should not apply to any other type of lock.

 Intent exclusive (IX) Lock –


This method of locking explicit locking at a lower level with exclusive or
shared locks. This means that if a transaction has used this type of lock,
then it must be a case of modifying the lower level of resources by
imposing exclusive lock separately.

 Intent shared (IS) Lock –


This method of locking is explicit locking at a lower level of the tree but
only with shared locks. This means that if a transaction has used this type
of lock, then it must be a case of reading the lower level of resources by

19
imposing shared lock separately.

 Shared intent exclusive (SIX) Lock –


This method of locking states that the transaction is used to read the
resources at a lower level. Here in SIX, we impose the shared lock on all
the resources that are available at the lower level. The subtree rooted by
that node is locked explicitly in shared mode and explicit locking is done
at a lower level with exclusive mode locks. In this method, only one SIX
can be acquired on a relation at a time and if there are any other
transactions for updating any change, then it will block those transactions.

 Update (U) Lock –


This method of locking can be imposed on a record that already consists
of a shared lock and if it has a shared lock already, then the update lock
will impose another shared lock on the target row or page of relation.
This is the same as an exclusive lock and also in some ways flexible. Here
in this lock, after checking that the transaction holds the update lock for
modifying the data, then the update lock will be modified into an
exclusive lock.

Drawbacks of locking:
1. May not free from recoverability.
2. Not free from deadlock.
3. Not free from starvation.
4. Not free from cascading rollback.

20
Level of Hierarchy in Locking

Now, let’s discuss the levels of locking one by one.

1. Database Level :
At the database level, the full or complete database is locked. Now, If let’s
say there are two relations in a database. If say, R1 and R2, where R1 uses
tables, then R2 cannot use them. You will always find a shared lock on this
level that is used whenever a transaction is connected to a database. On this
level, we use shared locking to prevent dropping of the database or restoring
a database backup over the database in use. Let’s see an example. When we
use a SELECT statement to read some data, a shared lock will be applied on
the database level, an intent shared lock will be applied on the table and on
the page level, and a shared lock on the row itself.

Applications of Database level –

 This type of locking is suitable for a group of processes.

21
 This type of locking is very slow, so it is not used for the online version
of multi-user DBMS.
2. Table Level :
At the table level, the full table or relation is locked. Now, If let’s say there
are two relations in a database say, R1 and R2, where R1 uses tables, then
R2 cannot use it. But, two transactions can access the same database only if
they are accessing different relations. A transaction using a level of the table
will hold shared and/or exclusive table locks. At the table level, there are 5
different types of locks. i.e, Exclusive (X), Shared (S), Intent exclusive (IX),
Intent shared (IS), and Shared with intent exclusive (SIX) and these locks
have already been discussed above.

Applications of Table level –

 This type of locking level is not suitable for multi-user database


management systems.
 It is also primarily used in preventing a relation from being dropped in
a DML operation.
3. Page Level :
The Page-level always consists of fixed size i.e, power of 2 or 2i type. A table
can span several pages and a page can contain several tuples of one or more
relations. At the page level, an intent shared lock (IS) will be imposed. This
lock is capable of locking a table, shared, or exclusive page. An intent
exclusive lock (IX) or intent update lock (IU) will be imposed if there’s a case
of DML statements (i.e. insert, update, delete).

Applications of Page level –

 This type of locking level is suitable for multi-user database


management systems.
 They are comparatively fast but also there are various conflicts.
4. Row Level :
This level of locking is less restrictive as compared to other levels of
locking. At the row level, if a concurrent transaction is accessing different
rows in the same relationship, even if the rows are located on the same page,
then this can be accepted by database systems. Here at this level, DBMS
allows concurrent transactions to access the rows of the same relation even
in the case of where the rows are on the same page. At this level, we can
22
apply 3 different types of locks, i.e, Exclusive, Shared, Update and these
locks have already been discussed above and also, particular rows are locked
in a query on this level.

Applications of Row level –

 It is very costly compared to other levels of locking.


 It’s also very restrictive.

What is an SQL Sequence?


Sequence is a feature supported by some database systems to produce
unique values on demand. Some DBMS
like MySQL supports AUTO_INCREMENT in place of Sequence.

is applied on columns, it automatically increments the


AUTO_INCREMENT

column value by 1 each time a new record is inserted into the table.

Sequence is also some what similar to AUTO_INCREMENT but it has some


additional features too.

Creating a Sequence

Syntax to create a sequence is,

CREATE SEQUENCE sequence-name

START WITH initial-value

INCREMENT BY increment-value

MAXVALUE maximum-value

CYCLE | NOCYCLE;

Copy
23
 The initial-value specifies the starting value for the Sequence.

 The increment-value is the value by which sequence will be


incremented.

 The maximum-value specifies the upper limit or the maximum value


upto which sequence will increment itself.

 The keyword CYCLE specifies that if the maximum value exceeds the set
limit, sequence will restart its cycle from the begining.

 And, NO CYCLE specifies that if sequence exceeds MAXVALUE value, an


error will be thrown.

Using Sequence in SQL Query

Let's start by creating a sequence, which will start from 1, increment


by 1 with a maximum value of 999.

CREATE SEQUENCE seq_1START WITH 1

INCREMENT BY 1

MAXVALUE 999CYCLE;

Copy

Now let's use the sequence that we just created above.

Below we have a class table,

ID NAME
1 abhi
2 adam
4 alex
The SQL query will be,

INSERT INTO class VALUE(seq_1.nextval, 'anu');

24
Copy
Resultset table will look like,

ID NAME
1 abhi
2 adam
4 alex
1 anu
Once you use nextval the sequence will increment even if you don't Insert any
record into the table.

MySQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.

You can add SQL statements and functions to a view and present the data as if the data
were coming from one single table.

A view is created with the CREATE VIEW statement.

SQL VIEW
A VIEW in SQL is a logical subset of data from one or more tables. View is
used to restrict data access.

Syntax for creating a View,

CREATE or REPLACE VIEW view_name

AS

SELECT column_name(s)

FROM table_name

WHERE condition

25
Copy
As you may have understood by seeing the above SQL query, a view is
created using data fetched from some other table(s). It's more like a
temporary table created with data.

Creating a VIEW

Consider following Sale table,

oid order_name previous_balance customer


11 ord1 2000 Alex
12 ord2 1000 Adam
13 ord3 2000 Abhi
14 ord4 1000 Adam
15 ord5 2000 Alex
SQL Query to Create a View from the above table will be,

CREATE or REPLACE VIEW sale_view AS SELECT * FROM Sale WHERE customer = 'Alex';

Copy
The data fetched from SELECT statement will be stored in another object
called sale_view. We can use CREATE and REPLACE seperately too, but using
both together works better, as if any view with the specified name exists,
this query will replace it with fresh data.

Displaying a VIEW

The syntax for displaying the data in a view is similar to fetching data from
a table using a SELECT statement.

SELECT * FROM sale_view;

Copy

26
Force VIEW Creation

FORCE keyword is used while creating a view, forcefully. This keyword is used
to create a View even if the table does not exist. After creating a force View
if we create the base table and enter values in it, the view will be
automatically updated.

Syntax for forced View is,

CREATE or REPLACE FORCE VIEW view_name AS

SELECT column_name(s)

FROM table_name

WHERE condition;

Copy

Update a VIEW

UPDATE command for view is same as for tables.

Syntax to Update a View is,

UPDATE view-name SET VALUEWHERE condition;

Copy
NOTE: If we update a view it also updates base table data automatically.

Read-Only VIEW

We can create a view with read-only option to restrict access to the view.

27
Syntax to create a view with Read-Only Access

CREATE or REPLACE FORCE VIEW view_name AS

SELECT column_name(s)

FROM table_name

WHERE condition WITH read-only;

Copy
The above syntax will create view for read-only purpose, we cannot
Update or Insert data into read-only view. It will throw an error.

Types of View

There are two types of view,

 Simple View

 Complex View

Simple View Complex View


Created from one table Created from one or more table
Does not contain functions Contain functions
Does not contain groups of data Contains groups of data

28

You might also like