You are on page 1of 53

Data Types

By: Prakhar Jha

SQL PLUS
CHAR(size) Actual Defined Stored As
- used to store fixed length string. Data As
-max size 255 character.
123456.78 NUMBER( 1234.79
9 6,2)
VARCHAR2(size)
-used to store variable length string . 123456.78 NUMBER( 123457
-it can store letter, number and 9 6)
punctuation marks.
-max size 4000 character.
123456.78 NUMBER( 123500
VARCHAR(size) 9 6,-2)
-same as CHAR(size),but speed is less.
-it is also used for storing string of variable
123456.78 NUMBER 123456.78
length.
9 9
NUMBER(precision , scale)
-precision total no of digits that can be
stored.
-scale total no of digits after decimal.

e.g. : NUMBER(4) or NUMBER(4,2) or


NUMBER.
DATE Object Type

LONG BLOB
-used to store variable length text, (Binary Large Object)
of very large size -this is used for storing binary data
-max size 2GB. of very large size.
-data stored like images and videos.
Binary Types -max size 4GB

CLOB
RAW(size)
(Character Large Object)
-used to store binary digit of max
-this data type is used to store very
size 255 bytes.
large character object.
LONG RAW
-data stored like text document.
-in this data type, it is possible to
-max size 4GB.
store binary data upto 2GB

*In one table, more than one lob type


data type can be stored.
Commands

SQL PLUS
CREATE AND INSERT
(basic)
CREATE TABLE <table_name>(<column_name>
<data_type>, <column_name> <data_type>,
<column_name> <data_type>);

DESC <table_name>;

INSERT INTO <table_name> VALUES (<value>, <value> ,


<value>);

INSERT INTO <table_name> VALUES (&<value>,


&<value>, &<value>);
SELECT and UPDATE and DELETE
SELECT * FROM <table_name>;
SELECT <column_name>,<column_name> FROM
<table_name>;
SELECT * FROM <table_name> WHERE <column_name> =
<value>;

UPDATE <table_name> SET <column_name> = <value>;


UPDATE <table_name> SET <column_name>=<value>
WHERE <condition>;

DELETE FROM <table_name>;


DELETE FROM <table_name> WHERE <condition>;
ALTER and DROP

ALTER TABLE <table_name> ADD (<column_name>


<data_type>(size));
ALTER TABLE <table_name> DROP COLUMN
<column_name>;
ALTER TABLE <table_name> MODIFY(<column_name>
<data_type>(size));

DROP TABLE <table_name>;


DISTINCT and ORDER BY
SELECT DISTINCT <column_name> FROM <table_name>;
SELECT DISTINCT * FROM <table_name>;

SELECT * FROM <table_name> ORDER BY


<column_name>;
SELECT * FROM <table_name> ORDER BY
<column_name> DESC;
CREATE and INSERT using
previous table.
CREATE TABLE <table_name a> (<column_name a>, <column_name
a>,) AS SELECT <column_name b>, <column_name b>, FROM
<table_name b>;

CREATE TABLE <table_name a> (<column_name a>, <column_name


a>,) AS SELECT <column_name b>, <column_name b>, FROM
<table_name b> WHERE <any_false_condition>;

The above query will create a new table same as <table_name b> but with no
records. This is because the condition can never be fulfilled.

INSERT INTO <table_name b> SELECT <column_name>,


<column_name>, FROM <table_name a>;

INSERT INTO <table_name b> SELECT <column_name a>,


<column_name a>, FROM <table_name a> WHERE <condition>;
RENAME & VIEW TABLES
RENAME <table_name a> TO <table_nameb>;

SELECT * FROM TAB;


Data Constraints

SQL PLUS
PRIMARY KEY and COMPOSITE
KEY
To identify each row uniquely in a table in RDBMS, the concept of primary key is developed.

If it is not possible to identify data uniquely based on single column, PRIMARY KEY is
applied on multiple column and that thing is known as COMPOSITE KEY.

It is applied on a particular column.

CREATE TABLE <table_name> (<column_1> <data_type>(size) PRIMARY KEY,


<column_2> <data_type>(size), <column_3> <data_type> (size));

