SQL II Topic

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

TOPIC NO- II

SQL Intro: What is SQL?


What is SQL? SQL stands for “Structured Query Language” and can be pronounced
as “SQL” or “sequel – (Structured English Query Language)”. Defined, SQL is a
query language used for accessing and modifying information in one or more data
tables and rows of a database.

SQL Database Design


IBM first developed SQL in 1970s. Also it is an ANSI/ISO standard. It has become a
Standard Universal Language used by most of the relational database management
systems (RDBMS). Some of the RDBMS systems are: Oracle, Microsoft SQL server,
Sybase etc.

Most of these have provided their own implementation extensions, thus enhancing
their RDBMS system features and making it a powerful tool. These RDBMS
systems, all use the popular SQL commands SELECT, UPDATE, DELETE, INSERT,
WHERE in similar format.

SQL Database Table


SQL database is constructed of a number of tables. In a business, SQL tables would
be used to divide and simplify the different areas of the operation: Table for
Customers, one for Vendors, Employees and so on.

SQL Database Table Columns


Each SQL table is made up of a number of columns, referred to as fields and run
along the top of the table. Sql columns or fields have their content
(object/data/info) defined into character types; such as text, date, numeric,
integer, length to name a few.

SQL Database Table Rows


Each SQL table row, referred to a record, is located in the left column of the table.
Sql record row will contain a string of data containing data matching up to each
column field across the top. So, in a "Customer table" each "customer record"
would consist of one row with data for the customer ID number, customer name,
address, phone ...email and so on.
SQL Commands:
Few of the Sql commands used in Sql code programming are: SELECT
Statement, UPDATE Statement, INSERT INTO Statement, DELETE
Statement, WHERE Clause, ORDER BY Clause, SQL GROUP BY
Clause, Subquery Clauses, Joins, Views,GROUP Functions, Indexes etc.

DDL Commands –
Create - Drop - Alter - Rename - Truncate

The Create Table Command


The create table command defines each column of the table uniquely. Each column has
minimum of three attributes.

 Name
 Data type
 Size(column width).

Each table column definition is a single clause in the create table syntax. Each table column
definition is separated from the other by a comma. Finally, the SQL statement is terminated
with a semicolon.

The Structure of Create Table Command

Table name is Student


Column name Data type Size
Reg_no varchar2 10
Name char 30
DOB date
Address varchar2 50
Example:

CREATE TABLE Student


(Reg_no varchar2(10),
Name char(30),
DOB date,
Address varchar2(50));

The DROP Command

Syntax:
DROP TABLE <table_name>

Example:
DROP TABLE Student;
It will destroy the table and all data which will be recorded in it.

The TRUNCATE Command

Syntax:
TRUNCATE TABLE <Table_name>

Example:
TRUNCATE TABLE Student;

The RENAME Command

Syntax:
RENAME <OldTableName> TO <NewTableName>

Example:
RENAME <Student> TO <Stu>

The old name table was Student now new name is the Stu.
The ALTER Table Command

By The use of ALTER TABLE Command we can modify our exiting table.

Adding New Columns

Syntax:
ALTER TABLE <table_name>
ADD (<NewColumnName> <Data_Type>(<size>),......n)

Example:
ALTER TABLE Student ADD (Age number(2), Marks number(3));

The Student table is already exist and then we added two more
columns Age and Marks respectively, by the use of above command.

Dropping a Column from the Table

Syntax:
ALTER TABLE <table_name> DROP COLUMN <column_name>

Example:
ALTER TABLE Student DROP COLUMN Age;

This command will drop particular column

Modifying Existing Table

Syntax:
ALTER TABLE <table_name> MODIFY (<column_name> <NewDataType>(<NewSize>))

Example:
ALTER TABLE Student MODIFY (Name Varchar2(40));

The Name column already exist in Student table, it was char and size 30, now it is modified by
Varchar2 and size 40.

Restriction on the ALTER TABLE


Using the ALTER TABLE clause the following tasks cannot be performed.

 Change the name of the table


 Change the name of the column
 Decrease the size of a column if table data exists

-------------------------------------------------------------------------------------
DML Commands –
Select - Insert - Update - Delete

Viewing Data in the Table (Select Command)

Once data has been inserted into a table, the next most logical operation would
be to view what has been inserted. The SELECT SQL verb is used to achieve this.

All Rows and All Columns

