0% found this document useful (0 votes)
2 views

Complete Oracle SQL

Uploaded by

Its Me SR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Complete Oracle SQL

Uploaded by

Its Me SR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

COMPLETE

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

7 Select Command with Where Condition

7 Concatenate Using Select Command

7 Select Null Statement

8 Select with Multiple Condition

8-9 Order By

9 To Order using Multiple Fields

9 To Display without a Specific Records

10-11 Like Pattern Operator

12 IN Operator

13 BETWEEN Operator

14-15 Pseudo Columns

15-16 Currval and Nextval


17 RowID and RowNum
18 Rename Table
18 Drop Table
18-19 Roll Back

20 Commit
21 Creating Tablespace
21 Creating User
21 Creating Role

22 Assigning Permission to Role

22 Passing Role to User

23 Alter Tablespace

23 Add New Datafile to an Existing Tablespace

23 See Total Datafiles List

24 See Total Tablespace List

24 Remove Datafile from a Tablespace

24 Drop Tablespace
25 Insert Multiple Records in One or More Table at Once

26 Grant a user table to another table

27 Drop Roles

27 Drop User

27 Referential Integrity or Foreign Key


28 Column Alias

29 Equi Join

30-31 Non 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

39 Anti Join or Not IN


40 Column Format
41 Clear Column Formatting
41-43 Aggregate Functions

43-44 Character Functions

45-46 Number Functions

47-48 Conversion Functions in Oracle

48 NVL

49 Decode

50-51 Date Functions

51 SQL Command Types in Oracle

52-55 SQL Buffer Commands


56 Not Null Constraint

57 Unique Constraint

58 Primary Key Constraint

59-62 Foreign Key

62-65 Check Constraint


65-66 Group By

67 Having Clause

68-69 Subquery or Inner Query or Nested Query

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.

CONNECT TO THE DATABASE


SQL> connect
Enter Username:
Enter Password:

Alternative method: -

SQL> connect username/password;

CLEAR THE SCREEN


SQL> clear screen;

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: -

SQL> Create table tablename (Fieldname datatype (length));

2|Page
Example: -
SQL> Create table student (Id number, Name varchar2(10) ,
Address varchar2(10));

SHOW THE DESCRIPTION OF THE TABLE


SQL> desc tablename;

INSERT VALUES INTO THE TABLE


SQL> Insert into tablename values (values of fields
separated by comma);

Alternative method : -

SQL> Insert into tablename values (&fields separated by


comma);

• Varchar2
needs single
quote.
• Number, date
does not need
single quote

3|Page
Example: -
SQL> Insert into student values (1, ‘Suman’, ‘Purulia’);

Alternative Method: -

SQL> Insert into student values (&Id, ‘&Name’,


‘&Address’);
Enter the value of Id: -
Enter the value of Name: -
Enter the value of Address: -

Insert Specific fields into the table


SQL> Insert into tablename (fieldname, fieldname) values
(value, value);

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: -

Select *from Student;

Show specific fields of the table: -


SQL> Select fieldname, fieldname from tablename;
Example: -

Select Id, Name from Student;

DELETE RECORD FROM TABLE


This command will delete records/rows from table with or without condition.

Delete all records: -


SQL> Delete from tablename;

5|Page
Delete specific records with a condition: -
SQL> Delete from tablename where condition;
Example: -

SQL> Delete from Student2 where Id=4;

UPDATE RECORDS IN THE TABLE


Updates records in the table

SQL> Update tablename set field= new value where condition;


Example: -

SQL> Update Student2 set name= ‘joydip’ where name =


‘Arpan’;

6|Page
SELECT COMMAND WITH WHERE CONDITION
For all the fields: -
SQL> Select *from tablename where condition;

For specific fields: -


SQL> Select fieldname, fieldname where condition;

Concatenate using Select command


SQL> Select id || '-' || name || '-' || adress from
student2;

Concatenate
Statement

Concatenate
Operator

