Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

Constraints in DBMS

In DBMS (Database Management Systems), constraints are guidelines or limitations


imposed on database tables to maintain the integrity, correctness, and consistency of
the data. Constraints can be used to enforce data linkages across tables, verify that
data is unique, and stop the insertion of erroneous data. A database needs constraints
to be reliable and of high quality.

What are the Constraints of DBMS?


In DBMS, constraints refer to limitations placed on data or data processes. This
indicates that only a particular type of data may be entered into the database or that
only a particular sort of operation can be performed on the data inside.

Constraints thereby guarantee data accuracy in a database management system


(DBMS).

The following can be guaranteed via constraints


Data Accuracy − Data accuracy is guaranteed by constraints, which make sure that only
true data is entered into a database. For example, a limitation may stop a user from
entering a negative value into a field that only accepts positive numbers.
Data Consistency − The consistency of data in a database can be upheld by using
constraints. These constraints are able to ensure that the primary key value in one
table is followed by the foreign key value in another table.
Data integrity − The accuracy and completeness of the data in a database are ensured by
constraints. For example, a constraint can stop a user from putting a null value into a
field that requires one.

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.

Types of Integrity Constraint


1. Domain constraints

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:

2. Entity integrity constraints


o The entity integrity constraint states that primary key value can't be null.
o This is because the primary key value is used to identify individual rows in relation and if
the primary key has a null value, then we can't identify those rows.
o A table can contain a null value other than the primary key field.

Example:

3. Referential Integrity Constraints

o A referential integrity constraint is specified between two tables.


o In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary
Key of Table 2, then every value of the Foreign Key in Table 1 must be null or be
available in Table 2.

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.

There are four types of lock protocols available:


1. Simplistic lock protocol

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.

2. Pre-claiming Lock Protocol

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:

1. Upgrading of lock (from S(a) to X (a)) is allowed in growing phase.


2. Downgrading of lock (from X(a) to S(a)) must be done in shrinking phase.

Example:
The following way shows how unlocking and locking work with 2-PL.

Transaction T1:

o Growing phase: from step 1-3


o Shrinking phase: from step 5-7
o Lock point: at 3

Transaction T2:

o Growing phase: from step 2-6


o Shrinking phase: from step 8-9
o Lock point: at 6

4. Strict Two-phase locking (Strict-2PL)


o The first phase of Strict-2PL is similar to 2PL. In the first phase, after acquiring all the
locks, the transaction continues to execute normally.
o The only difference between 2PL and strict 2PL is that Strict-2PL does not release a lock
after using it.
o Strict-2PL waits until the whole transaction to commit, and then it releases all the locks at
a time.
o Strict-2PL protocol does not have shrinking phase of lock release.

It does not have cascading abort as 2PL does.

What is partitioning in MySQL?


Partitioning in MySQL is used to split or partition the rows of a table into separate tables in
different locations, but still, it is treated as a single table. It distributes the portions of the table's
data across a file system based on the rules we have set as our requirement. The rule that we
have set to accomplish the division of table data is called as a partitioning function (modulus, a
linear or internal hashing function, etc.). The selected function is based on the partitioning type
we have specified and takes a user-supplied expression as its parameter. The user- expression
can be a column value or a function acting on column values, depending on the type of
partitioning used.

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

The following are the benefits of partitioning in MySQL:

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.

How can we partition the table in MySQL?

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:

1. CREATE TABLE [IF NOT EXISTS] table_name


2. (column_definitions)
3. [table_options]
4. [partition_options]

1. partition_options: It provides control on the table partition.


2.
3. PARTITION BY
4. { [LINEAR] HASH(exp)
5. | [LINEAR] KEY [ALGORITHM={1 | 2}] (colm_list)
6. | RANGE{(exp) | COLUMNS(colm_list)}
7. | LIST{(exp) | COLUMNS(colm_list)} }
8. [PARTITIONS num]
9. [SUBPARTITION BY
10. { [LINEAR] HASH(exp)
11. | [LINEAR] KEY [ALGORITHM={1 | 2}] (colm_list) }
12. [SUBPARTITIONS num]
13. ]
14. [(partition_definition [, partition_definition] ...)]
15.
16. partition_definition: It defines each partition individually.
17.
18. PARTITION part_name
19. [VALUES
20. {LESS THAN {(exp | val_list) | MAXVALUE}
21. |
22. IN (val_list)}]
23. [[STORAGE] ENGINE = engine_name]
24. [COMMENT = 'string' ]
25. [DATA DIRECTORY = 'data_dir']
26. [INDEX DIRECTORY = 'index_dir']
27. [MAX_ROWS = max_number_of_rows]
28. [MIN_ROWS = min_number_of_rows]
29. [TABLESPACE = tablespace_name]
30. [(subpartition_definition [, subpartition_definition] ...)]
31.
32. subpartition_definition: It is optional.
33.
34. SUBPARTITION logical_name
35. [[STORAGE] ENGINE [=] engine_name]
36. [COMMENT [=] 'string' ]
37. [DATA DIRECTORY [=] 'data_dir']
38. [INDEX DIRECTORY [=] 'index_dir']
39. [MAX_ROWS [=] max_number_of_rows]
40. [MIN_ROWS [=] min_number_of_rows]
41. [TABLESPACE [=] tablespace_name]
The below is the syntax of creating partition using ALTER TABLE command:

