Complete Oracle SQL
Complete Oracle SQL
ORACLE
SQL
@Suman Rajak
TABLE OF CONTENTS
1 What is SQL
1 Connect to the Database
1 Clear the Screen
2 Datatypes in ORACLE
2-3 Create Table
3 Show Description of the Table
3-4 Insert Values in the Table
5 Show Records of the Table
5-6 Delete Records of the Table
6 Update Records in the Table
8-9 Order By
12 IN Operator
13 BETWEEN Operator
20 Commit
21 Creating Tablespace
21 Creating User
21 Creating Role
23 Alter Tablespace
24 Drop Tablespace
25 Insert Multiple Records in One or More Table at Once
27 Drop Roles
27 Drop User
29 Equi Join
32 Table Alias
32-33 Self Join
34 Natural Join
35 Cross Join
36 Left Outer Join
37 Right Outer Join
38 Full Outer Join
48 NVL
49 Decode
57 Unique Constraint
67 Having Clause
70 Union Operator
71 Union All Operator
72 Intersect
73 Minus
74 Execute Commands Written in Physical File
75 Make New File Using Command Line
What is SQL?
SQl is a language which is followed by every RDBMS. Using this, we can communicate with
a database.
Alternative method: -
1|Page
DATATYPES IN ORACLE SQL
CREATE TABLE
Using this command we can create a table in the database.
Condition:-
• It is a DDL Command
• Table name can be upto 30 char long.
• Table name must begin with alphabet.
• Table name can’t contain single or double quote.
• Names are not case sensitive.
• Names can contain a-z , 0-9, _ , $ , #
• Names can’t be reserved words.
Command: -
2|Page
Example: -
SQL> Create table student (Id number, Name varchar2(10) ,
Address varchar2(10));
Alternative method : -
• Varchar2
needs single
quote.
• Number, date
does not need
single quote
3|Page
Example: -
SQL> Insert into student values (1, ‘Suman’, ‘Purulia’);
Alternative Method: -
Example: -
Insert into student2 (Id, Name) values (5, 'Arpan');
4|Page
SHOW THE RECORDS OF THE TABLE
Show the full table: -
SQL> Select *from tablename;
Example: -
5|Page
Delete specific records with a condition: -
SQL> Delete from tablename where condition;
Example: -
6|Page
SELECT COMMAND WITH WHERE CONDITION
For all the fields: -
SQL> Select *from tablename where condition;
Concatenate
Statement
Concatenate
Operator
7|Page
Select with Multiple Conditions
SQL> Select *from tablename where condition1 and condition2;
Example: -
SQL> Select *from student2 where id=2 and name = 'Tanu';
ORDER BY
It Orders the Output of in ascending or descending order.
Example: -
8|Page
(2) SQL> Select *from student2 order by id desc;
Example: -
SQL> Select *from student2 where not id=5;
9|Page
LIKE ‘PATTERN’ OPERATOR
Pattern: -
• % :- Represents any value of any length
• _ :- Represents one unknown character
• __ (twice) :- Represents two unknown characters
• To Search using first letter :- ‘ letter %’
• To Search using middle letter:- ‘%letter%’
• To search using second letter :- ‘_letter%’
• To search using last letter :- ‘%letter’
Example: -
First Letter: -
SQL> Select *from student2 where name like 'A%';
Last Letter: -
SQL> Select *from student2 where name like '%an’;
10 | P a g e
Second Letter: -
SQL> Select *from student2 where name like '_r%’;
Middle Letter: -
SQL> Select *from student2 where name like '%y%’;
Third Letter: -
SQL> Select *from student2 where name like '__m%’;
11 | P a g e
IN OPERATOR
Using IN Operator we can specify a list of possible values for any column.
Using IN operator: -
SQL> Select *from tablename where fieldname in (‘fieldname
1’, ‘fieldname 2’);
Example: -
Using IN operator: -
SQL> Select *from student2 where adress in
('Rnp','Moyna','Adra');
12 | P a g e
BETWEEN OPERATOR
Using between operator we can select all records which falls in a specific range.
Example: -
13 | P a g e
PSEUDO COLUMNS
A Pseudo Column behaves like a table column, but is not actually stored in the table.
You can select from Pseudo Columns, but you cannot insert, update, or delete their
values.
Example: -
SYSDATE: -
SYSTIMESTAMP: -
UID: -
14 | P a g e
UID: -
Example: -
15 | P a g e
2. Now we will insert the value of ID in a table using this sequence.
Example: -
16 | P a g e
ROWID AND ROWNUM
ROWID is a unique pseudo number assigned to each row uniquely, they never collapse to match
different table.
ROWNUM returns the number of rows for a resultant query.
Example: -
17 | P a g e
RENAME TABLE
SQL> Rename oldtablename to newtablename;
DROP TABLE
SQL> Drop table tablename;
ROLLBACK
To use rollback we have to make a savepoint. Then we will change something in the
database and will rollback to the savepoint. We will observe that the changes will be
removed due to the rollback.
We can undo the insert , update and delete command using rollback;
18 | P a g e
Example: -
19 | P a g e
COMMIT
Commit is used to permanently save in the database. We can permanently save the insert , update
and delete command using rollback;
SQL> COMMIT;
Example: -
20 | P a g e
CREATING TABLESPACE
SQL>CONNECT username/password;
SQL>CREATE TABLESPACE TablespaceName DATAFILE
2 ‘C://oraclexe/oradata/xe/TablespaceName.dbf’
3 SIZE 50M; Will create a tablespace
Of size 50 MB
CREATING USER
SQL>CREATE USER UserName IDENTIFIED BY Password
DEFAULT TABLESPACE TablespaceName
TEMPORARY TABLESPACE Temp
QUOTA UNLIMITED ON TablespaceName;
CREATING ROLE
SQL>CREATE ROLE RoleName
21 | P a g e
ASSIGNING PERMISSION ON ROLE
SQL>GRANT (roles) CREATE TABLE, CREATE SESSION TO RoleName;
Example: -
Now the user can create tables and can log in to the database because of the “create
session” role.
22 | P a g e
ALTER TABLESPACE
If a user has “alter tablespace” privilege then only he can use the alter tablespace
command.
A tablespace can have multiple data files.
23 | P a g e
See Total tablespace list
SQL> select tablespace_name from dba_data_files;
DROP TABLESPACE
SQL> drop tablespace tablespacename including contents and
datafiles;
24 | P a g e
INSERT MULTIPLE RECORDS IN ONE OR MORE TABLE AT ONCE
Example: -
(1) We are creating a table named tab1 and inserting 3 records at once.
(2) we are creating another table named tab2 and inserting multiple records in both
table at once.
SQL> insert all
2 into tab1 values (4, 'abc')
3 into tab1 values (5, 'xyz')
4 into tab2 values (1, 'tyu')
5 into tab2 values (2, 'hjk')
6 select *from dual;
25 | P a g e
GRANT A USER TABLE TO ANOTHER USER
First Make 2 users
Make 2 roles
Assign them the roles
Now connect to first user (let, ‘sr’) and create a table ‘te1’
Generally, we cannot see the table created by first user by connecting the second user
(let, ‘tanu’)
Now Connect to tanu and view the table of sr by using this query
26 | P a g e
DROP ROLES
Connect to administrative account i.e., using system username and use this query
SQL> Drop Role rolename cascade.
To delete the associated users
which are associated with the role
DROP USER
Connect to administrative account i.e., using system username and use this query
SQL> Drop user username cascade;
Child Table: -
SQL> create table student_marks (roll_no number references student_add
on delete cascade, subject varchar2(50), marks number (3));
Because of ‘on delete cascade’ if we delete a record from the parent table then it will be
automatically deleted from the child table.
27 | P a g e
COLUMN ALIAS
Using this we can change the column head name in the output.
Example: -
28 | P a g e
EQUI JOIN
In this join we use the equal operator.
Example: -
DEPT EMPL
29 | P a g e
NON EQUI JOIN
Here we use other operators like >, <, > =, < =, < > (Not Equals).
Example: -
(1)
DEPT EMPL
We will fetch the dno of the dept table which are greater than the dno in the empl table
In dept table,
10 is greater than no one in the empl table.
20 is greater than 10 and 10 in the empl table
30 is greater than 10,20,10 in the empl table
40 is greater than 10,20,10 in the empl table
30 | P a g e
(2)
DEPT EMPL
We will fetch the dno of the dept table which are lesser than the dno in the empl table
In dept table,
10 lesser than 20,50 in the empl table.
20 is lesser than 50 in the empl table
30 is lesser than 50 in the empl table
40 is lesser than 50 in the empl table
31 | P a g e
TABLE ALIAS
SQL> Select fieldname, fieldname from table1 table1_new_name, table2
table2_new_name where condition
Example: -
SQL> select eno,ename , dname from empl e , dept d where e.dno=d.dno;
SELF JOIN
In this join a table joins with itself with two different temporary names using table alias.
Example: -
EMPL
32 | P a g e
SQL> select e1.eno, e2.ename, e1.dno from empl e1 , empl e2
where e1.eno = e2.eno;
33 | P a g e
NATURAL JOIN
Natural join returns the matching column in both of the tables.
Example: -
DEPT EMPL
SQL> select eno, ename, dno, dname from empl natural join
dept;
34 | P a g e
CROSS JOIN
In the output the rows are merged of both of the tables without any condition
Example: -
DEPT EMPL
35 | P a g e
LEFT OUTER JOIN
It returns all the tuples of the left relation and only the matching tuples from the right
relation.
SQL> Select *from left_table, right_table where
left_table.matching_field = right_table.matching_field (+)
OR,
Example: -
EMPL DEPT
36 | P a g e
RIGHT OUTER JOIN
It returns all the tuples of the right relation and only the matching tuples from the left
relation.
SQL> Select *from left_table, right_table where
left_table.matching_field (+) = right_table.matching_field
OR,
Example: -
EMPL DEPT
37 | P a g e
FULL OUTER JOIN
It returns all the tuples from both of the relations even if they are not matching.
Example: -
EMPL DEPT
38 | P a g e
ANTI JOIN OR NOT IN OPERATOR
It returns all the records of the first table with are not matching with the second table.
Example: -
EMPL DEPT
SQL> select *from empl where dno not in (select dno from
dept where dname='MBA');
39 | P a g e
COLUMN FORMAT
We can temporarily format any column as per our requirement.
Example: -
40 | P a g e
CLEAR COLUMN FORMATTING
SQL> clear column;
OR,
Restart the ‘Run SQL Command Line’
41 | P a g e
Example: -
(1) AVG
(5) MAX(X)
42 | P a g e
(7) SUM (X)
43 | P a g e
Example: -
INITCAP
SQL> select initcap ('suman') from dual;
LENGTH
SQL> select length ('i am suman') from dual;
SUBSTR
SQL> select substr ('i am suman',3,2) from dual;
INSTR
SQL> select instr('i am suman','am') from dual;
GREATEST
SQL> select greatest(56,78,45,98,67) from dual;
LEAST
SQL> select least(56,78,45,98,67) from dual;
44 | P a g e
NUMBER FUNCTIONS IN ORACLE
Example: -
ABS
SQL> select abs (-345) from dual;
CEIL
SQL> select ceil (456.67) from dual;
45 | P a g e
FLOOR
SQL> select floor (456.34) from dual;
ROUND
SQL> select round (456.54,0), round (456.54,1), round (456.54,2) from
dual;
SQRT
SQL> select sqrt (9) from dual;
TRUNC
SQL> select trunc (456.54 ,0), trunc (456.54 ,1) from dual;
LN
SQL> select ln (5) from dual;
LOG
SQL> select log (2,5) from dual;
MOD
SQL> select mod (2,5) from dual;
46 | P a g e
CONVERSION FUNCTIONS IN ORACLE
TO_DATE
This is used to convert any string format into date format.
TO_CHAR
If we want to see only specific part.
47 | P a g e
Quarter Division of Months
NVL
It fills default value in the null fields.
Example: -
48 | P a g e
DECODE
Decode Function is used to expand a small abbreviation.
Example: -
49 | P a g e
DATE FUNCTIONS
Example: -
ADD_MONTHS
SQL> select add_months('6-jun-88',5) from dual;
LAST_DAY
SQL> select last_day('6-jun-88') from dual;
NEXT_DAY
SQL> select next_day('6-jun-88','WED') from dual;
50 | P a g e
MONTHS_BETWEEN
SQL> select months_between ('6-jun-88','6-nov-88') from dual;
NEW_TIME
SQL> select new_time('6-jun-88','gmt','bst') from dual;
51 | P a g e
SQL BUFFER COMMANDS
Buffer Stores the Number of Lines in a query.
Example: -
SQL> 1 (1 is selected as the new line)
52 | P a g e
INSERT A LINE AFTER THE NEW LINE
SQL> Input input_statement;
Example: -
(1 is selected as the new line)
DELETE A LINE
Select the Line and
SQL> del
Example: -
53 | P a g e
APPEND IN A LINE
Select the line and
SQL> Append, append_string
Example: -
SQL> 1 (Selects 1 as the new line)
SQL> Append, from empl
Example: -
SQL>1 (Selects the line 1 as the newline)
SQL> Change / *, from empl / id , name
54 | P a g e
ED OR EDIT BUFFER
First, we have to open the ‘run sql command line’ as an administrator.
Now, SQL> ed
(It will create a buffer notepad file …sekhane amar run kora query ta lekha thakbe…ami
notepad e kichu change korle seta command line e execute hobe…command execute korar jonno
‘/’ use korte hobe)
Example: -
STEP 2 – Connect
STEP 3 – Execute any Command and then, SQL> ed. Now a buffer notepad file will be created
Example: -
SQL> create table demo1 (id number, name varchar2(15) not null);
[Here the name field is not null]
56 | P a g e
UNIQUE CONSTRAINTS
If we make a column as unique then we have to store unique values for each field in that column.
We can make multiple columns unique.
Example: -
SQL> create table demo (id number unique, name varchar2(15));
[Here the ID field is unique]
57 | P a g e
PRIMARY KEY CONSTRAINT
Primary key identifies each record of the column uniquely.
A Primary Key –
• Accepts Only Unique Values.
• Cannot be Null.
• A table can have only one primary key.
Example: -
SQL> create table parent (parent_id number primary key, parent_name
varchar2(15) not null, city varchar2(10));
(Method-1)
SQL> Create Table tablename (fieldname (same as parent table primary
key) references parent_table_name);
Example: -
SQL> create table child (child_id number primary key, parent_id number
references parent, toy varchar2(15));
[ The ‘parent’ table is discussed in the primary key discussion section]
59 | P a g e
This is the Parent Table
We can insert the values of ‘parent_id’ which are available in the parent table (Ex:- 1)
We can’t insert the values of ‘parent_id’ which are not available in the parent table (Ex:- 3)
(Method 2)
Normally Make a table without referencing
Now,
SQL> alter table child_table_name add constraint constraint_name
foreign key (child_table_fieldname) references parent_table_name
(parent_table_fieldname);
60 | P a g e
We can Drop the Constraint to remove the Foreign Key using
SQL> alter table child_table_name drop constraint constraint_name;
Example: -
SQL> create table child(child_id number primary key, parent_id number,
toy varchar2(15));
[ Normally Creating a Table ]
We can insert the values of ‘parent_id’ which are available in the parent table (Ex:- 1)
We can’t insert the values of ‘parent_id’ which are not available in the parent table (Ex:- 3)
61 | P a g e
Dropping the Constraint
SQL> alter table child drop constraint fk_parentchild;
Now we can insert the values of ‘parent_id’ which are not available in the parent table (Ex:- 3)
CHECK CONSTRAINT
We use this constraint in create table and alter table. We use this to check certain conditions on a
column.
Example: -
(1)
SQL> create table marks (name varchar2(15), marks number, constraint
check_marks check (marks between 0 and 100));
We can insert the value of marks which are between 0 and 100
62 | P a g e
We can’t insert the value of marks which are not between 0 and 100
(2)
SQL> create table marks (name varchar2(15), marks number, constraint
check_name check (name = upper(name)));
Example: -
SQL> create table marks(name varchar2(15), marks number);
[ Normally Creating a Table ]
63 | P a g e
SQL> alter table marks add constraint check_marks check (marks between
0 and 100);
We can insert the value of marks which are between 0 and 100
We can’t insert the value of marks which are not between 0 and 100
Example: -
SQL> alter table marks disable constraint check_marks;
Now we can insert the value of marks which are not between 0 and 100
64 | P a g e
Re Enable Constraint: -
SQL> alter table tablename disable constraint constraint_name;
[ For re enabling we have to delete such records which are violating the condition of the
constraint]
GROUP BY
Group by clause is used in select statement. It is used for the grouping of multiple records. It
usually has an aggregate function but this is not mandatory.
Example: -
65 | P a g e
SQL> select product from orders group by product;
[ It groups the products]
66 | P a g e
HAVING CLAUSE
Having clause is used in select statement with group by clause. It is used to apply conditions in
the group by statement.
Example: -
[The product which has a sale of greater than rupees 2000 will be selected]
[The product which has a sale of greater or equal than 4 times will be selected
67 | P a g e
SUBQUERY OR INNER QUERY OR NESTED QUERY
Inside a query there is another query then it is called subquery or nested query or inner query.
In oracle we can use 255 level subqueries with where clause.
Example: -
(1)
SQL> select *from empl where eno = (select max(eno) from empl);
Explanation: - The subquery ‘select max(eno) from empl’ returns the maximum eno of the
table, which is 5.
Now the query returns all the details of the employee whose eno is 5.
68 | P a g e
(2)
SQL> select *from orders where product in (select product from orders
where sale>400);
Explanation: – The Subquery returns the products whose price is above 400.
They are,
Now the query returns all the products of this names with their details.
69 | P a g e
UNION OPERATOR
It merges two tables and removes the duplicates (if present).
Example: -
emp2013 emp2014
It removed the
Duplicate
value
70 | P a g e
UNION ALL
It merges two tables and doesn’t remove the duplicates (if present).
Example: -
emp2013 emp2014
71 | P a g e
INSTERSECT
It returns the tuples which are present in both of the tables.
Example: -
emp2013 emp2014
72 | P a g e
MINUS
It selects the tuples which are present in the first table but not in the second table.
Example: -
emp2013 emp2014
3 Tanumoy 50000
73 | P a g e
EXECUTE COMMANDS WRITTEN IN PHYSICAL FILE
It runs the sql query which is present in any physical file in ‘.sql’ or ‘.txt’ format.
Example: -
74 | P a g e
MAKE NEW FILE USING COMMAND LINE
SQL> Edit newfilename.extension(txt or sql);
Now save the file and run using the previous method using ‘Start’ command.
75 | P a g e