Professional Documents
Culture Documents
SQL Oracle
SQL Oracle
1) Number
The Number data type can store positive, negative, zeroes, fixed point
numbers and floating point numbers with a precision of 38.
a) column_name number { p = 38, s = 0 }
b) column_name number(p) { fixed point }
c) column_name number(p,s) { float point }
Where p is the precision, which refers to the total number of digits and s is the scale,
which refers to the number of digits to the right of the decimal point.
2) Char
This data types is used when fixed length character string is required. It can
store alphanumeric values. The column length for this data type varies between 1-2000 bytes. By
default it is One (1) byte.
● If user enters a value shorter than the specified length the database blank-pads to the
fixed length.
● If the user enters a value larger than the specified length the database would return an
error.
3) Varchar2
This data types supports variable length character string. It also stores
alphanumeric values. The size of this data types is 1-4000 bytes. Varchar2 saves disk space
compared to Char. Consider a column assigned with Varchar2 data type of size 30 bytes, if user
enters 10 bytes of character, than the column length in that row would only be 10 bytes and not 30
bytes. In case of Char it would still occupy 30 bytes because the remaining would be blank padded
by oracle.
4) Long
This is used to store variable character length. Maximum size is 2 GB. It also
stores alphanumeric values. The following restriction needs to be fulfilled when a long data type is
used for a column in a table.
a. Only one column in a table have long data type.
b. They should not contain unique or primary key constraints.
c. The column cannot be indexed
d. Procedure or Stored Procedure can not accept long data type as arguments.
5) Date
Date data type is used to date and time in a column of a table. Oracle uses its
own format to store date in a fixed length of 7 bytes for century, month, day, year, hour, minute, and
second. Default format of date data type is “dd-mon-yy”.
6) Raw
Raw data type is used to store byte oriented data like binary data or byte
strings and the maximum size of this data type is 2000 bytes. While using this data type the size
should be mentioned because by default it doesn’t speciy any size. Only storage and retrieval of this
data type are possible, manipulation of data cannot be done. Raw data type can be indexed.
7) Long Raw
Long raw data type is used to store binary data of variable length, which can
have a maximum size of 2 GB. This data type cannot be indexed. All limitations faced by long data
type also holds good for long row data type.
The Data Definition Language is used to create object (e.g table, view etc.),
alter the structure of the object and also drop or destroy the object created. A table is a unit in oracle
that holds data in the form of rows and columns. The Data Definition Language used for table
definition as following commands.
Create table command is used to create a table. General syntax is given below.
Example
SQL > Create table student1 (rollno number, name varchar2(20), address
varchar2(20), city varchar2(20));
SQL > Create table student2 (rollno number unique, name varchar2(20), address
varchar2(20), city varchar2(20));
We can also define a primary key to a column_name for the table.
SQL > Create table student3 (rollno number primary key, name varchar2(20),
address varchar2(20), city varchar2(20));
When you want to change the structure of table alter table command is used. For
example…
General syntax is …
Example
The truncate table command deletes all rows from the specified table but the
structure of table doesn’t change and it is retained by oracle. General syntax is..
Example
By adding ‘reuse storage’ clause to the above command the space that is used by the
rows of the above table is reused.
Example:
Example:
Data manipulation commands are used to query and manipulate existing objects like
tables. The DML commands are as follows.
1. Insert
2. Select
3. Update
4. Delete
1) Insert command
When the table is created using create table command, there is need to insert a rows
(records) into the table. The insert command is used to add one or more rows to a table. While using
this command the values are separated by commas and the data types varchar2, char, raw long and
date are enclosed in single quotes. The values must be entered in the same order as they are defined
in the table.
SQL > insert into student1 values (1,’Ramesh’, ‘abc society’, ‘wadhwan’);
SQL > insert into student1 values (2,’suresh’, ‘xyz society’, ‘wadhwan’);
SQL > insert into student1 (rollno, name) values (1,’Mahesh’);
SQL > insert into student1 values (&a,’&b’, ‘&c’, ‘&d’);
SQL > /
2) Select command
When we want to retrieve data stored in the table, we have to use select command.
This is generally referred to as ‘querying’ to the table. ‘*’ is used to select all columns for a
particular table.
Example:
To prevent the selection of duplicate rows from the table, we have to use distinct caluse in
the select statement. Suppose there are duplicate values for rollno in student1 table, the following
query would exclude them from being displayed.
3) Update command
When we want to change or modify data into the table we have to use update command.
With the update command we can update the rows in the table. A single column or more than one
column can be updated. The update command consists of a ‘set’ clause and an optional ‘where’
clause.
Example
SQL > update student1 set name = ‘suresh’;
SQL > update student1 set rollno = 5 where name = ‘mahesh’;
4) Delete Command
One or more rows could be deleted using the Delete command. All rows of a table
could also be deleted while structure remains unchanged. To delete specific rows from a table the
‘where’ clause can be used.
Example:
Clauses in SQL
1. WHERE
2. STARTING WITH (% and _ Clause)
3. ORDER BY
4. GROUP BY
5. HAVING
1) WHERE Clause
To select specific rows from a table we include ‘where’ clause in the select statement. We
can retrieve only the rows which satisfy the ‘where’ the condition.
Example:
SQL> select payee from checks where location = 'rajkot' and amount > 1000;
PAYEE
-------------------
kalpesh patel
SQL> select payee from checks where location = 'rajkot' or amount > 1500;
PAYEE
--------------------
kalpesh patel
jignesh joshi
Starting with clause is used search the string starts with a particular character or
string. % sign is used for multiple character and _ (Underscore) is used for one character.
Example
SQL> select payee from checks where payee like 's_’;
SQL> select payee from checks where payee like 's%';
PAYEE
--------------------
suresh shah
3) ORDER BY Clause
Example
AMOUNT
---------
500
1000
1200
1500
1700
2000
AMOUNT
---------
2000
1700
1500
1200
1000
500
SQL> select payee,amount from checks order by payee asc, amount desc;
PAYEE AMOUNT
-------------------- ---------
jignesh joshi 1700
kalpesh patel 2000
nilesh trivedi 1200
paresh shukla 1500
ramesh patel 1000
suresh shah 500
4) GROUP BY Clause
In order to find the records with particular group, group by clause is used.
Example
LOCATION SUM(AMOUNT)
--------------- --------------------
ahmedabad 500
rajkot 2000
surendranagar 3200
wadhwan 2200
SQL> select location, count(payee) "Total" from checks group by location;
LOCATION Total
--------------- ---------
ahmedabad 1
rajkot 1
surendranagar 2
wadhwan 2
Maximum Minimum
--------- ---------
500 500
2000 2000
1700 1500
1200 1000
5) HAVING Clause
Having clause is used with group by clause in order to find the records, which
satisfies the given condition.
Example
Maximum Minimum
--------- ---------
1200 1000
SQL> select location, sum(amount) "Total" from checks group by location having location =
'surendranagar';
LOCATION Total
--------------- ---------
surendranagar 3200
## SQL> select check_no, payee from checks where amount = (select max(amount) from
checks group by location having location = 'wadhwan');
CHECK_NO PAYEE
-------------- --------------------
103 nilesh trivedi
1. Commit 2) Savepoint
3) Rollback
All changes made to the database can be referred to as a transaction. Transaction
changes can be made permanent to a database only if they are committed.
Commit:
Commit command is used to end a transaction. With the help of this
command, transaction changes can be made permanent to the database.
Savepoint:
Save points are like markers to divide a very lengthy transaction to smaller
ones. They are used to identify a point in a transaction to when we can later rollback. Thus
savepoint is used in conjunction with rollback, to rollback portions of the current
transaction.
Rollback:
A rollback command is used to undo the work done in the current transaction.
We can either rollback the entire transaction so that all changes made by SQL statements are
undo or rollback a transaction to a savepoint so that the SQL statements after the save point
are rolled back.
Data control language provides users with privilege commands. The owner can give rights
of the database objects, say tables to the others users. Granting privileges (insert, select..) to others
allow them to perform operations within their (privileges) purview.
1. Grant
2. Revoke
Grant privilege:
Grant command is used to giving permission (rights) to use database objects (tables
etc…) to other users. In case the user wants to share an objects with others, the appropriate
privileges can be granted on that particular object others. Objects are logical data storage,
structures like tables, views, sequences etc.
SQL> grant privileges on <object_name> to <user_name>
SQL> grant select, update on student1 to scott;
The privilege to update values in the rollno, name columns of the student1 table is to
be granted to scott using following syntax.
When object privileges are granted and WITH GRANT OPTION is used, these
privileges can be passed to others.
SQL> grant select, update on student1 to scott with grant option;
Revoke privilege:
To withdraw(revoke) the privilege that has been granted to user, we use the revoke
command. The syntax is given below.
Set Operators:
Set operators combine the results of two queries into single one. The following set
operators are available in SQL to joining queries.
1. Union
2. Union all
3. Intersect
4. Minus
The columns in the select statements joined using the set operators should strictly follow the
following rules.
● The queries which are related by a set operator should have the same number
of columns and the corresponding columns must be of the same data type.
● Such a query should not contain any column of type long.
● The label under which the rows are displayed are those from the first select
statement.
STUDENT TEACHER
The Union operator returns all distinct rows selected by both queries. The following
example combines the result of two queries with the union operator which eliminates
duplicate rows.
SQL> select rollno from student union select rno from teacher;
ROLLNO
-----------
1
2
5
55
77
111
2) Union all
The ‘union all’ operator returns all rows selected by either query
including duplicates. The following example combine the result with the use of ‘union all’ operator
which does not eliminates duplicate rows.
SQL> select rollno from student union all select rno from teacher;
ROLLNO
---------
77
111
2
5
55
1
2
5
3) Intersect
Intersect operator returns only rows that are common to both the
queries.
SQL> select rollno from student intersect select rno from teacher;
ROLLNO
---------
2
5
4) Minus
Minus operator returns all distinct rows selected only by the first
query and not by second.
SQL> select rollno from student minus select rno from teacher;
ROLLNO
---------
55
77
111
SQL> select rno from teacher minus select rollno from student;
RNO
---------
1
The purpose of join is to combine the data spread across the tables. A join is actually
performed by the ‘where’ clause which combines the specified rows of tables. If a join involves
over two tables then oracle joins the first two based on the condition and then compares the result
with the next table and so on.
1. Simple join
a. Equi-join
b. Non equi-join
2. Self join
3. Outer join
1) Simple Join : It is the most common type of join. It retrieves rows from two tables having a
common column and is further classified into equi-join and non equi-join.
Table Aliases: Table aliases are used to make multiple table queries shorter and more
readable. As a result, we give an alias to the table in the ‘from’ clause. The alias can be used
instead of the table name throughout the query.
SQL> select s.rollno, s.name, t.tname from student s, teacher t
where s.rollno = t.rno;
B) Non-equi Join : A non-equi join specifies the relationship between columns belonging to
different table by making use of the relational operators (<,>,<=,>=,<>) other than =.
SQL> select s.rollno, s.name, t.tname from student s, teacher t where t.rno >= s.rollno;
2) Self Join : joining of table to itself is known as a self join. i.e. It joins one row in a
table to another. The join is performed by mirroring the table using the ‘where’
clause. It can compare each row of the table to itself and also with other rows of the
same table.
SQL> select a.rno, b.tname from teacher a, teacher b where a.rno = b.rno;
RNO TNAME
--------- -------------------------
1 jatin zinzuvadiya
2 jayanti khimsuria
5 dharmendra gadhvi
SQL> select a.rno, b.tname from teacher a, teacher b where a.rno = b.tno;
RNO TNAME
--------- -------------------------
1 jatin zinzuvadiya
2 jayanti khimsuria
SQL> select a.rno, b.tname from teacher a, teacher b where a.rno <> b.rno
RNO TNAME
--------- -------------------------
2 jatin zinzuvadiya
5 jatin zinzuvadiya
1 jayanti khimsuria
5 jayanti khimsuria
1 dharmendra gadhvi
2 dharmendra gadhvi
SQL> select a.rollno, b.name from student a, student b where a.rollno > b.rollno;
ROLLNO NAME
--------- --------------------
111 jayesh patel
77 dhaval mehta
111 dhaval mehta
5 dhaval mehta
55 dhaval mehta
77 suresh mehta
111 suresh mehta
55 suresh mehta
77 dinesh shukla
111 dinesh shukla
3) Outer Join : outer join extends the result of a simple join. An outer join returns all
the rows returned by simple join as well as those rows from one table that do not
match any row from the other table. The symbol (+) represents the outer join.
SQL> select s.rollno, s.name, t.tname from student s, teacher t where s.rollno(+) = t.rno;
The above example will also retrieve rows from teacher which do not have any
matching records in the student table.
SQL> select s.rollno, s.name, t.tname from student s, teacher t where s.rollno = t.rno(+);
The above example will also retrieve rows from student which do not have any
matching records in the teacher table.
SQL> select s.rollno, s.name, t.tname from student s, teacher t where s.rollno(+) = t.tno;
SQL> select s.rollno, s.name, t.tname from student s, teacher t where s.rollno = t.tno(+);
Functions
A) Aggregate functions
1) Sum ( ) 2) Avg ( ) 3) Min ( ) 4) Max ( )
5) Variance ( ) 6) Stddev( )
C) Arithmetic functions
1) abs ( ) 2) ceil ( ) 3) floor ( ) 4) exp
5) ln ( ) 6) log ( ) 7) power ( ) 8) sign ( )
9) sqrt ( ) 10) mod( ) 11) trunc ( ) 12) sin ( )
13) sinh ( ) 14) cos ( ) 15) cosh ( ) 16)
round ( )
D) Character functions
1) chr ( ) 2) concat ( ) 3) initcap ( ) 4) lower ( )
5) upper ( ) 6) lpad ( ) 7) rpad ( ) 8) ltrim ( )
9) rtrim ( ) 10) replace ( ) 11) substr ( ) 12) translate()
13) instr ( ) 14) length ( )
E) Conversion Functions
1) to_char ( ) 2) to_number( ) 3) to_date ( )
F) Miscellaneous Functions
1) greatest ( ) 2) least ( ) 3) nvl ( ) 4)
count ( )
4. vsize ( )
Constraints
A constraint is an object in a relational database that places rules on data inserted into a
column of a table. Constraints are used to ensure accuracy and consistency of data in a relational
database. Data integrity is this assurance of accurate and consistent data in the database.
Components of data integrity (data accuracy and consistency) enforce rules (constraints) on
the database. Accuracy of data involves placing rules (constraints) on table columns so that the
database only allows certain types of accurate data to be inserted into these columns. Database
normalization are used to provide data consistency. Implementation of referential integrity
constraints (foreign key) will help maintain consistent data in a normalized database.
Types of Constraints :
a) Not Null constraint : By default the tables can contain null values. The enforcement
of not null constraint in a table ensures that the table contains values. Oracle doesn’t
insert the record until this is satisfied.
Example:
SQL > create table emp (emp_id number(3) not null, emp_name varchar2(10) not
null, address varchar2(20), city varchar2(10));
b) Check constraint : This can be defined to allow only a particular range of values.
When the values not inserted in the specified range oracle rejects the record.
Example:
a. Unique constraint
b. Primary key constraint
a) Unique constraint : The unique constraint designates a column or a group of
columns as a unique key. This constraint allows only unique values to be stored in
the column. Oracle rejects duplication of records when unique key constraint is used.
Example
SQL> create table emp (emp_id number(3) not null unique, emp_name varchar2(10)
not null, address varchar2(20), city varchar2(10));
OR
SQL> alter table emp add constraint emp_id_unique unique (emp_id);
b) Primary key constraint : The primary key constraint avoids duplication of rows
and does not allow null values, when enforced in a column or set of columns. If a
primary key constraint is assigned to a combination of columns it is said to be a
composite primary key.
Example
SQL> create table emp (emp_id number(3) primary key, emp_name varchar2(10)
not null, address varchar2(20), city varchar2(10));
OR
SQL> alter table emp add constraint pk_emp_id primary key (emp_id);
SQL> create table customer (cust_id number(3) primary key, cust_name varchar2(10),
cust_address varchar2(20), cust_city varchar2(10));
SQL> create table Item (item_id number(3) primary key, cust_id number(3) constraint
fk_cust_id references customer (cust_id), item_desc varchar2(20), item_price number(5,2));
OR
SQL> alter table item add constraint fk_cust_id foreign key (cust_id) references customer
(cust_id);
On Cascade Clause
SQL> alter table item add constraint fk_cust_id foreign key (cust_id) references customer
(cust_id) on delete cascade;
Database Objects
1. View
2. Index
3. Synonym
4. Sequences
1) View : A view is often referred as a virtual table. A view is defined by a query on one or
more database tables. A view takes a output of a query and treats it as a table. Advantages of
views are : 1) They simplify commands for the user because they allow them to select
information from multiple tables without actually knowing how to perform a join. 2) They hide
data complexity because when view is defined by a join which is a collection of related columns
or rows in multiple tables therefore view hides the fact that this information actually originates
from several tables.
Example
2) Index : An index is a way of presenting data differently then the way it appears on the disk. We
can create indexes explicitly to speed up SQL statement execution on a table. Similar to the
indexes in books that help us to locate information faster, an oracle index provides a faster
access path to table data. The index points directly to the location of the rows containing the
value.
Example
Unique index : Indexes can be unique or non-unique. Unique indexes guarantee that no two
rows of a table have duplicate values in the column that define the index. Non-unique index do
not impose this restriction on the column values.
SQL> create unique index ind_tno on teacher(tno);
Composite index : A composite index (also called a concatenated index) is an index created on a
multiple column of a table.
Reverse key indexes : You can also create a index in reverse order. Under some circumstances
using a reverse-key index can make application run faster.
SQL> create index ind_rnotno on teacher(rno,tno) reverse;
3) Synonym : A Synonym is a database object which is used as an alias (alternative name) for a
table. They are used to Simply SQL statements, hide the name and owner of an object and
provide public access to an object.
Example
4) Sequences : A sequence is a database object which can generate unique, sequential integer
values. It can be used to automatically generate primary keyor unique key values. A sequence
can be either in ascending or descending order.
Cycle : specifies that the sequence continues to generate values from the beginning after
reaching either its max or min value. The default values is no cycle.
Cache : The cache option pre-allocates a set of sequence number an retains them in memory so
that sequence number can be accessed faster. The default value is no cache.
Alter Sequence : The sequence can be altered when we want to perform the follwing :
● Set or eliminate minvalue or maxvalue
● Change the increment value
● Change the number of cached sequence numbers.