1. ALTER TABLE [IF EXISTS] tab_name


2. (colm_definitions)
3. [tab_options]
4. [partition_options]

Types of MySQL Partitioning

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

Let us discuss each partitioning in detail.

MySQL RANGE Partitioning

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:

1. CREATE TABLE Sales ( cust_id INT NOT NULL, name VARCHAR(40),


2. store_id VARCHAR(20) NOT NULL, bill_no INT NOT NULL,
3. bill_date DATE PRIMARY KEY NOT NULL, amount DECIMAL(8,2) NOT NULL)
4. PARTITION BY RANGE (year(bill_date))(
5. PARTITION p0 VALUES LESS THAN (2016),
6. PARTITION p1 VALUES LESS THAN (2017),
7. PARTITION p2 VALUES LESS THAN (2018),
8. PARTITION p3 VALUES LESS THAN (2020));
Next, we need to insert records into the table as below statement:

1. INSERT INTO Sales VALUES


2. (1, 'Mike', 'S001', 101, '2015-01-02', 125.56),
3. (2, 'Robert', 'S003', 103, '2015-01-25', 476.50),
4. (3, 'Peter', 'S012', 122, '2016-02-15', 335.00),
5. (4, 'Joseph', 'S345', 121, '2016-03-26', 787.00),
6. (5, 'Harry', 'S234', 132, '2017-04-19', 678.00),
7. (6, 'Stephen', 'S743', 111, '2017-05-31', 864.00),
8. (7, 'Jacson', 'S234', 115, '2018-06-11', 762.00),
9. (8, 'Smith', 'S012', 125, '2019-07-24', 300.00),
10. (9, 'Adam', 'S456', 119, '2019-08-02', 492.20);

To verify the record, we will execute the below statement:

1. SELECT * FROM Sales;

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:

1. SELECT TABLE_NAME, PARTITION_NAME, TABLE_ROWS, AVG_ROW_LENGTH, DATA_LENGTH


2. FROM INFORMATION_SCHEMA.PARTITIONS
3. WHERE TABLE_SCHEMA = 'myemployeedb' AND TABLE_NAME = 'Sales';

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:

1. ALTER TABLE Sales TRUNCATE PARTITION p0;

After successful execution, we can see that the two rows are deleted from the table.

We can verify the partition table using the query below:

1. SELECT PARTITION_NAME, TABLE_ROWS


2. FROM INFORMATION_SCHEMA.PARTITIONS
3. WHERE TABLE_SCHEMA = 'myemployeedb' AND TABLE_NAME = 'Sales';
In the output, we can see that partition p0 does not contain any rows.

MySQL LIST Partitioning

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:

Region Store ID Number

East 101, 103, 105

West 102, 104, 106

North 107, 109, 111

South 108, 110, 112

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));

After the successful execution, it will give following output;

MySQL HASH Partitioning

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:

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 HASH(store_id)
9. PARTITIONS 4;

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.

MySQL COLUMN Partitioning

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:

o RANGE Columns Partitioning


o LIST Columns Partitioning

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.

The following are the syntax for Range Columns Partitioning.

1. CREATE TABLE tab_name


2. PARTITIONED BY RANGE COLUMNS(colm_list) (
3. PARTITION part_name VALUES LESS THAN (val_list)[,
4. PARTITION parti_name VALUES LESS THAN (val_list)][,
5. ...]
6. )
7.
8. colm_list: It is a list of one or more columns.
9. colm_name[, colm_name][, ...]
10.
11. val_list: It is a list of values that supplied for each partition definition and have the same numbe
r of values as of columns.
12. val[, val][, ...]

Let us understand it with the below example.

