100% found this document useful (1 vote)
626 views

SQL Queries

The document contains SQL statements for querying data from an emp table. It includes statements to select data, filter on conditions, order results, aggregate functions, insert/update/delete records, create/drop tables and indexes, and more. A variety of SQL functions are also demonstrated like INITCAP, SUBSTR, TRIM, etc. Connected queries and common table expressions are shown.

Uploaded by

Payal Chatterjee
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
626 views

SQL Queries

The document contains SQL statements for querying data from an emp table. It includes statements to select data, filter on conditions, order results, aggregate functions, insert/update/delete records, create/drop tables and indexes, and more. A variety of SQL functions are also demonstrated like INITCAP, SUBSTR, TRIM, etc. Connected queries and common table expressions are shown.

Uploaded by

Payal Chatterjee
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

select * from emp;

select distinct country from emp;


select count(distinct country) from emp;
select * from emp where country ="India";
select empname from emp where country="India" and city ="kolkata";
select empname from emp where country ="india" or country ="germany";
select empname from emp where not country ="india" and not country ="germany";
select empname ,empid from emp where country = "india" and (city ="kolkata" or city
= "delhi");
select * from emp order by country
select * from emp order by country desc
select * from emp order by country asc,empname desc
insert into emp(empname,empid,empadd) values ("mitra",1111,"Abc")
insert into emp(emp_name,empid,empadd) select emp_name,empid,empadd from emp1;
select * from emp where country is not null;
select * from emo where country is null;
update emp set empsal = empsal+1000 where empid =1000;
delete from emp where empid =1000;
select top 3 * from emp;
select * from emp where rownum<= 3;
select Min(price) as minprice from emp;
select Max(price) as maxprice from emp;
select Avg(price) as avgprice from emp;
select sum(price) as sumprice from emp;
select * from emp where empname like '%a"; ----ends with a
select * from emp where empname like 'a%"; ----starts with a
select * from emp where empname like '_a%"; ----a in second position
select * from emp where empname like 'a%o"; ----starts with a and ends with o
select * from emp where empname like 'a_%_%"; ----starts with a and 3 char long
select * from emp where country in ("germany","india","us");
select * from emp where country not in ("germany","india","us");
select * from emp where country in (select * from supp);
select * from emp where dept between 10 and 20;----Range of values
select * from emp where sal between 1000 and 2000 and designation not in
("mgr","chairman");
select city from cust union select city from suppliers-----only distinct values
select city from cust union all select city from suppliers ----dups also
select * from orders where quantity between 1 and 100 except select * from orders
where quantity between 50 and 100----returns 1-50(without dup). Use except all for
dup
select * from orders where quantity between 1 and 50 intersect select * from orders
where quantity between 50 and 100 ----returns 50-100 without dup(use intersect all
for dup)
select count(empid) , country from emp groupby country orderby desc
selct count(empid) , country from emp groupby country having count(empid) > 5----
where cannot be used with aggregate funct so having
select suppliername from suppliers where exists(select productname from product
where productid is 20)--returns boolen
select suppliername from suppliers where productname = any(select productname from
product where productid = 20)
select suppliername from suppliers where productname = all(select productname from
product where productid = 20)
select * into emp from dept;
create database db;
drop database db;
create table abc(empname varchar2(2000),
enmp_id int)

drop table abc


alter table abc add column emp_mgr varchar2(2000)
alter table abc drop column emp_mgr
alter table abc alter column emp_name varchar
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

CREATE TABLE Orders (


ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);

create index abc on emp(emp_id,emp_name)


create view abc as select emp_name,emp_id from emp;

---oracle funct

initcap("MTADROO MITRA")--result Mitadroo Mitra


initcap("mitadroo mitra") --- result Mitadroo Mitra
Instr("Mitadroo Mitra" ,a) ----1st occurence of a result 4
instr("mitadroo mitra" , a, 1,1)----the string search starts from the first char
1st occurence of a result 4
instr("mitadroo mitra" , a, 1, 2)---- the second occuerence of a
substr("mitadroo is a good boy" ,6) ----roo is a good boy
substr("mitadroo is a good boy" ,6,3)----roo
substr("mitadroo is a good boy" ,-6,3)----od(from 6 places from end )
trim(' mitadroo ' )-----trims blank spaces from both sides
trim (' ' from ' mitadroo ')
trim(LEADING '0' from'00123')---123
rtrim()---removes from end
lpad---add something from start
RPAD('tech', 8, '0')
Result: 'tech0000'

ALTER TABLE [dbo].[USER_PROFILE] ALTER COLUMN EMP_ID


