Dbms 5 Unit
Dbms 5 Unit
Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of information.
o Integrity constraints ensure that the data insertion, updating, and other processes have
to be performed in such a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the database.
o Domain constraints can be defined as the definition of a valid set of values for an
attribute.
o The data type of domain includes string, character, integer, time, date, currency, etc. The
value of the attribute must be available in the corresponding domain.
Example:
Example:
Example:
4. Key constraints
o Keys are the entity set that is used to identify an entity within its entity set uniquely.
o An entity set can have multiple keys, but out of which one key will be the primary key. A
primary key can contain a unique and null value in the relational table.
Example:
Lock-Based Protocol
In this type of protocol, any transaction cannot read or write data until it acquires an appropriate
lock on it. There are two types of lock:
1. Shared lock:
o It is also known as a Read-only lock. In a shared lock, the data item can only read by the
transaction.
o It can be shared between the transactions because when the transaction holds a lock,
then it can't update the data on the data item.
2. Exclusive lock:
o In the exclusive lock, the data item can be both reads as well as written by the
transaction.
o This lock is exclusive, and in this lock, multiple transactions do not modify the same data
simultaneously.
It is the simplest way of locking the data while transaction. Simplistic lock-based protocols allow
all the transactions to get the lock on the data before insert or delete or update on it. It will
unlock the data item after completing the transaction.
o Pre-claiming Lock Protocols evaluate the transaction to list all the data items on which
they need locks.
o Before initiating an execution of the transaction, it requests DBMS for all the lock on all
those data items.
o If all the locks are granted then this protocol allows the transaction to begin. When the
transaction is completed then it releases all the lock.
o If all the locks are not granted then this protocol allows the transaction to rolls back and
waits until all the locks are granted.
3. Two-phase locking (2PL)
o The two-phase locking protocol divides the execution phase of the transaction into three
parts.
o In the first part, when the execution of the transaction starts, it seeks permission for the
lock it requires.
o In the second part, the transaction acquires all the locks. The third phase is started as
soon as the transaction releases its first lock.
o In the third phase, the transaction cannot demand any new locks. It only releases the
acquired locks.
There are two phases of 2PL:
Growing phase: In the growing phase, a new lock on the data item may be acquired by the
transaction, but none can be released.
Shrinking phase: In the shrinking phase, existing lock held by the transaction may be released,
but no new locks can be acquired.
In the below example, if lock conversion is allowed then the following phase can happen:
Example:
The following way shows how unlocking and locking work with 2-PL.
Transaction T1:
Transaction T2:
MySQL 8.0 only supports partitioning in InnoDB and NDB storage engines. Other storage
engines such as MyISAM, MERGE, CSV, and FEDERATED cannot have support for partitioning.
MySQL has mainly two forms of partitioning:
1. Horizontal Partitioning
This partitioning split the rows of a table into multiple tables based on our logic. In horizontal
partitioning, the number of columns is the same in each table, but no need to keep the same
number of rows. It physically divides the table but logically treated as a whole. Currently, MySQL
supports this partitioning only.
2. Vertical Partitioning
This partitioning splits the table into multiple tables with fewer columns from the original table.
It uses an additional table to store the remaining columns. Currently, MySQL does not provide
supports for this partitioning.
Benefits of Partitioning
o It optimizes the query performance. When we query on the table, it scans only the
portion of a table that will satisfy the particular statement.
o It is possible to store extensive data in one table that can be held on a single disk or file
system partition.
o It provides more control to manage the data in your database.
We can create a partition in MySQL using the CREATE TABLE or ALTER TABLE statement. Below
is the syntax of creating partition using CREATE TABLE command:
MySQL has mainly six types of partitioning, which are given below:
1. RANGE Partitioning
2. LIST Partitioning
3. COLUMNS Partitioning
4. HASH Partitioning
5. KEY Partitioning
6. Subpartitioning
This partitioning allows us to partition the rows of a table based on column values that fall
within a specified range. The given range is always in a contiguous form but should not overlap
each other, and also uses the VALUES LESS THAN operator to define the ranges.
In the following example, we are going to create a table named "Sales" containing the five
columns cust_id, name, store_id, bill_no, bill_date, and amount. Next, we will partition this table
by using a range in several ways based on our needs. Here, we will use the bill_date column for
partitioning and then partition the table's data in four ways using a PARTITION BY RANGE
clause:
We can see that the records are successfully inserted into the Sales table.
We can see the partition created by CREATE TABLE statement using the below query:
We will get the following output where four partitions are created successfully:
DROP MySQL Partition
Sometimes our table contains the data that is useless in the partition table. In that case, we can
drop single or multiple partitions based on the need. The following statement is used to delete
all rows from the partition p0 of table Sales:
After successful execution, we can see that the two rows are deleted from the table.
It is the same as Range Partitioning. Here, the partition is defined and selected based on
columns matching one of a set of discrete value lists rather than a set of a contiguous range of
values. It is performed by the PARTITION BY LIST(exp) clause. The exp is an expression or
column value that returns an integer value. The VALUES IN(value_lists) statement will be used to
define each partition.
In the below example, suppose we have 12 stores distributed among four franchises based on
their region. The table explains it more clearly:
We can partition the above table where rows for stores belonging to the same region and will
be stored in the same partition. The following statement arranges the stores in the same region
using LIST partitioning, as shown below:
1. CREATE TABLE Stores (
2. cust_name VARCHAR(40),
3. bill_no VARCHAR(20) NOT NULL,
4. store_id INT PRIMARY KEY NOT NULL,
5. bill_date DATE NOT NULL,
6. amount DECIMAL(8,2) NOT NULL
7. )
8. PARTITION BY LIST(store_id) (
9. PARTITION pEast VALUES IN (101, 103, 105),
10. PARTITION pWest VALUES IN (102, 104, 106),
11. PARTITION pNorth VALUES IN (107, 109, 111),
12. PARTITION pSouth VALUES IN (108, 110, 112));
This partitioning is used to distribute data based on a predefined number of partitions. In other
words, it splits the table as of the value returned by the user-defined expression. It is mainly
used to distribute data evenly into the partition. It is performed with the PARTITION BY
HASH(expr) clause. Here, we can specify a column value based on the column_name to be
hashed and the number of partitions into which the table is divided.
This statement is used to create table Store using CREATE TABLE command and uses hashing on
the store_id column that divided it into four partitions:
NOTE: If you do not use the PARTITIONS clause, the number of partitions will be one by default. If
you do not specify the number with the PARTITIONS keyword, it will throw an error.
This partitioning allows us to use the multiple columns in partitioning keys. The purpose of these
columns is to place the rows in partitions and determine which partition will be validated for
matching rows. It is mainly divided into two types:
They provide supports for the use of non-integer columns to define the ranges or value lists.
They support the following data types:
o All Integer Types: TINYINT, SMALLINT, MEDIUMINT, INT (INTEGER), and BIGINT.
o String Types: CHAR, VARCHAR, BINARY, and VARBINARY.
o DATE and DATETIME data types.
Range Column Partitioning: It is similar to the range partitioning with one difference. It defines
partitions using ranges based on various columns as partition keys. The defined ranges are of
column types other than an integer type.
In this example, the table "test_part" contains the four columns A, B, C, and D. We have used
the first three columns in partitioning in the order of A, B, C. And, each list value is used to
define a partition that contains three values in the same order as INT, CHAR, and INT. After
execution, we will get the output as below and verified by the SELECT statement successfully.
List Columns Partitioning: It takes a list of single or multiple columns as partition keys. It
enables us to use various columns of types other than integer types as partitioning columns. In
this partitioning, we can use String data types, DATE, and DATETIME columns.
The following example explains it more clearly. Suppose a company has many agents in three
cities for marketing purposes. We can organize it as below:
The following statement uses a List Columns Partitioning to organize the agents:
It is similar to the HASH partitioning where the hash partitioning uses the user-specified
expression, and MySQL server supplied the hashing function for key. If we use other storage
engines, the MySQL server employs its own internal hashing function that is performed by using
the PARTITION BY KEY clause. Here, we will use KEY rather than HASH that can accept only a list
of zero or more column names.
If the table contains a PRIMARY KEY and we have not specified any column for partition, then
the primary key is used as partitioning key. The below example explains it more clearly:
If the table have unique key but not contains the primary key, then a UNIQUE KEY is used as a
partition key.
SUBPARTITIONING
It is a composite partitioning that further splits each partition in a partition table. The below
example helps us to understand it more clearly:
We can use SQL Server Synonym in various scenarios and take advantage out of them. Some of
the scenarios are:
o Name_of_schema: The name_of_schema is the name of the schema where the synon
o ym is going to be created.
o Name_of_synonym: The name_of_synonym represents the name of the synonym.
o Name_of_base_object: The name_of_base_object represents the name of the base object
to which the synonym is going to be assigned.
Let us understand SQL Server Synonym with the help of an example. Let us create a database
and select that particular database. The syntax for creating and selecting that database is:
Now, we will create a schema and a table inside that schema. The syntax for the creation of a
schema and a table is:
As we can see in the image a schema named 'grocery' has been created successfully and a table
named fruits having two columns to store the quantity and name of the fruits inside the grocery
schema is also created successfully.
Now let us add some data to the fruits table. The syntax for the same is:
1. INSERT INTO grocery.fruits(fruit_name,quantity) VALUES('Apple',12);
2. INSERT INTO grocery.fruits(fruit_name,quantity) VALUES('Coconut',2);
3. INSERT INTO grocery.fruits(fruit_name,quantity) VALUES('Blueberry',30);
4. INSERT INTO grocery.fruits(fruit_name,quantity) VALUES('Apricot',15);
5. INSERT INTO grocery.fruits(fruit_name,quantity) VALUES('Black Currant',20);
6. INSERT INTO grocery.fruits(fruit_name,quantity) VALUES('Cantaloupe',6);
7. INSERT INTO grocery.fruits(fruit_name,quantity) VALUES('Dates',40);
As shown in the image the seven rows of data have been inserted into the fruits table. And the
same can be seen as the output of the SELECT command.
Whenever we want to refer to the fruits table, first we need to write the database name followed
by the schema name and then the name of the table. To reduce this overhead, we can create a
synonym with the syntax:
So, this article helps us to understand the working of the Synonym in SQL Server and how to use
it according to our problem requirement.
PL/SQL Introduction
Read
Discuss
Courses
Practice
PL/SQL is a block structured language that enables developers to combine the power of SQL
with procedural statements.All the statements of a block are passed to oracle engine all at once
which increases processing speed and decreases the traffic.
Basics of PL/SQL
•PL/SQL stands for Procedural Language extensions to the Structured Query Language
(SQL).
PL/SQL is a combination of SQL along with the procedural features of programming
languages.
Oracle uses a PL/SQL engine to processes the PL/SQL statements.
PL/SQL includes procedural language elements like conditions and loops. It allows
declaration of constants and variables, procedures and functions, types and variable of those
types and triggers.
Disadvantages of SQL:
SQL doesn’t provide the programmers with a technique of condition checking, looping and
branching.
SQL statements are passed to Oracle engine one at a time which increases traffic and
decreases speed.
SQL has no facility of error checking during manipulation of data.
Features of PL/SQL:
1. PL/SQL is basically a procedural language, which provides the functionality of decision
making, iteration and many more features of procedural programming languages.
2. PL/SQL can execute a number of queries in one block using single command.
3. One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types,
which are stored in the database for reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as
exception handling block.
5. Applications written in PL/SQL are portable to computer hardware or operating system
where Oracle is operational.
6. PL/SQL Offers extensive error checking.
Differences between SQL and PL/SQL:
SQL PL/SQL
other.
Typically, each block performs a logical action in the program. A block has the following
structure:
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
Declare section starts with DECLARE keyword in which variables, constants, records as
cursors can be declared which stores data temporarily. It basically consists definition of
PL/SQL identifiers. This part of the code is optional.
Execution section starts with BEGIN and ends with END keyword.This is a mandatory
section and here the program logic is written to perform any task like loops and conditional
statements. It supports all DML commands, DDL commands and SQL*PLUS built-in
functions as well.
Exception section starts with EXCEPTION keyword.This section is optional which contains
statements that are executed when a run-time error occurs. Any exceptions can be handled in
this section.
PL/SQL identifiers
There are several PL/SQL identifiers such as variables, constants, procedures, cursors, triggers
etc.
1. Variables: Like several other programming languages, variables in PL/SQL must be declared
prior to its use. They should have a valid name and data type as well. Syntax for declaration
of variables:
variable_name datatype [NOT NULL := value ];
1. Example to show how to declare variables in PL/SQL :
C
SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;
BEGIN
null;
END;
1. Output:
PL/SQL procedure successfully completed.
1. Explanation:
SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.
var1 INTEGER : It is the declaration of variable, named var1 which is of integer type.
There are many other data types that can be used like float, int, real, smallint, long etc. It
also supports variables used in SQL as well like NUMBER(prec, scale), varchar, varchar2
etc.
PL/SQL procedure successfully completed.: It is displayed when the code is compiled
and executed successfully.
Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.
Assignment operator (:=) : It is used to assign a value to a variable.
2. Displaying Output: The outputs are displayed by using DBMS_OUTPUT which is a built-in
package that enables the user to display output, debugging information, and send messages
from PL/SQL blocks, subprograms, packages, and triggers. Let us see an example to see how
to display a message using PL/SQL :
C
SQL> DECLARE
BEGIN
dbms_output.put_line(var);
END;
1. Output:
I love GeeksForGeeks
SQL> DECLARE
a number := &a;
b varchar2(30) := &b;
BEGIN
null;
END;
1. Output:
Enter value for a: 24
old 2: a number := &a;
new 2: a number := 24;
Enter value for b: 'GeeksForGeeks'
old 3: b varchar2(30) := &b;
new 3: b varchar2(30) := 'GeeksForGeeks';
PL/SQL procedure successfully completed.
1. (***) Let us see an example on PL/SQL to demonstrate all above concepts in one single
block of code.
C
--PL/SQL code to print sum of two numbers taken from the user.
SQL> DECLARE
a integer := &a ;
b integer := &b ;
c integer ;
BEGIN
c := a + b ;
END;
/
Sum of 2 and 3 is = 5
SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
Datatype of SQL:
1. Binary Datatypes
There are Three types of binary Datatypes which are given below:
binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.
varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.
image It has a maximum length of 2,147,483,647 bytes. It contains variable-length binary data.
float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value e.g. 6.2, 2.9 etc.
char It has a maximum length of 8000 characters. It contains Fixed-length non-unicode characters.
varchar It has a maximum length of 8000 characters. It contains variable-length non-unicode characters.
text It has a maximum length of 2,147,483,647 characters. It contains variable-length non-unicode cha
Datatype Description
timestamp It stores the year, month, day, hour, minute, and the second value.
SQL Commands
o SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.
o DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.
o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
o CREATE
o ALTER
o DROP
o TRUNCATE
Syntax:
Example:
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
Example
c. ALTER: It is used to alter the structure of the database. This change could be either to modify
the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
EXAMPLE
Syntax:
Example:
o DML commands are used to modify the database. It is responsible for all form of
changes in the database.
o The command of DML is not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.
o INSERT
o UPDATE
o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.
Syntax:
Or
For example:
Syntax:
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
Syntax:
For example:
DCL commands are used to grant and take back authority from any database user.
o Grant
o Revoke
Example
Example
1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.
These operations are automatically committed in the database that's why they cannot be used
while creating tables or dropping them.
o COMMIT
o ROLLBACK
o SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
1. COMMIT;
Example:
b. Rollback: Rollback command is used to undo transactions that have not already been saved
to the database.
Syntax:
1. ROLLBACK;
Example:
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the
entire transaction.
Syntax:
1. SAVEPOINT SAVEPOINT_NAME;
o SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to select
the attribute based on the condition described by WHERE clause.
Syntax:
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:
1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;
Next Topi