Syntax: SELECT * FROM Table_name;

eg: Select * from Student; It will show all the table records.

More than one are there to Insert data into a table

eg: INSERT INTO student (reg_no, first_name, last_name, dob,address, pincode)

VALUES('A101', 'Mohd', 'Imran', '01-MAR-89','Allahabad', 211001);

eg : INSERT INTO student VALUES('A101', 'Mohd', 'Imran', '01-MAR-89','Allahabad',


211001);

Note : Character expression placed within the insert into statement must be
enclosed in single quotes (').
DELETE Operation:
The DELETE command can remove all the rows from the table or a set of rows from the table.

eg: DELETE FROM student; It will DELETE all the rows from student table.

eg: DELETE FROM student WHERE reg_no='A101'; If condition will be satisfied then it will delete
a row from the table Register number A101 will be deleted from the table

If you want to delete table column then use ALTER TABLE command.

eg : ALTER TABLE student DROP COLUMN dob; The DOB column will be
deleted from the student table.

UPDATE Operation:
The UPDATE command is used to change or modify data values in a table and UPDATE
command can Update all the rows from the table or a set of rows from the table.

eg : UPDATE Student SET course='MCA';

Course is a column name, suppose ant time you want to update something like that in
the student table course should be MCA for all students then you can use this type of
query. It will update all the rows in the table all rows will have MCA course.

Now, if you want update particular row then see below.

UPDATE Student SET course='MCA' where reg_no='A101'; it will update only


one row that will have Register no. A101.

you can use different-different types of condition in WHERE clause, eg salary updation, if salary has
increased someone's then simply multiply, addition you can do in salary column.

I will show example. Suppose someone's has increased salary by 10% then what should to do. See
example:

UPDATE employee SET salary= salary+salary*0.1 WHERE employee_id='E101'; Salary will


be automatically increased by 10% of salary.
SQL WHERE Clause
The WHERE Clause is used when you want to retrieve specific information from a
table excluding other irrelevant data. For example, when you want to see the
information about students in class 10th only then you do need the information
about the students in other class. Retrieving information about all the students
would increase the processing time for the query.

So SQL offers a feature called WHERE clause, which we can use to restrict the data
that is retrieved. The condition you provide in the WHERE clause filters the rows
retrieved from the table and gives you only those rows which you expected to see.
WHERE clause can be used along with SELECT, DELETE, UPDATE statements.

Syntax of SQL WHERE Clause


WHERE {column or expression} comparison-operator value

Syntax for a WHERE clause with Select statement is:

SELECT column_list FROM table-name


WHERE condition;

 column or expression - Is the column of a table or a expression


 comparison-operator - operators like = < > etc.
 value - Any user value or a column name for comparison

SELECT first_name, last_name FROM student_details


WHERE id = 100;
SQL ORDER BY
The ORDER BY clause is used in a SELECT statement to sort results either in
ascending or descending order. Oracle sorts query results in ascending order by
default.

Syntax for using SQL ORDER BY clause to sort data is:


SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];

database table "employee";

id name dept age salary location


100 Ramesh Electrical 24 25000 Bangalore
101 Hrithik Electronics 28 35000 Bangalore
102 Harsha Aeronautics 28 35000 Mysore
103 Soumya Electronics 22 20000 Bangalore
104 Priya InfoTech 25 30000 Mangalore

For Example: If you want to sort the employee table by salary of the employee,
the sql query would be.
SELECT name, salary FROM employee ORDER BY salary;

The output would be like


name salary
---------- ----------
Soumya 20000
Ramesh 25000
Priya 30000
Hrithik 35000
Harsha 35000

The query first sorts the result according to name and then displays it.
You can also use more than one column in the ORDER BY clause.

By default, the ORDER BY Clause sorts data in ascending order. If you want to sort
the data in descending order, you must explicitly specify it as shown below.

SELECT name, salary

FROM employee

ORDER BY name, salary DESC;

The above query sorts only the column 'salary' in descending order and the column
'name' by ascending order.

If you want to select both name and salary in descending order, the query would be
as given below.

SELECT name, salary

FROM employee

ORDER BY name DESC, salary DESC;

SQL Integrity Constraints


Integrity Constraints are used to apply business rules for the database tables.