Select Null Statement


SQL> Select *from tablename where fieldname is null;
Example: -
SQL> Select *from student2 where adress is null;

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.

For Ascending Order: -


SQL> Select *from tablename order by fieldname;

For Descending Order: -


SQL> Select *from tablename order by fieldname desc;

Example: -

(1) SQL> Select *from student2 order by name;

8|Page
(2) SQL> Select *from student2 order by id desc;

To order using Multiple Fields


If we have some matching records in a field then we have to order using two fields.

SQL> Select *from tablename order by field1, field2;

If there is some matching field in


field1 then we will order using the
field2

To display without a specific record


SQL> Select *from tablename where not condition;

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

Without using IN operator: -


SQL> Select *from tablename where fieldname = ‘value’ OR
fieldname 1 = ‘value’ OR fieldname 2 = ‘value’

Example: -

Using IN operator: -
SQL> Select *from student2 where adress in
('Rnp','Moyna','Adra');

Without using IN operator: -


SQl> Select *from student2 where adress = ‘Rnp’ or
adress=’Moyna’ or adress =’Adra’;

12 | P a g e
BETWEEN OPERATOR
Using between operator we can select all records which falls in a specific range.

Using BETWEEN operator: -


SQL> Select *from tablename where fieldname between
lowerbound AND upperbound;

Without using BETWEEN operator: -


SQL> Select *from tablename where fieldname >= lowerbound
AND fieldname <= upperbound;

Example: -

Using BETWEEN operator: -


SQL> Select *from student2 where id between 2 and 5;

Without using BETWEEN operator: -


SQL> Select *from student2 where id>=2 and id<=5;

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.

SYSDATE – Current Date and Time


SYSTIMESTAMP – Complete time with millisecond and AM, PM etc.
ROWNUM – sequence number assigned to retrieve rows
ROWID – unique identifier for a row
UID – number associated with a user
USER – UserID of current user
CURRVAL – current value
NEXTVAL – next value

Example: -

SYSDATE: -

SQL> select sysdate from dual;

SYSTIMESTAMP: -

SQL> select systimestamp from dual;

UID: -

SQL> select uid from dual;

14 | P a g e
UID: -

SQL> select user from dual;

Currval and Nextval


SQL> CREATE SEQUENCE id_seq
MINVALUE 1
MAXVALUE 9999
START WITH 1
INCREMENT BY 1
CACHE 20
With respect to a sequence, the cache option specifies how many sequence values will be stored
in memory for faster access.
‘Nocache’ means that none of the sequence values are stored i memory.

Example: -

1. First, we have to create a sequence.


SQL> CREATE SEQUENCE id_seq
2 MINVALUE 1
3 MAXVALUE 9999
4 START WITH 1
5 INCREMENT BY 1
6 CACHE 20;

15 | P a g e
2. Now we will insert the value of ID in a table using this sequence.

SQL> Insert into tablename values (fieldname


sequencename.nextval);

Example: -

SQL> create table tb1 (id number, name varchar2(20));

SQL> insert into tb1 vlaues (id_seq.nextval , 'ram');


SQL> insert into tb1 values (id_seq.nextval , 'rahim');
SQL> insert into tb1 values (id_seq.nextval , 'shyam');
SQL> insert into tb1 values (id_seq.nextval , 'bharat');

SQL> insert into tb1 values (id_seq.currval , 'sundar');

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: -

SQL> select rowid from tb1;

SQL> select rownum from tb1;

Q) Select less than 3rd row without any ID field.


Ans:-
SQL> select *from tb1 where rownum<3;

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;

STEP 1 → SQL> Savepoint savepoint_name;

STEP 2 → NOW MAKE SOME CHANGES IN THE DATABASE.

STEP 3 → SQL> Rollback to savepoint_name;

STEP 4 → THE CHANGES WILL BE REMOVED.

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;

PASSING ROLE TO USER


SQL>GRANT RoleName TO UserName;

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.