ADD MASKED WITH (FUNCTION = 'partial(1, "XXXXX", 0)');

ALTER TABLE [dbo].[USER_PROFILE] ALTER COLUMN Email


ADD MASKED WITH (FUNCTION = 'email()');

select * from [dbo].[USER_PROFILE] where Email like '%@%'

Contains is equivalent of like but performance faster for clob storage

select * from abc where contains(name,'%a%e' )>0 ----where name column conatins
this regular exp. It is helpfull if we create context index with name column

Clob for large text data


blob for image,video etc
WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'

Hierachical Query

SELECT
CONCAT
(
LPAD
(
' ',
LEVEL*3-3
),
ENAME
) ENAME
FROM
EMP
CONNECT BY
PRIOR EMPNO = MGR
START WITH
MGR IS NULL
ORDER SIBLINGS BY
EMP.ENAME;

output

ENAME
----------------
KING
BLAKE
ALLEN
JAMES
MARTIN
TURNER
WARD
CLARK
MILLER
JONES
FORD
SMITH
SCOTT
ADAMS
---------------------------------
SELECT empno,
ename,
job,
mgr,
hiredate,
level
FROM emp
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
Gets me this result
7839 KING PRESIDENT 17-Nov-81 1
7566 JONES MANAGER 7839 2-Apr-81 2
7788 SCOTT ANALYST 7566 19-Apr-87 3
7876 ADAMS CLERK 7788 23-May-87 4
7902 FORD ANALYST 7566 3-Dec-81 3
7369 SMITH CLERK 7902 17-Dec-80 4
7698 BLAKE MANAGER 7839 1-May-81 2
7499 ALLEN SALESMAN 7698 20-Feb-81 3
7521 WARD SALESMAN 7698 22-Feb-81 3
7654 MARTIN SALESMAN 7698 28-Sep-81 3
7844 TURNER SALESMAN 7698 8-Sep-81 3
7900 JAMES CLERK 7698 3-Dec-81 3
7782 CLARK MANAGER 7839 9-Jun-81 2
7934 MILLER CLERK 7782 23-Jan-82 3

SELECT empno,
ename,
job,
mgr,
hiredate,
LEVEL
FROM emp
WHERE LEVEL <= 2
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
empno ename job mgr hiredate level
7839 KING PRESIDENT 17-Nov-81 1
7566 JONES MANAGER 7839 2-Apr-81 2
7698 BLAKE MANAGER 7839 1-May-81 2
7782 CLARK MANAGER 7839 9-Jun-81 2

SELECT Lpad(ename,Length(ename) + LEVEL * 10 - 10,'-')


FROM emp
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr

KING
----------JONES
--------------------SCOTT
------------------------------ADAMS
--------------------FORD
------------------------------SMITH
----------BLAKE
--------------------ALLEN
--------------------WARD
--------------------MARTIN
--------------------TURNER
--------------------JAMES
----------CLARK
--------------------MILLER

CTE SQL Server


-----------
WITH
cteTotalSales (SalesPersonID, NetSales)
AS
(
SELECT SalesPersonID, ROUND(SUM(SubTotal), 2)
FROM Sales.SalesOrderHeader
WHERE SalesPersonID IS NOT NULL
AND OrderDate BETWEEN '2003-01-01 00:00:00.000'
AND '2003-12-31 23:59:59.000'
GROUP BY SalesPersonID
),
cteTargetDiff (SalesPersonID, SalesQuota, QuotaDiff)
AS
(
SELECT ts.SalesPersonID,
CASE
WHEN sp.SalesQuota IS NULL THEN 0
ELSE sp.SalesQuota
END,
CASE
WHEN sp.SalesQuota IS NULL THEN ts.NetSales
ELSE ts.NetSales - sp.SalesQuota
END
FROM cteTotalSales AS ts
INNER JOIN Sales.SalesPerson AS sp
ON ts.SalesPersonID = sp.BusinessEntityID
)
SELECT
sp.FirstName + ' ' + sp.LastName AS FullName,
sp.City,
ts.NetSales,
td.SalesQuota,
td.QuotaDiff
FROM Sales.vSalesPerson AS sp
INNER JOIN cteTotalSales AS ts
ON sp.BusinessEntityID = ts.SalesPersonID
INNER JOIN cteTargetDiff AS td
ON sp.BusinessEntityID = td.SalesPersonID
ORDER BY ts.NetSales DESC

CTE ORACLE
----------------

with cte (dt) as (


select add_months(trunc(sysdate), -1) as dt
from dual
union all
select cte.dt+1
from cte
where
cte.dt+1 < sysdate
)
select * from cte;