Column 1 has PRIMARY KEY CONSTRAINT.

CREATE TABLE <table_name> (<col_1> <data_type>(size), <col_2>


<data_type>(size), <col_3> <data_type>(size) , PRIMARY KEY (col_1,col_2,col_3));

col_1,col_2,col_3 together have PRIMARY KEY CONSTRAINT on them.


AUTO INCREMENT

-to set auto increment in oracle. We have to create SEQUENCE

CREATE SEQUENCE <name>


MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;

-now when we insert a value to a primary key column, we will use this
sequence object to insert our new values.

INSERT INTO <table_name> (<column_name>, <column_name>,


<column_name>) values(<name>.nextval, <value>, <value>);

-<name>.nextval will return the next number in SEQUENCE.


FOREIGN KEY
<table_name a> - Detail Table or Foreign Table.
-when a table is created and FK is described in it, that table is known as Detail Table to the table
where this FK is PK to that table.
<table_name b> - Master Table or Primary Table.
-the actual table whose PK is being described in other table as FK.

CREATE TABLE <table_name a> (


<col_1> <data_type>(size) PRIMARY KEY,
<col_2> <data_type>(size) REFERENCES <table_name b> [(<column_name>)],
<col_3> <data_type>(size) ) ;

-oracle automatically associates <table_name b>s PK to <col_2> and described <col_2> as FK, if
we dont mention <column_name> after REFERENCE <table_name> .

CREATE TABLE <table_name a>(


<col_1> <data_type>(size) PRIMARY KEY,
<col_2> <data_type>(size)
CONSTRAINT <constraint_name> FOREIGN KEY(col_2)
REFERENCES <table_name b>(<column_name>)
);
[CONSTRAINT [symbol]] FOREIGN KEY [index_name]
(index_col_name, ...) REFERENCES tbl_name
(index_col_name,...) [ON DELETE reference_option] [ON UPDATE
reference_option]

-reference_option: RESTRICT | CASCADE | SET NULL | NO


ACTION
CREATE TABLE <table_name a> (<col_1> <data_type>(size) PRIMARY KEY,
<col_2> <data_type>(size), <col_3> <data_type>(size), FOREIGN KEY(col_2)
REFERENCES <table_name b>(<column_name>) );

CREATE TABLE <table_name a> (<col_1> <data_type>(size) PRIMARY KEY,


<col_2> <data_type>(size), <col_3> <data_type>(size), FOREIGN KEY(col_2)
REFERENCES <table_name b>(<column_name>) ) ON DELETE CASCADE;

- ON DELETE CASCADE will delete the associated record from <table_name


a> if any record is deleted in the Master Table or <table_name b>.

CREATE TABLE <table_name a> (<col_1> <data_type>(size) PRIMARY KEY,


<col_2> <data_type>(size), <col_3> <data_type>(size), FOREIGN KEY(col_2)
REFERENCES <table_name b>(<column_name>) ) ON DELETE SET NULL;

- ON DELETE SET NULL will set NULL in <table_name a> at the places
where the record is associated to the Master Table or <table_name b>, if the
record is deleted from master table.
UNIQUE KEY
- UK constraint is similar to PK.
-if we apply UK constraint on any column that column can store NULL values in
them, this thing is not possible with PK contraint.
-a column with UK constraint on it can have multiple NULL value, but when there
is actual value stored, no two values can be similar.

CREATE TABLE <table_name> (


<col 1> <data_type> UNIQUE ,
<col 2> <data_type>,
<col 3> <data_type> );

CREATE TABLE <table_name> (


<col 1> <data_type> ,
<col 2> <data_type>,
<col 3> <data_type> ,
UNIQUE(col 1));
Business Rule Constraint i.e.
CHECK Constraint
CREATE TABLE <table_name> (
<col 1> <data_type>(size),
<col 2> <data_type>(size),
<col 3> <data_type>(size) CHECK(<col 3> == 2000),
CHECK(<col 1> LIKE E%)
);

