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

Oracle SQL Queries

Uploaded by

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

Oracle SQL Queries

Uploaded by

soul killer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Oracle(SQL Queries)

**********************Query to create table************************


Syntax
Create table tablename(column1 datatype, column2 datatype(size), column3
datatype(size)……………column n);
Example
Create table supplier1(supplierid int, suppliername varchar(255),
supplieraddress varchar(255), suppliercontactno varchar(50), suppliercity
varchar(255));

****************Query to insert data into table********************


Syntax
Insert into tablename(column1, column2, …….) values(value1, value2,….);
Example
Insert into supplier1(supplierid, suppliername, supplieraddress,
suppliercontactno, suppliercity) values(‘1’, ‘abc’, ‘navrangpura’,
‘999999’,’ahmedabad’);
Likewise….
=========Insert n number of records==========

****************Use of Select Keyword********************


Select suppliername, supplieraddress, suppliercity from supplier1 where
supplierid = ‘1’;
****************Query to update data into table********************
Syntax
Update tablename set columnname = ‘value’ where condition;

Example
Update supplier1 set suppliername = ‘bcd’ where supplierid = ‘1’;
****************Query to add column in table********************
Syntax
ALTER TABLE table_name add columnname datatype(size);
Example
Alter table supplier1 add supplieremail varchar2(255);

****************Query to drop column in table********************


Syntax
ALTER TABLE table_name drop column columnname;
Example
Alter table supplier1 drop column suppliercity;

****************Query to delete record in a Table********************


Syntax
Delete from table_name where condition;
Example
Delete from supplier1 where supplierid = ‘1’;

****************Use of Distinct********************
Select distinct suppliername from supplier1 where supplierid = ‘1’;
*******To find ascii value corresponding to a particular character******
Select ascii(‘A’) Big_A, ascii(‘z’) small_z, ascii(‘ ‘) from supplier1;
Output

Big_A small_z Ascii(‘ ‘)


65 122 32

***********Query to merge two columns**************


Select concat(‘Bhoomi’, ‘Parikh’ from supplier1;
Or
Select ‘Bhoomi’ || ‘Parikh’ || ‘Ahmedabad’ from supplier1;

**********To capitalize first character of a column***********


Select suppliername, initcap(suppliername) suppliername_example from
supplier1;

*********To find length of all records in a column************


Select suppliername, length(suppliername) suppliername_length from supplier1;

*********To find character corresponding to a numeric value*********


Select chr(65), chr(122), chr(255) from supplier1;

*********To convert entire column into lowercase*********


Select suppliername, lower(suppliername) lowercase_suppliername from
supplier1;

***********Use of LPAD************
 LPAD(c1, i [,c2]) takes three arguments, where c1 and c2 are character
strings and i is an integer.
 This function returns the character string c1 expanded in length to i
characters, using c2 to fill in space as needed on the left side of c1.
Example
select lpad(suppliername, 10) lpad_lname, lpad(suppliercity,8,1)
lpad_suppliercity from supplier1where suppliername like 'd%';

*********Use of Ltrim**********
 LTRIM(c1 [,c2]) takes two arguments, where c1 and c2 are character
strings.
 This function returns c1 without any leading characters that appear in c2.
 If no c2 characters are leading characters in c1, then c1 is returned
unchanged.
 c2 defaults to a single space.
Example
Select ltrim(‘Mississippi’, ‘Mis’) from supplier1;

********Use of Replace********
 REPLACE(c1, c2 [,c3]) takes three arguments, where c1, c2, and c3 are
character strings.
 This function returns c1 with all occurrences of c2 replaced with c3.
Example
select replace ('uptown', 'up', 'down') from supplier1;

**********Use of RPad***********
 RPAD(c1, i [, c2]) takes three arguments, where c1 and c2 are character
strings and i is an integer.
 This function returns the character string c1 expanded in length to i
characters, using c2 to fill in space as needed on the right side of c1.

select rpad(suppliername, 15, '-') rpad_suppliername, lpad(supplierid,12,' ')


lpad_supplierid from supplier1 where suppliername like 'd%';
***********Use of Rtrim***********

SELECT RTRIM('Mississippi','ip') from supplier1;

*********Use of Substr*********
select substr('The Three Musketeers', 1,3)Part1, substr('The Three
Musketeers',5,5)Part2, substr('The Three Musketeers',11)Part3, substr('The Three
Musketeers',-5)Part4 from salesstore1;

*********Use of nvl***********
 The NVL function is used to replace a NULL value with a literal value.
 NVL takes two arguments, NVL(x1, x2), where x1 and x2 are expressions.
 The NVL function returns x2 if x1 is NULL.
 If x1 is not NULL, then x1 is returned.

 For Example:
 Select NVL(100,200) from dual; returns 100(literal value)
 Select NVL(NULL, ‘abc’) from dual; abc
 Select NVL(‘abc’,NULL) from dual; abc

*******Use of nvl2(null value)********


--use of nvl2
--assume that (null,1,2) are three arguments corresponding to e1,e2 and e3
--if e1 is not null then argument will be incremented and e2 will be printed.
--if e1 is null then directly e3 will be printed.
--Here storeid is null so condition is true therefore value in third argument
will be printed.

select nvl2(1,'abc','999999') from supplier1;

********Use of translate********

SELECT suppliername, TRANSLATE(suppliername, 'aeiou', '*#$') no_vowel


FROM supplier1 WHERE suppliername like 'a%';
*********Use of upper*********
Select upper(‘abc’) from supplier1;

*********Use of coalesce*********
If x1 is not NULL, then
Return x1
Else
Check x2
If x2 is not NULL, then
Return x2
Else
Check x3
If x3 is not NULL, then
Return x3
Else
Return NULL
End If
End If
End If

SELECT COALESCE(NULL,1)FROM supplier1;

SELECT COALESCE(NULL,'A','B') result FROM supplier1;

***********Use of BITAND************

SELECT BITAND(6,3) result FROM supplier1;

*********Use of Ceil*********
SELECT CEIL(9.8), CEIL(0), CEIL(5) FROM supplier1;
*********Use of Floor********
SELECT FLOOR(9.8), FLOOR(137) FROM supplier1;
********Use of Round*******
select round(123.489), round(123.489,2) from supplier1;
*********Use of Modulus********
select mod(14,5) from supplier1;
*********Use of SQRT*********
select sqrt(64), sqrt(49), sqrt(81) from supplier1;
*********Use of truncate********
select trunc(123.489), trunc(123.489,2), trunc(123.489,-2), trunc(1275,-2) from
salesstore1;
********Use of Sysdate*********
select sysdate from dual;
********Use of timestamp*********
select sysdate, systimestamp from supplier1;
********To add months*********
select sysdate, add_months(sysdate, -1) prev_month, add_months(sysdate,12)
next_year from dual;
*******Adding current date********
select sysdate, current_date from dual;
*******Adding Timestamp******
select current_date, current_timestamp from dual;
******Extracting year from sysdate*******
select sysdate,extract(year from sysdate) year from dual;
*******SessionTimeZone*******
Select SESSIONTIMEZONE FROM dual;
*******To extract last day and next month last day******
Select sysdate, last_day(sysdate) end_of_month, last_day(sysdate)+1
next_month from dual;
*****To select next day from current day*****
Select sysdate, next_day(sysdate,’Fri’) from dual;
*****To round nearest time*****
Select sysdate, round(sysdate,’HH24’) from dual;
*****Conversion from binary to number*****
Select bin_to_num(1,1,0,1) bitfield1, bin_to_num(0,0,0,1) from dual;

*****Conversion from yeartomonth interval*****


SELECT SYSDATE, SYSDATE+NUMTOYMINTERVAL(2,’YEAR’)”2
years later”, SYSDATE+NUMTOYMINTERVAL(5,’MONTH’) “5 MONTHS
LATER” from dual;
*****Conversion from numtohour/minute interval*****
SELECT SYSDATE,SYSDATE+NUMTODSINTERVAL(2,’HOUR’)”2
HOURS LATER”, SYSDATE+NUMTODSINTERVAL(30,’MINUTE’)”30
MINUTES LATER” FROM DUAL;
*****Conversion from rowidtochar*****
SELECT ROWIDTOCHAR(ROWID) CHARROWID, first_name from
employees where first_name = ‘abc’;
*****Use of nullif*****
Nullif takes two arguments where x1 and x2 are expressions
The function returns null if x1 equals x2,
otherwise it returns x1,
if x1 is null. nullif returns x1.
Select nullif(100,100) from dual-returns null
Select nullif(100,200) from dual- returns 100
*****Use of group by clause*****
The group by clause is used to select statement to group rows into a set of
summary rows by values of columns or expressions.
Note: The group by clause returns one row per group.
The group by clause is used with aggregate functions such as avg(), count(),
max(), min() and sum().
Consider following database:
Orders Table:
Customer_id Order_id Status Salesman_id Order_date
1 1 Shipped 1 15/11/2023
1 2 Pending 2 16/11/2023
1 3 Canceled 3 17/11/2023
1 4 Pending 4 18/11/2023
2 1 Shipped 5 19/11/2023
2 2 Canceled 6 20/11/2023
3 1 Shipped 7 21/11/2023
4 1 Canceled 8 22/11/2023
4 1 Pending 9 23/11/2023
5 1 Shipped 10 24/11/2023

*** Using group by clause to find unique order statuses***


Select status from orders group by status;
Output
Shipped

Pending

Canceled

***Using group by clause with count aggregate function


Select customer_id, count(order_id) from orders group by customer_id order by
customer_id;
Customer_id Order_id
1 4
2 2
3 1
4 2
5 1
Consider employees table
Id Name Department Salary Gender Commission City
1001 John IT 35000 Male 3500 London
1002 Smith HR 45000 Female 4500 Mumbai
1003 James Finance 50000 Male 5000 Delhi
1004 Mike Finance 50000 Male NULL London
1005 Linda HR 75000 Female NULL Mumbai
1006 Anurag IT 35000 Male NULL London
1007 Priyanka HR 45000 Female NULL Mumbai
1008 Sambit IT 55000 Male 5500 London
1009 Pranaya IT 57000 Male 5700 London
1010 Hina HR 75000 Female 7500 Mumbai

***Use of group by clause with aggregate sum function in oracle***


Select sum(salary) as total salary from employee;
Output
522000
Select department, sum(salary) as total salary from employee group by
department.
Department Total Salary
HR 240000
IT 182000
Finance 100000

***Use of group by clause with max and min function in oracle***


Select department, max(salary) as maxsalary, min(salary) as minsalary from
employee group by department;
Department Max Salary Min Salary
HR 75000 45000
IT 57000 35000
Finance 50000 50000

***Use of group by clause with avg function in oracle***


Select department, avg(salary) as average salary from employee group by
department;
Department Average Salary
HR 60000
IT 45500
Finance 50000

***Use of group by clause with having statement and sum function***


Consider salesdepartment database
ItemName Sale Billing_address
Shoes 120 Agra
Belts 105 Kolkata
Shoes 45 Allahabad
Sari 210 Varanasi
Sari 5000 Chennai
Medicines 250 Salem
Computer 210 Delhi
Shoes 1000 Kanpur

Select itemname, sum(sale) as “total sales” from salesdepartment group by


itemname having sum(sale) <1000;
Output:
Itemname Total Sales
Belts 105
Medicines 250
Computer 210

***Use of group by clause with where and having***


Select billing_address, count(*) as number of items from salesdepartment where
sale>100 group by billing_address having count(*)>=2;
Output
Billing_address Number of items
Agra 1
Kolkatta 1
Varanasi 1
Chennai 1
Salem 1
Delhi 1
Kanpur 1

***Use of group by clause with MIN Function***


Consider employees database

Emp_id Name Age Department Salary


1 Aladin 21 Mechanical 12000
2 Billu 23 Hardware 15000
3 Chhaya 22 Software 24000
4 Dinesh 34 Software 32000
5 Ramesh 21 Software 20000
6 lalu 18 Software 10000

Select department, min(salary) as “lowest salary” from employees group by


department having min(salary)<15000;
Department Lowest Salary
Mechanical 12000
Software 10000
***Use of group by function with MAX Function***
Select department, max(salary) as “highest salary” from employees group by
department having max(salary)>30000;
Department Highest Salary
Software 32000

***Use of group by function with order by clause***


Select department, sum(salary) as “total salary” from employees group by
department order by department desc;
Department Sum
Software 86000
Mechanical 12000
Hardware 15000

***Inner Join Example***


Create Suppliers Table
SupplierID SupplierName SupplierAddress
1 Bata shoes Agra
2 Kingfisher Delhi
3 Vojo Lucknow

Create Order1 Table


Ordernumber Supplierid City
101 1 Allahabad
102 2 Kanpur

Select suppliers.supplierid, suppliers.suppliername, order1.ordernumber


From suppliers inner join order1 on suppliers.supplierid = order1,supplierid;
Output:
Supplier_id Supplier_name Order_number
1 Bata shoes 101
2 Kingfisher 102
***Left Outer Join Example***
Consider Table Purchaser
PurchaserID PurchaserName PlotNo ServiceId
1 Sam 12 1001
2 Pill 13 1002
3 Don 14 1003
4 Brock 15 1004

Consider Table Seller


ServiceId Seller_name Seller_Email
1001 Big Show [email protected]
1002 Gem [email protected]
1003 Matt [email protected]

Select serviceid, sellername, purchasername, plotno from purchaser left outer


join seller on purchaser.serviceid = seller.serviceid;

Output
ServiceId Seller_name Purchasername PlotNo
1001 Big Show Sam 12
1002 Gem Pill 13
1003 Matt Don 14
1004 Null Brock 15

***Right Outer Join*** Example


Select serviceid, sellername, purchasername, plotno from purchaser right outer
join seller on purchaser.serviceid = seller.serviceid;

Output
ServiceId Seller_name Purchasername PlotNo
1001 Big Show Sam 12
1002 Gem Pill 13
1003 Matt Don 14
***Full Outer Join Example***
Select serviceid, sellername, purchasername, plotno from purchaser full outer
join seller on purchaser.serviceid = seller.serviceid;
ServiceId Seller_name Purchasername PlotNo
1001 Big Show Sam 12
1002 Gem Pill 13
1003 Matt Don 14
1004 Null Brock 15

***Cross Join Example***


Select serviceid, sellername, purchasername, plotno from purchaser cross join
seller;
Serviceid Seller_name Purchasername PlotNo
1001 Big Show Sam 12
1001 Big Show Pill 13
1001 Big Show Don 14
1001 Big Show Brock 15
1002 Gem Sam 12
1002 Gem Pill 13
1002 Gem Don 14
1002 Gem Brock 15
1003 Matt Sam 12
1003 Matt Pill 13
1003 Matt Don 14
1003 Matt Brock 15

**********************All The Best**************************

You might also like