Cte is a named tempopary result set which can be used multiple times within the
scope of the single statement
with
cte1 as (select a,b from table1),
cte2 as (select c,d from table2)

select b,d from cte1 join cte2


where cte1.a=cte2.b;

Inline view
----------------

An inline view is a SELECT statement in the FROM-clause of another SELECT


statement. In-line views are commonly used to simplify complex queries by removing
join operations and condensing several separate queries into a single query. This
feature was introduced in Oracle 7.2.
This feature is commonly referred to in the MSSQL community as a derived table, and
in the Postgres community simply refers to it as a subselect (subselects are inline
views + subqueries in Oracle nomenclature).
Examples[edit]

Example inline view:


SELECT *
FROM ( SELECT deptno, count(*) emp_count
FROM emp
GROUP BY deptno ) emp,
dept
WHERE dept.deptno = emp.deptno;

Highest sal in each dept and inline view


-------------------------------------------------

SELECT a.last_name, a.salary, a.department_id, b.maxsal


FROM employees a,
( SELECT department_id, max(salary) maxsal
FROM employees
GROUP BY department_id ) b
WHERE a.department_id = b.department_id
AND a.salary = b.maxsal;

Derived TABLE
---------------------------

https://logicalread.com/when-to-apply-sql-server-derived-tables-mc03/#.Wa-A2MgjHIU

Diff between Blob and Clob


=====================================

BLOB is for binary data (videos, images, documents, other)

CLOB is for large text data (text)

Maximum size on MySQL 2GB

Maximum size on Oracle 128TB

Json in oracle
====================================