-in the above query the CHECK constraint is applied on <col 1> & <col 3>
- in <col 1>, it will check if the value which is being inserted, starts from E or
not.
- in <col 3>, it will check if the value which is being inserted, equals to 2000
or not.

Syntax :

CHECK(<logical_expression>)
Defining Integrity Constraints by
ALTER command
ALTER TABLE <table_name a> ADD FOREIGN
KEY(<col_name>) REFERENCES <table_name
b>(<col_name>);

ALTER TABLE <table_name> ADD PRIMARY


KEY(<col_name>);

ALTER TABLE <table_name> DROP PRIMARY KEY;


NOT NULL and DEFAULT
CREATE TABLE <table_name>(
<col 1> <data_type>(size) PRIMARY KEY,
<col 2> <data_type>(size) NOT NULL
);

-the insert query wont execute, if there is no data for <col 2>.

CREATE TABLE <table_name>(


<col 1> <data_type>(size) PRIMARY KEY,
<col 2> <data_type>(size) DEFAULT <value>
);

-if value is string, wrap it in single quotes.


-if number no need to wrap it.
USER_CONTRAINTS table
DESC USER_CONSTRAINTS;

SELECT <column_name> FROM


USER_CONSTRAINTS WHERE
TABLE_NAME =<table_name> ;
Data Manipulation In SQL

SQL PLUS
Operators
< : Is less than

> : Is greater than


+ : Addition
<= : Is less than or equal to
- : Subtraction
>= : Is greater than or equal to

* : Multiplication = : Is equal to

/ : Division != : is NOT equal to


Arithmetic Comparison
Logical Operators

AND : Logical AND Operator.

OR : Logical OR Operator.

NOT : Logical NOT Operator.

examples:

AND
SELECT * FROM EMPLOYEES WHERE
SALARY > 10000 AND SALARY < 25000;

OR
SELECT * FROM SUBJECTS WHERE
NAME = java AND NAME < oracle ;

NOT
SELECT * FROM EMPLOYEE WHERE
NOT(SALARY > 25000)
Using AND and OR
together
SELECT * FROM EMPLOYEE
WHERE
salary > 25000 AND ( designation= mngr OR designation=
sec );
Range Searching
SELECT * FROM <table_name>
WHERE <col_name> BETWEEN <value 1> AND <value
2> ;

- in the output, the tuple(row) with <value 1> and <value 2> will
be included.
Pattern Matching
SELECT * FROM <table_name> WHERE
SELECT * FROM <table_name> <col_name> IN (<value>);
WHERE <col_name> LIKE
E%; - the braces after IN can hold multiple value
each of which is separated by comma.
SELECT * FROM <table_name> - the output will contain all records(rows)
WHERE <col_name> LIKE where the values of <col_name> matches
%E; to <value>.

Assume <col_name> = name


SELECT * FROM <table_name>
- when the above query is executed the WHERE <col_name> NOT IN (<value>);
output will show all the records whose
name are starting with the letter E or -the exact opposite of above query will
ending with letter E in the second query. happen in this query.

LIKE Predicate IN and NOT IN Predicate


Renaming Columns and
Tables
SELECT last_name AS FAMILY,
first_name FROM persons;

-output

FAMILY FIRST_NAME
Jha prakhar
Soni rohit
Yadav ankit
Patel sachin SELECT * FROM
<table_name> <table
_alias> ;
Column Alias Table Alias
DUAL Table in Oracle
-we use SELECT command to retrieve output from a table, and it is
compulsory to write a table name with it. But some time when we need
to perform any Arithmetic Calculation or use some Function, at that
point of time we cannot use any table name because it will return
unexpected results, and using SELECT without table name is
incomplete.
For this purpose we use DUAL table.

DESC DUAL;
SELECT * FROM DUAL;
SELECT 2+2 FROM DUAL; output : 4
SELECT 2*3 FROM DUAL; output: 6

SYSDATE:
SELECT SYSDATE FROM DUAL; output: current date of your system
Oracle Functions

SQL PLUS
Group Function and Scalar
Functions

-function that works on a set of values are known


as Group Functions or Aggregate Functions,
when we apply any function on a table's
column, it generate output according to all the
values that is selected by the executed query.