Add New Datafile to an Existing Tablespace


SQL> alter tablespace tablespacename add datafile
'C:\oraclexe\oradata\XE\datafilename.DBF'
2 SIZE size in mb;

See Total Datafiles List


SQL> select file_name from dba_data_files;

23 | P a g e
See Total tablespace list
SQL> select tablespace_name from dba_data_files;

Remove Datafile from a tablespace


We can only remove a datafile from a tablespace when it have multiple datafiles in it.
Because it is mandatory for a tablespace to have at least one datafile in it.

SQL> alter tablespace tablespacename drop datafile


'C:\oraclexe\oradata\XE\datafilename.DBF';

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

SQL> insert all


2 into tablename values ()
3 into tablename values ()
4 into tablename values ()
5 select *from dual;

Example: -

(1) We are creating a table named tab1 and inserting 3 records at once.

SQL> insert all


2 into tab1 values (1, ‘ram’)
3 into tab1values (2,’shyam’)
4 into tab1 values (3,’laxman’)
5 select *from dual;

(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 we will grant tanu to ‘view’ the table of sr

SQL> connect sr/sr;


SQL> grant select on te1 to tanu; ‘Select’ is a permission to view only.
We can also use other permissions
like ‘insert’, ‘update’, ‘delete’.

Now Connect to tanu and view the table of sr by using this query

SQL> select *from sr.te1;

Revoke the permission from tanu : -

SQL> revoke select on te1 from tanu;

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;

REFERENTIAL INTEGRITY OR FOREIN KEY


Parent Table: -
SQL> create table student_add (roll_no number primary key, name
varchar2(50), city varchar2(10), mobile number (13), pin number (6));

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.

SQL> select fieldname "desired field name in output" from tablename;

Example: -

SQL> select adress "Home", name from student2;

SQL> select id+10 "New ID", name, adress "HOME" from


student2;

In this way, we can do calculations inside the query.

28 | P a g e
EQUI JOIN
In this join we use the equal operator.

SQL> Select fieldname, fieldname from table1, table2 where


table1.field = table2.field;

Example: -

DEPT EMPL

Between these two tables we will fetch the matching fields.


SQL> Select eno,ename ,dname from empl,dept where dept.dno=empl.dno;

29 | P a g e
NON EQUI JOIN
Here we use other operators like >, <, > =, < =, < > (Not Equals).

SQL> Select fieldname, fieldname from table1, table2 where


table1.field operator table2.field;

Example: -
(1)

DEPT EMPL

We will fetch the dno of the dept table which are greater than the dno in the empl table

SQL> Select eno,ename ,dname from empl,dept where


dept.dno>empl.dno;

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

So we will have total 0+2+3+3 = 8 records.

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

SQL> Select eno,ename ,dname from empl,dept where


dept.dno>empl.dno;

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

So we will have total 2+1+1+1 = 5 records.

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;

TABLE ALIAS i.e.; Table


Temporary New Names

SELF JOIN
In this join a table joins with itself with two different temporary names using table alias.

SQL> Select tablenamealias.fieldname , tablenamealias.fieldname from


tablename tablenamealias1 , tablename tablenamealias2 where
tablenamealias1.fieldname condition tablenamealias2.fieldname.

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;

SQL> select e1.eno, e2.ename, e1.dno from empl e1 , empl e2


where e1.eno > e2.eno;

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.

SQL> Select fieldname, fieldname, fieldname from table1


natural join table2;

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

SQL> Select *from table1, table2.


OR,

SQL> Select *from table1 cross join table2.

Example: -

DEPT EMPL

SQL> select *from empl, dept;


OR,

SQL> select *from empl cross join dept;

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,

SQL> Select *from left_table left outer join right_table on


left_table.matching_field = right_table.matching_field

Example: -

EMPL DEPT

SQL> select *from empl,dept where empl.dno=dept.dno (+);


OR,

Select *from empl left outer join dept on empl.dno=dept.dno;

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,

SQL> Select *from left_table right outer join right_table


on left_table.matching_field = right_table.matching_field

Example: -

EMPL DEPT

SQL> select *from empl,dept where empl.dno(+)=dept.dno;


OR,

Select *from empl right outer join dept on


empl.dno=dept.dno;

37 | P a g e
FULL OUTER JOIN
It returns all the tuples from both of the relations even if they are not matching.

SQL> Select *from left_table full outer join right_table on


left_table.matching_field = right_table.matching_field

Example: -

EMPL DEPT

SQL> select *from empl full outer join dept on


empl.dno=dept.dno;

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.

SQL> Select *from table1 where matching_field not in (Select


*from table2 where condition);

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.

SQL> Column column_name format format_statement;

Example: -

SQL> column salary format 9,99,999.99;


The values of the Salary column
will be separated by a comma.

SQL> column ename format a3 trunc;


It will show only the first three letters
of the values of the ename column

40 | P a g e
CLEAR COLUMN FORMATTING
SQL> clear column;
OR,
Restart the ‘Run SQL Command Line’

AGREEGATE FUNCTIONS IN ORACLE SQL

41 | P a g e
Example: -

(1) AVG

SQL> Select avg (salary) from empl;

(2) COUNT (X)

SQL> select count(salary) from empl;

(3) COUNT (*)


SQL> select count(*) from empl;

(4) COUNT (DISTINCT X)

SQL> select count (distinct salary) from empl;

(5) MAX(X)

SQL> select max(salary) from empl;

(6) MIN (X)

SQL> select min(salary) from empl;

42 | P a g e
(7) SUM (X)

SQL> select sum(salary) from empl;

(8) STDDEV (X)

SQL> select stddev(salary) from empl;

(9) VARIANCE (X)

SQL> select variance (salary) from empl;

CHARACTER FUNCTIONS IN ORACLE

. Here White Spaces are also counted

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.

SQL> insert into birth values ('Suman', to_date('2003-march-21',


'yyyy-mm-dd' ));

TO_CHAR
If we want to see only specific part.

SQL> select name,to_char (dob , 'mm') from birth;

SQL> select name,to_char (dob , 'yyyy') from birth;

SQL> select name,dob from birth where to_char (dob,'q')='3';

(because July is in quarter 3)

47 | P a g e
Quarter Division of Months

Q1 – January, February, March


Q2 – April, May, June
Q3 – July, August, September
Q4 – October, November, December

NVL
It fills default value in the null fields.

SQL> Select fieldname, fieldname nvl(fieldname , default_value) from


tablename;

Example: -

SQL> select eno,ename, eno, nvl(salary , 60000) from empl;

48 | P a g e
DECODE
Decode Function is used to expand a small abbreviation.

SQL> select field, decode (field_to_be_decoded, 'small_name',


'full_name','NOT SPECIFIED')"new_column_name" from tablename;

Example: -

SQL> select name, city, decode (city, 'ADA', 'ADRA' , 'DHN' ,


'DHANBAD' , 'RNP' , 'RAGHUNATHPUR','NOT SPECIFIED')"DECODED CITY" from
city;

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;

SQL COMMAND TYPES IN ORACLE

51 | P a g e
SQL BUFFER COMMANDS
Buffer Stores the Number of Lines in a query.

TO SEE THE LINES


SQL> L;

TO SELECT A LINE AS THE NEWLINE


SQL> line_number;

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)