The constraints available in SQL are Foreign Key,Not Null, Unique, Check.
Constraints can be defined in two ways
1) The constraints can be specified immediately after the column definition. This is
called column-level definition.
2) The constraints can be specified after all the columns are defined. This is called
table-level definition.
1) SQL Primary key:
This constraint defines a column or combination of columns which uniquely
identifies each row in the table.

Syntax to define a Primary key at column level:


column name datatype [CONSTRAINT constraint_name] PRIMARY KEY

Syntax to define a Primary key at table level:


[CONSTRAINT constraint_name] PRIMARY KEY

(column_name1,column_name2,..)

 column_name1, column_name2 are the names of the columns which define


the primary Key.
 The syntax within the bracket i.e. [CONSTRAINT constraint_name] is optional.
For Example: To create an employee table with Primary Key constraint, the query
would be like.
Primary Key at column level:
CREATE TABLE employee

( id number(5) PRIMARY KEY,

name char(20),

dept char(10),

age number(2),

salary number(10),

location char(10)

);

2) SQL Foreign key or Referential Integrity :


This constraint identifies any column referencing the PRIMARY KEY in another table.
It establishes a relationship between two columns in the same table or between
different tables. For a column to be defined as a Foreign Key, it should be a defined
as a Primary Key in the table which it is referring. One or more columns can be
defined as Foreign key.
Syntax to define a Foreign key at column level:
[CONSTRAINT constraint_name] REFERENCES

Referenced_Table_name(column_name)

Syntax to define a Foreign key at table level:


[CONSTRAINT constraint_name] FOREIGN KEY(column_name)

REFERENCES referenced_table_name(column_name);

For Example:
1) Lets use the "product" table and "order_items".

Foreign Key at table level:


CREATE TABLE order_items

( order_id number(5) ,

product_id number(5),

product_name char(20),

supplier_name char(20),

unit_price number(10)

CONSTRAINT od_id_pk PRIMARY KEY(order_id),

CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES

product(product_id)

);

4) SQL Unique Key:


This constraint ensures that a column or a group of columns in each row have a
distinct value. A column(s) can have a null value but the values cannot be
duplicated.
Syntax to define a Unique key at table level:
[CONSTRAINT constraint_name] UNIQUE(column_name)

Unique Key at table level:


CREATE TABLE employee

( id number(5) PRIMARY KEY,

name char(20),

dept char(10),

age number(2),

salary number(10),

location char(10),

CONSTRAINT loc_un UNIQUE(location)

);

5) SQL Check Constraint :


This constraint defines a business rule on a column. All the rows must satisfy this
rule. The constraint can be applied for a single column or a group of columns.

Syntax to define a Check constraint:


[CONSTRAINT constraint_name] CHECK (condition)

Check Constraint at table level:


CREATE TABLE employee

( id number(5) PRIMARY KEY,

name char(20),

dept char(10),

age number(2),

gender char(1),

salary number(10),
location char(10),

CONSTRAINT gender_ck CHECK (gender in ('M','F'))

);

SQL Subquery
Subquery or Inner query or Nested query is a query in a query. SQL subquery
is usually added in the WHERE Clause of the SQL statement. Most of the time, a
subquery is used when you know how to search for a value using a SELECT
statement, but do not know the exact value in the database.
Subqueries are an alternate way of returning data from multiple tables.

Subqueries can be used with the following SQL statements along with the
comparision operators like =, <, >, >=, <= etc.

 SELECT
 INSERT
 UPDATE
 DELETE

Subquery output would be similar to:

first_name last_name subject


------------- ------------- ----------
Shekar Gowda Badminton
Priya Chandra Chess

Join in SQL
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of
data. SQL Join is used for combining column from two or more tables by using values common to
both tables. JoinKeyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is(n-1) where n, is number of tables. A table can also join to itself known
as, Self Join.

Types of Join

The following are the types of JOIN that we can use in SQL.
 Inner

 Outer

 Left

 Right

Cross JOIN or Cartesian Product

This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a table
which consists of records which combines each row from the first table with each row of the second
table.

Cross JOIN Syntax is,

SELECT column-name-list

from table-name1

CROSS JOIN

table-name2;

Example of Cross JOIN

The class table,

ID NAME

1 abhi

2 adam

4 alex
The class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Cross JOIN query will be,

SELECT *

from class,

cross JOIN class_info;

The result table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 1 DELHI

4 alex 1 DELHI

1 abhi 2 MUMBAI

2 adam 2 MUMBAI

4 alex 2 MUMBAI