{ "PONumber" : 1600,
"Reference" : "ABULL-20140421",
"Requestor" : "Alexis Bull",
"User" : "ABULL",
"CostCenter" : "A50",
"ShippingInstructions" : { "name" : "Alexis Bull",
"Address": { "street" : "200 Sporting Green",
"city" : "South San Francisco",
"state" : "CA",
"zipCode" : 99236,
"country" : "United States of America" },
"Phone" : [ { "type" : "Office", "number" : "909-555-
7307" },
{ "type" : "Mobile", "number" : "415-555-
1234" } ] },
"Special Instructions" : null,
"AllowPartialShipment" : false,
"LineItems" : [ { "ItemNumber" : 1,
"Part" : { "Description" : "One Magic
Christmas",
"UnitPrice" : 19.95,
"UPCCode" : 13131092899 },
"Quantity" : 9.0 },
{ "ItemNumber" : 2,
"Part" : { "Description" : "Lethal Weapon",
"UnitPrice" : 19.95,
"UPCCode" : 85391628927 },
"Quantity" : 5.0 } ] }

CREATE TABLE j_purchaseorder


(id RAW (16) NOT NULL,
date_loaded TIMESTAMP WITH TIME ZONE,
po_document CLOB
CONSTRAINT ensure_json CHECK (po_document IS JSON));

INSERT INTO j_purchaseorder


VALUES (SYS_GUID(),
SYSTIMESTAMP,
'{"PONumber" : 1600,
"Reference" : "ABULL-20140421",
"Requestor" : "Alexis Bull",
"User" : "ABULL",
"CostCenter" : "A50",
"ShippingInstructions" : {...},
"Special Instructions" : null,
"AllowPartialShipment" : true,
"LineItems" : [...]}');

SELECT po.po_document.ShippingInstructions.Phone FROM j_purchaseorder po;


SELECT po.po_document.ShippingInstructions.Phone.type FROM j_purchaseorder po;

SELECT jt.*
FROM j_purchaseorder,
JSON_TABLE(po_document, '$.ShippingInstructions.Phone[*]'
COLUMNS (row_number FOR ORDINALITY,
phone_type VARCHAR2(10) PATH '$.type',
phone_num VARCHAR2(20) PATH '$.number'))
AS jt;
ROW_NUMBER PHONE_TYPE PHONE_NUM
---------- ---------- --------------------
1 Office 909-555-7307
2 Mobile 415-555-1234

select emono,empname,sal,avg(sal) over (Pratition by deptno) as avg_dept_sal from


emp

Use of Package in oracle


====================================

Cohesion: all the procedures and functions relating to a specfic sub-system are in
one program unit. This is just good design practice but it's also easier to manage,
e.g. in source control.
Constants, sub-types and other useful things: there's more to PL/SQL than stored
procedures. Anything we can define in a package spec can be shared with other
programs, for instance user-defined exceptions.
Overloading: the ability to define a procedure or function with the same name but
different signatures.
Security: defining private procedures in the package body which can only be used by
the package because they aren't exposed in the specification.
Sharing common code: another benefit of private procedures.
We only need to grant EXECUTE on a package rather than on several procedures.

Difference between count(*),count(1),count(0)


===================================================

COUNT(*) returns the number of items in a group. This includes NULL values and
duplicates.
COUNT(1) returns the number of items in a group. This includes NULL values and
duplicates.
COUNT(ALL expression) evaluates expression for each row in a group and returns the
number of nonnull values.
COUNT(DISTINCT expression) evaluates expression for each row in a group and returns
the number of unique, nonnull values.

Different types of Subquery


============================================

https://www.oracletutorial.com/oracle-basics/oracle-subquery/

Natural Join
======================================================

https://www.w3resource.com/oracle/joins/natural-join.php

Difference between inner join and natural join


=============================================================

https://stackoverflow.com/questions/8696383/difference-between-natural-join-and-
inner-join
Delete duplicate record
==================================================================

With CTE_Duplicates as
(select empid,name , row_number() over(partition by empid,name order by
empid,name ) rownumber
from EmpDup )
delete from CTE_Duplicates where rownumber!=1

Merge in oracle
=========================================================================

Most common use is upsert

SQL> select * from student;

ID NAME SCORE
---------- --------------- ----------
1 Jack 540
2 Rose
3 William 650
4 Caledon 620
5 Fabrizio 600
6 Thomas
7 Ruth 680
8 Spacer 555

8 rows selected.

SQL> select * from student_n;

ID NAME SCORE
---------- --------------- ----------
7 Ruth 690
8 Spicer 620
9 Wallace 600
10 Lizzy
11 Brock 705

As you can see, the following actions are required on table STUDENT:

1 row for id#7 to be corrected for score: Ruth had scored 690, not 680.
1 row for id#8 to be corrected for name: the student is called Spicer, not Spacer.
3 new rows (ids#9,10,11) to be inserted into STUDENT table.
5 rows should get processed in all.

SQL> merge into student a


2 using
3 (select id, name, score
4 from student_n) b
5 on (a.id = b.id)
6 when matched then
7 update set a.name = b.name
8 , a.score = b.score
9 when not matched then
10 insert (a.id, a.name, a.score)
11 values (b.id, b.name, b.score);

5 rows merged.

SQL> select * from student;

ID NAME SCORE
---------- --------------- ----------
1 Jack 540
2 Rose
3 William 650
4 Caledon 620
5 Fabrizio 600
6 Thomas
7 Ruth 690
11 Brock 705
10 Lizzy
9 Wallace 600
8 Spicer 620

11 rows selected.
Sure enough, 5 rows have got merged as expected � 2 updates + 3 inserts.

MERGE in 10G supports insert-only and update-only operations.

You cannot update any of the columns you are merging on. If you try updating a
student�s id in the example above, this error will show up in 10G:

ORA-38104: Columns referenced in the ON Clause cannot be updated

delete after update in merge read from https://www.oratable.com/oracle-merge-


command-for-upsert/

Sum of positive and negative numbers in a column separately


========================================================================

select sum (case when acolumn >= 0 then acolumn else 0 end) as positive,
sum (case when acolumn < 0 then acolumn else 0 end) as negative
from table

;WITH Psum_CTE
AS
( SELECT SUM(num) AS PositiveSum
FROM sample
WHERE num>=0
)
,Nsum_CTE
AS
(
SELECT SUM(num) AS NegativeSum
FROM sample
WHERE num<0
)

SELECT PositiveSum,NegativeSum
FROM Psum_CTE,Nsum_CTE

Query to display if two has same value


================================================

ID Address State Name


-------------------------------
0 7 Brown NY John
1 3 Red WX Jane
2 7 Brown WX Ted
3 7 Brown NY Fred

My question would be:

Find all ID's for rows where the row's Address and State field matched another
row's Address and State field.

The answer to this query would be:

ID Address State Name


------------------------------
0 7 Brown NY John
3 7 Brown NY Fred

SELECT A.*
FROM YourTable A
INNER JOIN (SELECT Address, State
FROM YourTable
GROUP BY Address, State
HAVING COUNT(*) > 1) B
ON A.Address = B.Address AND A.State = B.State

How to check if two tables are identical

====================================================

select count(*) from


(
(select * from dept1
minus
select * from dept2)
unionall
(select * from dept2
minus
select * from dept1)
)

will tell you how many rows are in dept1 not in dept2 + in dept2 not in dept1

Lead and Lag


============================================================

https://oracle-base.com/articles/misc/lag-lead-analytic-functions

You might also like