1. CREATE TABLE test_part (A INT, B CHAR(5), C INT, D INT)


2. PARTITION BY RANGE COLUMNS(A, B, C)
3. (PARTITION p0 VALUES LESS THAN (50, 'test1', 100),
4. PARTITION p1 VALUES LESS THAN (100, 'test2', 200),
5. PARTITION p2 VALUES LESS THAN (150, 'test3', 300),
6. PARTITION p3 VALUES LESS THAN (MAXVALUE, MAXVALUE, MAXVALUE));

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:

City Marketing Agents

New York A1, A2, A3

Texas B1, B2, B3

California C1, C2, C3

The following statement uses a List Columns Partitioning to organize the agents:

1. CREATE TABLE AgentDetail (


2. agent_id VARCHAR(10),
3. agent_name VARCHAR(40),
4. city VARCHAR(10))
5. PARTITION BY LIST COLUMNS(agent_id) (
6. PARTITION pNewyork VALUES IN('A1', 'A2', 'A3'),
7. PARTITION pTexas VALUES IN('B1', 'B2', 'B3'),
8. PARTITION pCalifornia VALUES IN ('C1', 'C2', 'C3'));

After the successful execution, we will get the output as below:


MySQL KEY Partitioning

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:

1. CREATE TABLE AgentDetail (


2. agent_id INT NOT NULL PRIMARY KEY,
3. agent_name VARCHAR(40)
4. )
5. PARTITION BY KEY()
6. PARTITIONS 2;

If the table have unique key but not contains the primary key, then a UNIQUE KEY is used as a
partition key.

1. CREATE TABLE AgentDetail (


2. agent_id INT NOT NULL UNIQUE KEY,
3. agent_name VARCHAR(40)
4. )
5. PARTITION BY KEY()
6. PARTITIONS 2;

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:

1. CREATE TABLE Person (


2. id INT NOT NULL PRIMARY KEY,
3. name VARCHAR(40),
4. purchased DATE
5. )
6. PARTITION BY RANGE( YEAR(purchased) )
7. SUBPARTITION BY HASH( TO_DAYS(purchased) )
8. SUBPARTITIONS 2 (
9. PARTITION p0 VALUES LESS THAN (2015),
10. PARTITION p1 VALUES LESS THAN (2020),
11. PARTITION p2 VALUES LESS THAN MAXVALUE
12. );

Execute the below statement to verify the sub-partitioning:

1. SELECT PARTITION_NAME, TABLE_ROWS


2. FROM INFORMATION_SCHEMA.PARTITIONS
3. WHERE TABLE_SCHEMA = 'myemployeedb' AND TABLE_NAME = 'Person';

It will give the output as below:


SQL Server Synonym
An alias or alternative names can be given to any of the database objects like a table, view,
stored procedure, user-defined function, and sequence with the help of SQL Server Synonym.

Whenever we create a SQL Server Synonym in a database, the synonym is referenced to a


particular database object and that database object is called base object. The location of the
base object to which the synonym is referenced can be either in the same database or in some
other database in the same server or even on some other instance running on another server.

We can use SQL Server Synonym in various scenarios and take advantage out of them. Some of
the scenarios are:

o As there are 100's or sometimes 1000's of references in code to a particular object, so in


that case, we can assign a synonym to that object.
o An additional layer of abstraction can be added to the actual base object to which the
synonym is assigned.
o The database queries can easily refer to the objects that appear to reside in the current
database even though in reality they are present in some other database.
o Backward compatibility can also be provided to the old legacy base object that is needed
in the newer version of the database.
o An additional security layer for the protection of the base object can be provided with
the help of SQL Server Synonym.
o There are scenarios when we want to move to another database, with the help of SQL
Server Synonym we can refer to the base object without thinking about the migration.
o The lengthy and confusing object names of a database can be simplified with the help of
SQL Server Synonym.
o Various issues with the cross-database and server dependencies in downstream
environments such as development, test, and quality assurance as part of a continuous
integration build process can be easily eliminated with the use of the SQL Server
Synonym.

The syntax for creating a Synonym in SQL Server Database is:

1. CREATE SYNONYM [ name_of_schema. ] name_of_synonym


2. FOR name_of_base_object;

In the above-written syntax:

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.

How to use Synonym in SQL Server Database?

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:

1. CREATE DATABASE salesdb;


2.
3. USE salesdb;
As we can see in the image a database by the name of 'salesdb' has been created and selected
successfully.

Now, we will create a schema and a table inside that schema. The syntax for the creation of a
schema and a table is:

1. CREATE SCHEMA grocery;


2.
3. CREATE TABLE grocery.fruits(
4. fruit_name VARCHAR(100) NOT NULL,
5. quantity INT PRIMARY KEY IDENTITY
6. );

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:

1. CREATE SYNONYM fruits FOR salesdb.grocery.fruits;


The synonym named 'fruits' has been created successfully and now we can use it.

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

PL/SQL is a block of codes that used to write


SQL is a single query that is used to
the entire program blocks/ procedure/
perform DML and DDL operations.
function, etc.

It is declarative, that defines what needs to


PL/SQL is procedural that defines how the
be done, rather than how things need to be
things needs to be done.
done.

Execute as a single statement. Execute as a whole block.

Mainly used to manipulate data. Mainly used to create an application.

It is an extension of SQL, so it can contain


Cannot contain PL/SQL code in it.
SQL inside it.
Structure of PL/SQL Block:
PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a
structural language that is more powerful than SQL. The basic unit in PL/SQL is a block. All
PL/SQL programs are made up of blocks, which can be nested within each

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> SET SERVEROUTPUT ON;

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> SET SERVEROUTPUT ON;

SQL> DECLARE

var varchar2(40) := 'I love GeeksForGeeks' ;

BEGIN

dbms_output.put_line(var);

END;

1. Output:
I love GeeksForGeeks

PL/SQL procedure successfully completed.


1. Explanation:
 dbms_output.put_line : This command is used to direct the PL/SQL output to a screen.
2. Using Comments: Like in many other programming languages, in PL/SQL also, comments
can be put within the code which has no effect in the code. There are two syntaxes to create
comments in PL/SQL :
 Single Line Comment: To create a single line comment , the symbol – – is used.
 Multi Line Comment: To create comments that span over several lines, the
symbol /* and */ is used.
3. Taking input from user: Just like in other programming languages, in PL/SQL also, we can
take input from the user and store it in a variable. Let us see an example to show how to take
input from users in PL/SQL:
 C

SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a

a number := &a;

-- taking input for variable b

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> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a

a integer := &a ;

-- taking input for variable b

b integer := &b ;

c integer ;

BEGIN

c := a + b ;

dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);

END;
/

Enter value for a: 2


Enter value for b: 3

Sum of 2 and 3 is = 5

PL/SQL procedure successfully completed.


PL/SQL Execution Environment:
The PL/SQL engine resides in the Oracle engine.The Oracle engine can process not only single
SQL statement but also block of many statements.The call to Oracle engine needs to be made
only once to execute any number of SQL statements if these SQL statements are bundled inside a
PL/SQL block.

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:

Data Type Description

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.

2. Approximate Numeric Datatype :

The subtypes are given below:

Data type From To Description

float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value e.g. 6.2, 2.9 etc.

real -3.40e + 38 3.40E + 38 It specifies a single precision floating point number

3. Exact Numeric Datatype


The subtypes are given below:

Data type Description

int It is used to specify an integer value.

smallint It is used to specify small integer value.

bit It has the number of bits to store.

decimal It specifies a numeric value that can have a decimal number.

numeric It is used to specify a numeric value.

4. Character String Datatype

The subtypes are given below:

Data type Description

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

5. Date and time Datatypes

The subtypes are given below:

Datatype Description

date It is used to store the year, month, and days value.

time It is used to store the hour, minute, and second values.

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.

Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1. Data Definition Language (DDL)

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.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP
o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:

1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:

1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

1. DROP TABLE table_name;

Example

1. DROP TABLE EMPLOYEE;

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:

To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:

1. ALTER TABLE table_name MODIFY(column_definitions....);

EXAMPLE

1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));


2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the
table.

Syntax:

1. TRUNCATE TABLE table_name;

Example:

1. TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language

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.

Here are some commands that come under DML:

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:

1. INSERT INTO TABLE_NAME


2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);

Or

1. INSERT INTO TABLE_NAME


2. VALUES (value1, value2, value3, .... valueN);

For example:

1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");


b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITI


ON]

For example:

1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.

Syntax:

1. DELETE FROM table_name [WHERE condition];

For example:

1. DELETE FROM javatpoint


2. WHERE Author="Sonoo";

3. Data Control Language

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

b. Revoke: It is used to take back permissions from the user.

Example
1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language

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.

Here are some commands that come under TCL:

o COMMIT
o ROLLBACK
o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

1. COMMIT;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already been saved
to the database.

Syntax:

1. ROLLBACK;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. ROLLBACK;

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;

5. Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

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

You might also like