-function that works on single value are known


as scalar functions, they are also known as
single row function .
Group Functions
SELECT AVG(marks) AS Average Marks FROM STUDENTS ;

SELECT COUNT(*) AS No Of Rows FROM STUDENTS ;


SELECT COUNT(name) AS No Of Rows FROM STUDENTS ;

SELECT MAX(marks) AS Maximum Marks FROM STUDENTS;

SELECT MIN(marks) AS Minimum Marks FROM STUDENTS;

SELECT SUM(marks) AS Sum Of Marks FROM STUDENTS:

- in above example marks & name are column in table STUDENTS .


- * used above can be replaced by column names as well.
Scalar Function
Numeric Function

SELECT ABS(-24) FROM DUAL; output: 24

SELECT POWER(5,2) FROM DUAL; output: 5*5 = 25

SELECT ROUND(16.966, 1) FROM DUAL; output: 17.0

SELECT SQRT(25) FROM DUAL; output: 5

SELECT EXP(2) FROM DUAL; output: 7.3890561

- this function calculates the value of e to the power argument where e = 2.71828183 .

SELECT GREATEST(12, 20, 40) FROM DUAL; output: 40

SELECT LEAST(12, 20, 40) FORM DUAL; output: 12;

SELECT MOD(12,5) FROM DUAL; output: 12 divided by 5 and the answer is 2

SELECT CEIL(82.2) FROM DUAL; output: 83

SELECT FLOOR(82.2) FROM DUAL; output: 82


String Function

SELECT LOWER(PRAKHAR) FROM DUAL; output: prakhar

SELECT UPPER(prakhar) FROM DUAL; output: PRAKHAR

SELECT INITCAP(pRAKhar) FROM DUAL; output: Prakhar

SELECT SUBSTR(prakhar,2,5) FORM DUAL; output: rakha

- in above query, oracle will start reading from 2nd position up till a which is at 5th position from there.

SELECT ASCII(A) FROM DUAL; output: 65

SELECT INSTR(prakhar, a) FROM DUAL; output: 3

SELECT INSTR(prakhar, a, 1, 2) FROM DUAL; output: 6

-the above query will search for a , it will start searching from the first occurrence of a and it will search for the a at second position.

SELECT TRANSLATE(prakhar, ar , bs) FROM DUAL; output: psbkhbs

SELECT LENGTH(cow) Length Of String FROM DUAL; output: 3

SELECT LTRIM(prakhar , pr ) FORM DUAL; output: akhar

-if no argument is passed i.e. in this case pr , by default it will remove the white spaces from the starting.

SELECT RTRIM(prakhar, khar) FROM DUAL; output: pra


SELECT TRIM( prakhar ) AS TRIM FROM DUAL; output: prakhar

SELECT TRIM(LEADING X FROM XXXprakharXXX ) FROM DUAL;


output: prakharXXX

SELECT TRIM(TRAILING X FROM XXXprakharXXX ) FROM DUAL;


output: XXXprakhar

SELECT TRIM(BOTH X FROM XXXprakharXXX ) FROM DUAL; output:


prakhar

SELECT LPAD(prakhar , 10, *) FROM DUAL; output: ***prakhar

SELECT RPAD(prakhar , 10, *) FROM DUAL; output: prakhar***


Conversion Function

SELECT 2 + TO_NUMBER(2) FROM DUAL; output: 4

SELECT TO_CHAR(12345, 00,0000) FROM DUAL; output: 01,2345

- argument passed in the above query 12345 is the input and 00,0000 this is the format we
expect in our output.

SELECT TO_CHAR(SYSDATE, MONTH DD YYYY) AS Date FROM DUAL; output: March


24 2015

SELECT TO_CHAR(SYSDATE, MM DD YYYY) AS Date FROM DUAL; output: 03 24 2015

- in the above 2 queries the argument which we have passed the first one represents input
date, and second one is for the format which we expect.

SELECT TO_DATE(SYSDATE, DD MM YYYY) TO DATE FROM DUAL; output: 24-03-


2015
Date Function

- in oracle there are some function defined, with the help of them we can perform various tasks upon the values whose type is
DATE.

SELECT ADD_MONTHS(SYSDATE, 6) Add Month FROM DUAL; input: 24-MAR-15 output: 24-SEP-15

- the argument passed in the above question, the first one represents the input date and the second one represents no. of months to
be added to that current date.

SELECT LAST_DAY(SYSDATE) Last Day FROM DUAL; input (SYSDATE): 24-MAR-15 output: 31-MAR-15

SELECT NEXT_DAY(24-MAR-15, monday) FROM DUAL; output: 30-MAR-15

- the above function needs two arguments first one is the date and second one is day.
- this function helps us to find the date which will occur on the inputted day, and the date will be after 24-MAR-15 i.e. the inputted
date in above case.

SELECT MONTHS_BETWEEN( 06-JAN-16 , 06-APR-15) FROM DUAL; output: 1

- the above function requires two arguments which are date, and this function will find out the months between these two dates.

SELECT TO_CHAR(SYSDATE, DDTH/MM/YY) FROM DUAL; output: example - 24TH/MAR/15

SELECT TO_CHAR(SYSDATE, DDSP/MM/YY) FROM DUAL; output: example twenty-four/MAR/15

SELECT TO_DATE(24/03/2015, DD/MM/YYYY) FROM DUAL; output: 24-MAR-15

- in the above query the first argument is the string date which we want to cast in date formant, the second argument is to tell the
function that in which format we are sending the date.
This is COMPANY table and
Grouping functions are applied on it
COMPANY AMOUNT TABLE NAME = COMPANY

SELECT COMPANY, SUM(amount) FROM


Tcs 12000 COMPANY WHERE COMPANY = Hp GROUP
BY COMPANY;

Tcs 20000 - In the above query the table name and the first
column name are both COMPANY
- The output of the query will be executed in a
Hp 40000 manner such that all the rows with the company
name Hp will collapse and become one and all
the data in the amount column against Hp will be
added together.
Hp 30000
SELECT COMPANY, SUM(amount) FROM
COMPANY GROUP BY COMPANY HAVING
SUM(amount)>4000;

- We use HAVING clause in a situation where we


need further filtration on a result.
- In the above query the group by clause will
generate a result and the having clause will
provide further filtration on it.

output : Hp 70000
Joins, Sub-queries, and Views

SQL PLUS
Example table to understand joins

emp_id (pk) emp_name prod_id prod_name emp_id


(pk) (fk)
E01 Pandey sunil
234 Printer E01
E02 Dubey ajay
657 Table E03
E03 Dubey anand
865 Chair E03
E04 Singh ashwin

employees Table (j.1) orders Table (j.2)


Inner Join
Inner join is used for handling complex data. When we need to extract
the data from multiple tables then inner join keyword is used.

SELECT e.emp_name, o.prod_name FROM orders o INNER JOIN


employees e ON e.emp_id = o.emp_id;
-output:
1- pandey sunil printer
2- dubey anand table
3- dubey anand chair

- the above query can also be formed this way.

SELECT employees.emp_name, orders.prod_name FROM orders


INNER JOIN employees ON employees.emp_id = orders.emp_id;
Right Join
This join works in a way that, the output of the query with right join will contain all the rows
that are present in the table whose name is written on the right side of this keyword.

SELECT e.emp_name, o.prod_name FROM orders o RIGHT JOIN employees e ON


e.emp_id = o.emp_id;
-output:
1- pandey sunil printer
2- dubey anand table
3- dubey anand chair
4- singh ashwin
5- dubey ajay

- the above query can also be formed this way.

SELECT employees.emp_name, orders.prod_name FROM orders INNER JOIN


employees ON employees.emp_id = orders.emp_id;
Left Join
This join works in a way that, the output of the query with left join will contain all the rows
that are present in the table whose name is written on the left side of this keyword.

SELECT e.emp_name, o.prod_name FROM orders o LEFT JOIN employees e ON


e.emp_id = o.emp_id;
-output:
1- pandey sunil printer
2- dubey anand table
3- dubey anand chair

- the above query can also be formed this way.

SELECT employees.emp_name, orders.prod_name FROM orders LEFT JOIN


employees ON employees.emp_id = orders.emp_id;
Self Join table( j.3 )

Id Name Type
Let this table name be persons
1 Teacher 1 In self join we treat one single
2 Student 1 0 table as two different table.
All the columns in this table and
3 Student 2 0 all the example tables have data
type VARCHAR2(10).

SELECT teacher.name Teacher


Name, student.name Student
FROM persons teacher, person
student where student.type=0
and teacher.type=1;

-output:
Teacher Name Student Name
1 Teacher Student 1
2 Teacher Student 2
Cross Join
Sr_No Course_Name SELECT c.course_name,
1 BCA s.subject_name FROM courses
2 BSC c CROSS JOIN subjects s;

Table: courses
SELECT
courses.course_name,
subjects.subject_name FROM
Sr_no Sub_Name courses CROSS JOIN subjects;
1 oracle
2 java Output:

Table: subjects 1. BSC oracle


2. BSC java
3. BCA oracle
4. BSC java
Sub-Queries
We will use table j.1 and table j.2 to create a
example showing how to use sub queries.

SELECT * FROM orders WHERE emp_id IN


(SELECT emp_id FROM employees WHERE
emp_name=Pandey sunil);

output:
234 printer E01
UNION and UNION ALL
UNION helps us to take out records from multiple tables and join them.

The records that are present in the output, there can be multiple
similar records but since we are using UNION only single set of the
total records will be displayed or we can say there will be no similar
records in the output.

Just like UNION, UNION ALL is used the basic difference between
them is that, when we use UNION no duplicate record is displayed.
Well in the case of UNION ALL, all the outputs which are generated by
the individual query are displayed. We will see repetition of records
while using UNION ALL clause.

Using table (j.1) and (j.2) we will query on these table to understand
union and union all more effectively.
SELECT emp_id FROM employees UNION SELECT emp_id FROM orders;

SELECT emp_id FROM employees UNION ALL SELECT emp_id FROM orders;

Emp_id Emp_id
E01 E01
E02 E02
E03 E03
E04 E04
E01
E03
E03

UNION query output UNION ALL query output


INTERSECT
SELECT emp_id FROM Emp_id
employees INTERSECT E01
SELECT emp_id FROM E03
orders;

- the only records which


are common in both the
table will be show as the
output of the above query.

output:
right side.
MINUS
SELECT emp_id FROM Emp_id
employees MINUS SELECT E02
emp_id FROM orders;
e04
- the output of the above query
will contain all the emp_ids
which are present in the
employees table but not in the
orders table.

- if we swap places of both the


table name in the above query
the output will have no records
to display, because order table
have emp_id (1, 3) where as in
employees (1,2,3,4).
VIEWS
They are used for security purposes, so that each column of a table
can only be seen by those who are authorized to see it.

If for each user we define part-of a particular table so that he can see
only those columns which they are allowed to, the redundancy will
increase and this sort of approach is inefficient, but have the capability
to provide security.

View dont have data stored in them. They read the table and also read
there own implementation so as to know, what are all the columns the
need to show to the user.

We can use views as if they are tables, we can perform CRUD queries.

Views are of 2 types READ-ONLY and UPDATABLE.


CREATE , SELECT and INSERT

CREATE VIEW <view_name> AS SELECT <col_name>


<alias_name>, <col_name 1> <alias_name 1> ,.FROM
<table_name>;

SELECT <alias_name>, <alias_name1>, FROM <view_name>;

INSERT INTO <view_name> values (<value>, <value>);

UPDATE <view_name> SET <alias_name> = <value> WHERE


<alias_name?> = <value>;

DELETE FROM <view_name> WHERE <alias_name?>=<value>;

DROP VIEW <view_name>;


Limitations (updatable view)

Aggregate functions cannot be used.


DISTINCT, HAVING, GROUP BY clause cannot be used.
Sub queries cannot be used.
UNION, INTERSECT and MINUS cannot be used.
Constant, Strings and Expressions.

If one view is defined by another the other view must be


updatable.

You might also like