1 abhi 3 CHENNAI
2 adam 3 CHENNAI

4 alex 3 CHENNAI

INNER Join or EQUI Join

This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the query.

Inner Join Syntax is,

SELECT column-name-list

from table-name1

INNER JOIN

table-name2

WHERE table-name1.column-name = table-name2.column-name;

Example of Inner JOIN

The class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

The class_info table,


ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Inner JOIN query will be,

SELECT * from class, class_info where class.id = class_info.id;

The result table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

Outer JOIN

Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,

 Left Outer Join

 Right Outer Join

 Full Outer Join

Left Outer Join

The left outer join returns a result table with the matched data of two tables then remaining rows of
the lefttable and null for the right table's column.
Left Outer Join syntax is,

SELECT column-name-list

from table-name1

LEFT OUTER JOIN

table-name2

on table-name1.column-name = table-name2.column-name;

Left outer Join Syntax for Oracle is,

select column-name-list

from table-name1,

table-name2

on table-name1.column-name = table-name2.column-name(+);

Example of Left Outer Join

The class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

The class_info table,

ID Address
1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Left Outer Join query will be,

SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id=class_info.id);

The result table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

5 ashish null null

Right Outer Join

The right outer join returns a result table with the matched data of two tables then remaining rows of
the right table and null for the left table's columns.
Right Outer Join Syntax is,

select column-name-list

from table-name1

RIGHT OUTER JOIN

table-name2

on table-name1.column-name = table-name2.column-name;

Right outer Join Syntax for Oracle is,

select column-name-list

from table-name1,

table-name2

on table-name1.column-name(+) = table-name2.column-name;

Example of Right Outer Join

The class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

The class_info table,

ID Address
1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Right Outer Join query will be,

SELECT * FROM class RIGHT OUTER JOIN class_info on (class.id=class_info.id);

The result table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

null null 7 NOIDA

null null 8 PANIPAT

Full Outer Join

The full outer join returns a result table with the matched data of two table then remaining rows of
both lefttable and then the right table.
Full Outer Join Syntax is,

select column-name-list

from table-name1

FULL OUTER JOIN

table-name2

on table-name1.column-name = table-name2.column-name;

Example of Full outer join is,

The class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

The class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA
8 PANIPAT

Full Outer Join query will be like,

SELECT * FROM class FULL OUTER JOIN class_info on (class.id=class_info.id);

The result table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

5 ashish null null

null null 7 NOIDA

null null 8 PANIPAT

SQL Views
A VIEW is a virtual table, through which a selective portion of the data from one or
more tables can be seen. Views do not contain data of their own. They are used to
restrict access to the database or to hide data complexity. A view is stored as a
SELECT statement in the database. DML operations on a view like INSERT,
UPDATE, DELETE affects the data in the original table upon which the view is
based.

The Syntax to create a sql view is


CREATE VIEW view_name

AS

SELECT column_list

FROM table_name [WHERE condition];

 view_name is the name of the VIEW.


 The SELECT statement is used to define the columns and rows that you want to
display in the view.
For Example: to create a view on the product table the sql query would be like
CREATE VIEW view_product
AS
SELECT product_id, product_name
FROM product;
Index
Indexes are special lookup tables that the database search engine can use
to speed up data retrieval. Simply put, an index is a pointer to data in a
table. An index in a database is very similar to an index in the back of a
book.

For example, if you want to reference all pages in a book that discuss a
certain topic, you first refer to the index, which lists all topics alphabetically
and are then referred to one or more specific page numbers.

An index helps speed up SELECT queries and WHERE clauses, but it slows
down data input, with UPDATE and INSERT statements. Indexes can be
created or dropped with no effect on the data.

Creating an index involves the CREATE INDEX statement, which allows you
to name the index, to specify the table and which column or columns to
index, and to indicate whether the index is in ascending or descending
order.

Indexes can also be unique, similar to the UNIQUE constraint, in that the
index prevents duplicate entries in the column or combination of columns
on which there's an index.

The CREATE INDEX Command:


The basic syntax of CREATE INDEX is as follows:

CREATE INDEX index_name ON table_name;

Single-Column Indexes:
A single-column index is one that is created based on only one table
column. The basic syntax is as follows:

CREATE INDEX index_name


ON table_name (column_name);
Unique Indexes :
Unique indexes are used not only for performance, but also for data
integrity. A unique index does not allow any duplicate values to be inserted
into the table. The basic syntax is as follows:

CREATE UNIQUE INDEX index_name


on table_name (column_name);

Composite Indexes:
A composite index is an index on two or more columns of a table. The basic
syntax is as follows:

CREATE INDEX index_name


on table_name (column1, column2);
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. AUTO_INCREMENT is
applied on columns, it automatically increments the column value by 1 each time a new record is entered
into the table. Sequence is also some what similar to AUTO_INCREMENT but its has some extra
features.

Creating Sequence

Syntax to create sequences is,

CREATE Sequence sequence-name

start with initial-value

increment by increment-value

maxvalue maximum-value

cycle|nocycle

initial-value specifies the starting value of the Sequence, increment-value is the value by which sequence
will be incremented and maxvalue specifies the maximum value until which sequence will increment
itself.cycle specifies that if the maximum value exceeds the set limit, sequence will restart its cycle from
the begining.No cycle specifies that if sequence exceeds maxvalue an error will be thrown.

Example to create Sequence

The sequence query is following

CREATE Sequence seq_1


start with 1
increment by 1
maxvalue 999

cycle ;
What is PL/SQL?
PL/SQL stands for Procedural Language extension of SQL.
PL/SQL is a combination of SQL along with the procedural features of programming
languages.
It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of
SQL.

The PL/SQL Engine:

Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL language
code can be stored in the client system (client-side) or in the database (server-side)
.

A Simple PL/SQL Block:


Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block.

PL/SQL Block consists of three sections:


 The Declaration section (optional).
 The Execution section (mandatory).
 The Exception Handling (or Error) section (optional).

Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.
This section is optional and is used to declare any placeholders like variables, constants,
records and cursors, which are used to manipulate data in the execution section.
Placeholders may be any of Variables, Constants and Records, which stores data
temporarily. Cursors are also declared in this section.

Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends
with END. This is a mandatory section and is the section where the program logic is
written to perform any task. The programmatic constructs like loops, conditional
statement and SQL statements form the part of execution section.

Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION.
This section is optional. Any errors in the program can be handled in this section, so that
the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that
cannot be handled, the Block terminates abruptly with errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks
can be nested within other PL/SQL blocks. Comments can be used to document code.

How a Sample PL/SQL Block Looks

DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
 Learning PL/SQL
Advantages of PL/SQL
These are the Advantages of PL/SQL

 Block Structures: PL SQL consists of blocks of code, which can be nested within each
other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be
stored in the database and reused.

 Procedural Language Capability: PL SQL consists of procedural language constructs
such as conditional statements (if else statements) and loops like (FOR loops).

 Better Performance: PL SQL engine processes multiple SQL statements
simultaneously as a single block, thereby reducing network traffic.

 Error Handling: PL/SQL handles errors or exceptions effectively during the


execution of a PL/SQL program. Once an exception is caught, specific actions can
be taken depending upon the type of the exception or it can be displayed to the
user with a message.

Difference Between SQL and PL/SQL


SQL PL/SQL
SQL is a Structured Query PL-SQL is a programming language
Language used to issue a single SQL, used to write full
query or execute a single programs using variables,
insert/update/delete. loops,operators etc. to carry
out multiple
selects/inserts/updates/deletes
.
PL/SQL can be considered as the
SQL may be considered as the application language similar
source of data for our to Java or PHP. It might be
reports, web pages and the language used to build,
screens. format and display those
reports, web pages and screens.
SQL is a data oriented PL/SQL is a procedural language
language used to select and used to create applications.
manipulate sets of data.
SQL is used to write PL/SQL is used to write program
queries, DDL and DML statements blocks, functions, procedures
. triggers,and packages.

PL/SQL is executed as a block


SQL is executed one statement of code.
at a time.
SQL is declarative, i.e., it Whereas, PL/SQL is procedural,
tells the database what to do i.e., it tells the database how
but not how to do it. to do things.
SQL can be embedded within a But PL/SQL can’t be embedded
PL/SQL program. within a SQL statement.

DATA TYPES IN PL SQL

Scalar types
Scalar data type haven't internal components. It is like a linear data type. Scales data
type divides into four different types character, numeric, boolean or date/time type.

Numeric Data types


Following are numeric data types in PL/SQL:

Data types Description, Storage(Maximum)

NUMBER data type used to store numeric data.