SQL> Input this is the inserted new line

DELETE A LINE
Select the Line and
SQL> del

Example: -

SQL> 2 (Selects 2 as the new line)

SQL> del (Deletes the line)

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

CHANGE SPECIFIC STRING IN THE QUERY


Select the line and
SQL> Change / string_to_be_changed / changed_string

Example: -
SQL>1 (Selects the line 1 as the newline)
SQL> Change / *, from empl / id , name

RUN THE BUFFER COMMAND


SQL> /

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 1 – Run as Administrator

STEP 3 – Execute any Command and then, SQL> ed. Now a buffer notepad file will be created

STEP 5 – Same Change will be shown in the


STEP 4 – Change in the notepad file command line and execute it using55
‘ / |‘ .P a g e
NOT NULL CONSTRAINT
If we create a field as not null then we can’t insert null value in that. We can make multiple
columns as not null.
SQL> Create table tablename (fieldname datatype not null);

Example: -
SQL> create table demo1 (id number, name varchar2(15) not null);
[Here the name field is not null]

We can store null value in ID

But we can’t store null value in name


iID

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.

SQL> Create table tablename (fieldname datatype unique);

Example: -
SQL> create table demo (id number unique, name varchar2(15));
[Here the ID field is unique]

The Name field can store duplicate values

The ID field can’t store duplicate values

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.

SQL> Create Table tablename (fieldname datatype primary key);

Example: -
SQL> create table parent (parent_id number primary key, parent_name
varchar2(15) not null, city varchar2(10));

Primary Key is Not Null

Unique value can be inserted

But it can’t store duplicate values


58 | P a g e
FOREIGN KEY
Foreign key is used to make relationship between two tables. The foreign key of a table points to
the primary key of another table.
A Foreign key –
• Can be Null.
• Can have duplicate values.
• It accepts only those value which are available on the parent / base table
We can make foreign key in two methods –

(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 ]

This is the Parent Table

SQL> alter table child add constraint fk_parentchild foreign


key(parent_id) references parent(parent_id);

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.

(Check Constraint in Create Table)


SQL> Create Table tablename (fieldname datatype, constraint
constraint_name check (condition));

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

We can insert name in Uppercase

We cannot insert name without Uppercase

(Check Constraint in Alter Table)


Normally Create a Table
Now,
SQL> alter table tablename add constraint constraint_name check
(condition)

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

Temporarily Disable the Constraint: -


SQL> alter table tablename disable constraint constraint_name;

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]

Drop the Constraint Permanently: -


SQL> alter table tablename drop constraint constraint_name;

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.

SQL> Select fieldname from tablename group by fieldname.

Example: -

65 | P a g e
SQL> select product from orders group by product;
[ It groups the products]

SQL> select product,count(sale) from orders group by product;


[ It counts the number of sale of a product ]

SQL> select product,sum(sale) from orders group by product;


[ It counts the total sale of a product ]

SQL> select product,min(sale) from orders group by product;


[ It displays the minimum price of a product ]

SQL> select product,max(sale) from orders group by product;


[ It displays the maximum price of a product ]

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.

SQL> Select fieldname from tablename group by fieldname having


condition.

Example: -

(1) SQL> select product, sum(sale) from orders group by product


having sum(sale)>2000;

[The product which has a sale of greater than rupees 2000 will be selected]

(2) SQL> select product, count(sale) from orders group by product


having count(sale)>=4;

[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).

SQL> select *from table1 union select *from table2;

Example: -

emp2013 emp2014

SQL> select *from emp2013 union select *from 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).

SQL> select *from table1 union all select *from table2;

Example: -

emp2013 emp2014

SQL> select *from emp2013 union all select *from emp2014;

It does not remove


the duplicates.

71 | P a g e
INSTERSECT
It returns the tuples which are present in both of the tables.

SQL> select *from table1 intersect select *from table2;

Example: -

emp2013 emp2014

SQL> select *from emp2013 intersect select *from emp2014;

72 | P a g e
MINUS
It selects the tuples which are present in the first table but not in the second table.

SQL> select *from table1 minus select *from table2;

Example: -

emp2013 emp2014

SQL> select *from emp2013 minus select *from emp2014;

3 Tanumoy 50000

Is present in the seond table. So it is removed.

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.

Make a .sql or .txt file in notepad.


Now,
SQL> Start file location (use ‘/’) / filename;

Example: -

SQL> start F:/PROGRAMMING/SQL/cmd.sql;

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

You might also like