It's contain letters, numbers, and special characters.
Storage Range : Precision range(p) : 1 to 38 and Scale range(s) : -84 to
127
NUMBER Subtypes : This sub type defines different types storage range.

Sub Data types Maximum Precision Description

INTEGER 38 digits

INT 38 digits

NUMBER(p,s) SMALLINT 38 digits

DEC 38 digits
This data types are used to
store fixed decimal points. You
DECIMAL 38 digits
can use based on your
requirements.
NUMERIC 38 digits

REAL 63 binary digits

DOUBLE PRECISION 126 binary digits

FLOAT 126 binary digits

BINARY_INTEGE BINARY_INTEGER data type store signed integer's value.


R Note : BINARY_INTEGER values require less storage space compare of
NUMBER data type values.
Storage Range : from -2147483647 to 2147483647
BINARY_INTEGER Subtypes : This sub type define constraint to store a
value.

Sub Data types Description


NATURAL
NATURAL/POSITIVE data type prevent to store
negative value, allow only positive values.
POSITIVE

NATURALN
NATURALN/POSITIVEN data type prevent to assign
a NULL value.
POSITIVEN

SIGNTYPE SIGNTYPE allow only -1, 0, and 1 values.

PLS_INTEGER data type used to store signed integers data.


Note : PLS_INTEGER data type value require less storage space compare
of NUMBER data type value.
PLS_INTEGER Storage Range : from -2147483647 to 2147483647
Performance : PLS_INTEGER data type give you better performance on
your data. PLS_INTEGER perform arithmetic operation fast than
NUMBER/BINARY_INTEGER data type.

Character Data types


Character Data types used to store alphabetic/alphanumeric character. Following are
some character data types in PL/SQL,

Storage(Maximum
Data types Description
)

CHAR data type used to store character data within


CHAR 32767 bytes
predefined length.

CHARACTER data type same as CHAR type, is this


CHARACTER 32767 bytes
another name of CHAR type.

VARCHAR2 VARCHAR2 data type used to store variable strings data 32767 bytes
within predefined length.
VARCHAR2 Subtypes : Following sub type defines
same length value.
Sub Data types Description

STRING
We can access this data type.
VARCHAR

NCHAR data type used to store national character data


NCHAR 32767 bytes
within predefined length.

NVARCHAR2 data type used to store Unicode string


NVARCHAR2 32767 bytes
data within predefined length.

The RAW data type used to store binary data such as


RAW 32767 bytes
images, graphics etc.

LONG data type used to store variable string data within


LONG predefined length, This data type used for backward 32760 bytes
compatibility. Please use LONG data to the CLOB type.

LONG RAW data type same as LONG type used to


store variable string data within predefined length, This
LONG RAW 32760 bytes
data type used for backward compatibility.
Use LONG RAW data type for storing BLOB type data.

The ROWID data type represents the actual storage address of a row. And
ROWID table index identities as a logical rowid. This data type used to storing
backward compatibility. We strongly recommended to use UROWID data type.

The UROWID data type identifies as universal rowid,


same as ROWID data type. Use UROWID data type for
UROWID[(size)
developing newer applications. 4000 bytes
]
Optional, You can also specify the size of UROWID
column type.

Boolean Data types


Boolean Data types stores logical values either TRUE or FALSE. Let's see Boolean data
types in PL/SQL:
Data types Description

Boolean data type stores logical values. Boolean data types doesn't take
any parameters.
Boolean Boolean data type store either TRUE or FALSE. Also store NULL, Oracle
treats NULL as an unassigned boolean variable.
You can not fetch boolean column value from another table.

Date/Time Data types


Date/time variable can holds value, we can say date/time data type. PL/SQL
automatically converts character value in to default date format ('DD-MM-YY') value.
Following are the Date/Time data types in PL/SQL:

Data types Description Range

Jan 1, 4712 BC
DATE data type stores valid date-time format with fixed length. to
DATE
Starting date from Jan 1, 4712 BC to Dec 31, 9999 AD. Dec 31, 9999
AD

TIMESTAMP data type stores valid date (year, month, day) with time (hour,
minute, second).

Type TIMESTAMP Type


TIMESTAM
Syntax : TIMESTAMP [(fractional_seconds_precision)]
P
Example : TIMESTAMP '2014-04-13 18:10:52.124'
1 fractional_seconds_precision optionally specifies the number of digits in
the fractional part of the second precision. Range from 0 to 9. The default is
6.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy