You are on page 1of 17

how to search user in oracle.

select * from dba_users

How Create New User in Oracle SQL


create user abc identified by target

grant dba to abc

how to delete user in oracle


drop user abc

Get Oracle “SERVICE NAMES” through SQL commands (sql plus)


select value from v$parameter where name like '%service_name%';
OR
show parameter service_name;

copy table structure with record


*create table abc as select * from EMP;

copy table structure with out record


*create table abc as select * from EMP where 1=2;

desc abc

How to recover delete rows in oracle(with thin 1 hour no other task should be perform)
*select * from test1 as of timestamp(systimestamp-interval '4' minute)
Then type rollback

HOW TO DELETE ROWS FROM TABLE


* delete from table where deptno='10'
++

HOW TO CREATE TABLE 

create table scenario1(Col1 varchar(5),Col2 varchar(5),Col3 varchar(5));


------
Create table INTIAL_STAGE_LOAD
(
COMPANY_NUMBER INTEGER NOT NULL,
COMPANY_NAME VARCHAR2(80 BYTE),
COUNTRY_ID  INTEGER NOT NULL,
COUNTRY_NAME VARCHAR2(35 BYTE),
POLICY_NUMBER INTEGER  NOT NULL,
POLICY_TYPE VARCHAR2(80 BYTE),
EFF_DATE DATE,
EXP_DATE DATE,
AGENT_ID INTEGER  NOT NULL,
AGENT_NAME VARCHAR2(20 ),
AGENT_TYPE VARCHAR2(20 ),
CLAIM_NO INTEGER  NOT NULL,
LOSS_CAUSE INTEGER,
CLAIMANT VARCHAR2(20 ) NOT NULL,
CLAIMANT_ADDRESS VARCHAR2(20 ),
CLAIM_AMT INTEGER,
PAID_CLAIM INTEGER,
HDATE DATE
);

The SQL INSERT INTO TABLE

insert into stud1(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)


VALUES('1123', 'CAM' ,'DRIVER' ,'7839' ,'20-07-2021' ,'3000', '3000', '50')
OR
INSERT INTO  STD1 VALUES('X','Y','Z')

ORACLE INSERT INTO MULTIPLE ROWS

INSERT ALL
INTO SCENARIO3(COL1,COL2,COL3)VALUES('A','B','C')
INTO SCENARIO3(COL1,COL2,COL3)VALUES('R','F','U')
INTO SCENARIO3(COL1,COL2,COL3)VALUES('A','B','C')
INTO SCENARIO3(COL1,COL2,COL3)VALUES('V','F','R')
INTO SCENARIO3(COL1,COL2,COL3)VALUES('V','F','R')
SELECT * FROM DUAL

UPDATE Table
UPDATE SCENARIO2 SET ID=30 WHERE NAME='CCC'

HOW TO Rename Table in oracle SQL database

ALTER TABLE SCENARIO5 RENAME TO SCENARIO16

Delete Column in oracle  Sql Table

ALTER TABLE SCENARIO16 DROP COLUMN CLO4


How to add Column in oracle  Sql Table

alter table  SOURCE21 add SAL varchar2(5)

alter table SENARIO33 add Num DOUBLE PRECISION


How do I delete blank rows in MySQL?
delete from SENARIO33 where name=’ ’ or name is NULL;

JOIN

Inner Join
Only fetch Matching data from both tables
SELECT * FROM STUD1 INNER JOIN STUD2 ON STUD1.DEPTNO=STUD2.DEPTNO
LEFT JOIN

Return only match records from left side 

How does it decide which table is left ?

SELECT * FROM STUD1 LEFT JOIN STUD2 ON STUD1.DEPTNO=STUD2.DEPTNO


 Stud1 is left side it will take left

SELECT * FROM STUD2 LEFT JOIN STUD1 ON STUD1.DEPTNO=STUD2.DEPTNO

 Stud2 is left side it will take left

RIGHT JOIN

SELECT * FROM STUD1 RIGHT JOIN STUD2 ON STUD1.DEPTNO=STUD2.DEPTNO

FULL OUTER JOIN (INNER + LEFT+RIGHT)

SELECT * FROM STUD1 FULL OUTER JOIN STUD2 ON STUD1.DEPTNO=STUD2.DEPTNO

what is sql

 SQL is used to communicate with a database.


 SQL stands for Structured Query Language, which is a programming language used to
communicate with relational databases.
 According to ANSI (American National Standards Institute), it is the standard language
for relational database management systems.
  SQL statements are used to perform tasks such as update data on a database, or
retrieve data from a database.

DDL - Data Definition Language

CREATE

Creates a new table, a view of a table, or other object in the database.

ALTER

Modifies an existing database object, such as a table.

DROP

Deletes an entire table, a view of a table or other objects in the database.

Truncate
Similar to DROP, the TRUNCATE statement is used to quickly remove all records from a table.
However, unlike DROP that completely destroys a table, TRUNCATE preserves its full structure
to be reused later.
Truncate statement syntax is:
TRUNCATE TABLE table_name;
For example:
TRUNCATE TABLE Employee;
In this example, we’re marking all the extents of the Employee table for deallocation, so they’re
considered empty for reuse.

DML - Data Manipulation Language

SELECT

Retrieves certain records from one or more tables.

INSERT

Creates a record.

UPDATE
Modifies records.

DELETE

Deletes records.

DCL - Data Control Language

GRANT

Gives a privilege to user.

REVOKE

Takes back privileges granted from user.

SQL  Constraints
Means add some condition/restriction
We have to add conditions on column attribute

UNIQUE Constraint-No duplicate allowed

NOT NULL Constraint-Not empty, (0 is value)

PRIMARY Key(unique+ Not null combination)-unique & not null value enter

FOREIGN Key-

CHECK Constraint-means example age>10 it will check each value enter by user.if less than 10 it
will reflect error

DEFAULT Constraint- if use will not put any value it will automatically take default value
What is the purpose of the NVL function?

The NVL function allows you to replace null values with a default value. If the value in the first
parameter is null, the function returns the value in the second parameter. If the first parameter
is any value other than null, it is returned unchanged.

Display the names of all the employees who are working as clerks and drawing a salary more
than 3000.

SQL>select ename from emp where job='CLERK' and sal>3000;


Display the names,SAL,JOB of all the employees who are working as clerks and drawing a salary
more than 3000.

SQL>select ename,SAL,JOB from emp where JOB='CLERK' and sal>1000;

Display the employee number and name  who are earning comm.

   SQL>select empno,ename from emp where comm is not null;

Display the employee number,ENAME,COMM  and name  who are earning comm.and not
display comm =o

SELECT EMPNO,ENAME,COMM FROM EMP WHERE COMM IS NOT NULL AND COMM != 0 

SELF JOIN

S_ID C_ID SINCE

S1      C1    2016

S2       C2   2017

S1      C2     2017

Find student id who is enrolled at least 2 course

Assume same table 2 times 

Select from study  T1,study T2 where T1.s_id=T2.s_id and T1.c_id<>T2.c_id

HOW TO FIND DUPLICATES COUNT

select count(1),"JOB" FROM SCOTT."EMP" GROUP BY "JOB" HAVING COUNT(1)>1

Q- DISPLAY TOP 3 SALARIES FROM EMP;


SQL>SELECT SAL FROM ( SELECT * FROM EMP ORDER BY SAL DESC )
WHERE ROWNUM <4

Q- Query To Find Nth(3rd) Highest Salary In SQL


TABLE
Sal
1000
2000
6000
5000
3000
o/p-3000

SELECT TOP 1 SAL FROM


(SELECT TOP 3 SAL [1st inner query excute]
FROM EMP
ORDER BY DESC)
ORDER BY SAL ASC

[when inner query excute we get 6000,5000,3000. when inner query excute we get 3000,5000,6000., asc order
3000 is top 1]

Q-.Display the name of employees who have joined in 2016 and salary is greater than 10000?

SELECT "ENAME" FROM SCOTT."EMP" WHERE "HIREDATE" LIKE ‘2016’ AND "SAL">900

Q- Query the list of city names from A Table that do not start with vowels and end with vowels. Your
result can not contain duplicates.

Can not contain duplicate means you have to use distinct

Substring is use to take out small string out of bigger string

Substring syntax

Substring(string, starting value, length)

M -1 u-2 m-3 b-4 a-5 i-6 for back P- minus4 U- minus3 N- minus2 E- minus1

Select distinct city from EMP

WHERE SUBSTR(CITY,1,1 ) NOT IN

(‘a’, ‘e’, ’I’, ’o’, ’u’, ‘A’, ‘E’, ‘I’, ‘O’ , ‘U’ )

AND SUBSTAR(CITY, -1 , 1) NOT IN

(‘a’, ‘e’, ’I’, ’o’, ’u’, ‘A’, ‘E’, ‘I’, ‘O’ , ‘U’ )

Q-SQL QUERY TO FIND HIGHEST SALARY IN A DEPARTMENT[DEPTID,SALARY]


SELECT DEPTID, MAX(SAL)

FROM EMP

GROUPBY DEPTID;

[This query 1st group all the dept id and then print dept id with max sal]

Q-SQL QUERY TO FIND HIGHEST SALARY IN A DEPARTMENT, DEPTID,SAL,DEPT NAME

[FETCHING DATA FROM 2 TABLE, using join then writing simple highest sal query]

SELECT D.NAME AS ‘DEPT’,

E.NAME AS ‘EMP’,E.SAL

FROM EMP E

INNER JOIN DEPT D [here we select requirement sal, name, dept id peform join]

ON E.DEPTID=D.ID [common column between 2 table]

WHERE(DEPTID,SAL)

IN

(SELECT DEPTID, MAX(SAL) [inner query wrote in above to find max sal dept wise]

FROM EMP

GROUPBY DEPTID);

Q- FIND OUT DUPLICATE EMAILS I A TABLE

SELECT EMAIL

FROM TABLENAME

GROUP BY EMAIL [select all the email]

HAVING COUNT(EMAIL)>1 [count those email greater than 1]

Q- FETCH EMP NAME IN UPPER CASE & USE ALIAS

SELECT EMPNAME AS UPPER(1STNAME)

FROM EMP; [as for alies 1stname ]


Q-FETCH TOP N RECORDS

SELECT TOP N * FROM EMP [fro top n record we use TOP N command]

ORDER BY SAL DESC; [we have use order it by sal ]

Q- RETRIVE EMPFNAME & EMPLNAME IN A SINGLE COLUMN AS ‘FULLNAME’ FIRST NAME, LAST
NAME SEPARATED WITH SPACE

[we have 2 coloumn make to 1 single column]

SELECT CONCAT (EMPFNAME, ‘ ’ , EMPNAME) [concat function use to combine]

AS ‘FULL NAMAE’

FROM EMP ;

Q-RETRIVE EMP-POSITION ALONG WITH TOTAL SAL PAID FOR EACH OF THEM

SELECT EMP-POSITION, SUM(SAL) [SUM use for combination all sal paid fro each of them ]

FROM EMP

GROUP BY EMP-POSIYION; [we have use group by to gropu it and print each position]

Q-fetch detail of employes with address as ‘DELHI(DEL)’

SELECT * FROM EMP

WHERE ADDRESS LIKE ‘DELHI(DEL)%’;

Q- FETCH ONLY THE FIRST NAME FROM FULL NAME COLUMN

[substring is use to fech name, fullname is column, zero is used


from which index value from which index we want out put value]

SELECT SUBSTRING (FULLNAME, 0

CHARINDEX (‘ ‘, FULLNAME)) [charindex is give the index of 1 name of column]

FROM EMP;

Q- Query to find ALL Duplicate in column Table in SQL (NO DISTINCT)

[here we have to find all the rows whose duplicate are available, here we have to use COUNT, because
when ever we have to find out duplicates COUNT come to picture]
[in this table we have duplicate rows we have to print duplicate rows]

TABLE

Eid, NAME

1 abc

2 mr

1 abc

3 xyz

2 mr

O/p- 1,2

SELECT EID [eid column name]

FROM EMP

GROUP BY EID [this group all duplicate edi together]

HAVING COUNT(EID)>1 [here we will print whose eid grearer than 1]

Q- FETCH DUPLICATES RECORDS FROM A TABLE

SELECT EMPID, DEPT, COUNT(*)

FROM EMP

GROUP BY EMPID,DEPT

HAVING COUNT(*)>1 [count is aggregate function, it aggregate]

Q- remove duplicates

DELTE FROM EMP

WHERE EMPID IN(

SELET EMPID FROM EMP

GROUP BY DEPT

HAVING COUNT(*)>1);
Q- fetch common column between 2 tables

SELECT * FROM TABLE1

INTERSET

SELECT * FROM TABLE2

Q- increase income of all employees by 5% in a table

[when we want to change in table we use update query]

UPDATE EMPLOYEE

SET INCOME=INCOME +(INCOME *%5.0/100.0);

Q- find name of employees starting with ‘A’

[% means null or any number of alphabet]

SELECT FIRST-NAME FROM EMP

WHERE FIRST-NAME LIKE ’A%’;

Q-find number of employees working in department ‘ABC’

[find any thing we use count function]

SELECT COUNT(*) FROM EMP

WHERE DEPT-NAME=’ABC’;

Q-print details of employees where first name ends with ‘A’ and contains 6 alphabates

SELECT * FROM EMP

WHERE FRIST-NAME LIKE ‘_ _ _ _ _ A’;

Q- print details of employees whose sal lies between 10000 and 50000

[Between operater is used]

SELECT * FROM EMP

WHERE SAL BETWEEN 10000 AND 50000;


Q- find 2nd highest salary

[3 ways max,limit,top]

MAX

[Query in braket is inner query it is always executed before outer query

In back end (SELECT MAX(SAL) FROM EMP) maxium sal will be selected example-7000

Then outer query SELECT MAX(SAL) FROM EMP

WHERE SAL < 70000 will executed where max sal is less than 6000 will be printed ]

SELECT MAX(SAL) FROM EMP

WHERE SAL <(SELECT MAX(SAL) FROM EMP);

2- LIMIT

[1st inner query will executed if you will not write DESC by default it will ascending order

ORDER BY will sorted in one particular order. LIMIT 2 means top 2 example 7000,6000 it will 6000

2nd Then outer query executed SELECT SAL FROM (inner)

AS EMP ORDER BY SAL LIMIT 1;

ORDER BY SAL by default ascending order become 6000,7000 LIMIT 1 means 1 will return 6000]

SELECT SAL FROM (SELECT SAL FORM EMP ORDER BY SAL DESC LIMIT 2)

AS EMP ORDER BY SAL LIMIT 1;

3-TOP

[1st inner query executed then, 1 order by desc will executed in table and sorted in descending order

Example -7000,6000, because its TOP2 , and it return 7000,& 6000

2nd the outer query excuted ,1st it select TOP1 ,then ASC order 6000,7000, it will select 6000 ]

SELECT TOP 1 SAL FROM

(SELECT TOP 2 SLA FROM EMP ORDER BY SAL DESC )

AS EMP ORDER BY SAL ASC;


Q- delete duplicate

[4 ways

1- using temporary table2


2- using auto id
3- using row number
4- using cte

USING TEMPORY TABLE

SELECT DISTINCT * INTO NEWTABLE [it will select all distinct item from old table and put in new
table]

DELETE * FROM OLDTABLE[then it will delete all item from old table]

INSERT INTO OLDTABLE SELECT * FROM NEWTABLE[select item form new table and insert in old
table, now old table have distinct item]

DROP TABLE NEWTABLE [now drop the new table]

SELECT DISTINCT * INTO NEWTABLE

FROM OLDTABLE

DELETE * FROM OLDTABLE

INSERT INTO OLDTABLE SELECT * FROM NEWTABLE

DROP TABLE NEWTABLE;

Using auto id

[INT IDENTITY (1,1) means IDENTITY (SEED,increament) seed is basically where you want to start,
I will start form 1 ,so it will increment every single time]

[we have a table with duplicate emp id ,when ALTER TABLE EMP ADD AUTOID INT IDENTITY (1,1)
we use this query it add a new column to table autoid to unique number for each row ,INT means
integer]

[2nd executed inner query , 1st it will group by all empid together example-a=1,a=2,a=3,b=4,c=5,d=6
then MIN auto id will retuent 1,4,5,6 because a will in 1 group , b will in 1 , c will in 1 group , 3
group min is 1 from every group ]
[DELETE * FROM EMP WHERE AUTO ID NOT IN it will delete all the item from table example – 2,3
and rest will return ]

ALTER TABLE EMP

ADD AUTOID INT IDENTITY (1,1) [1st executed ]

- DELETE * FROM EMP [3rd executed inner query]

WHERE AUTO ID NOT IN

(SELECT MIN(AUTOID) [2nd executed inner query]

FROM EMP

GROUP BY EMPID,EMP-NAME)

Q- query the name of students who score higher than 75 mark order your output last 3
characters of each name. if 2 or more students both have names ending In the same last 3
character[i.e kavya,navya,etc] secondary short them by ascending id

[substring(string,start,length)]

1,2,3, NATASHA-string -4, -3,-2,-1

SELECT NAME

FROM STUDENTS [- query the name of students]

WHERE MARK>75 [who score higher than 75 mark]

ORDER BY SUBSTAR(NAME,-3,3), ID; [order in asc, desc Order by by default ascending]

Q- quary an alphabetically ordered list of all names ,immediately followed by the first letter of
each profession enclosed in parameters.

Table

Name Occupation

Ram doctor

Sam police
Hari lawer

o/p- ram(d)

sam(p)

hari(l)

when we combine more columns and add neutral values to it we use CONCAT function

SELECT CONCAT(NAME,”(”, SUBSTR(OCCUPTION,1,1),”)” )FROM EMP

Q- SQL Query To Fetch Employees Who Are Also Managers

TABLE

Empid manid

121 123

450 676

131 450

[here we have to get the data from same table, we use self join , self join basically inner join
only ]

SELECT DISTNICT EMPID,

FROM EMP E [SAME TABLE 2 diff table name E , M]

INNER JOIN EMP M

ON E.EMPID=M.EMPID

Q- select the job and the min and max sal for each group of rows with same job code, but only for
groups with more than one row and with a max sal greater than or equal to 27000

SELECT JOB ID,MIN(SAL),MAX(SAL)


FROM EMP

GROUP BY JOB ID,

HAVING COUNT(X)>1 [Count is aggregate function ,having is when we use aggregate function]

AND MAX(SAL)>=27000;

Q- how to add unique row number to table?

[when we want to add unique row we use ROW_NUMBER()]

TABLE

Car code

101

102

102

SELECT ROW-NUM() OVER() AS ROWNO

CARCODE,CARNAME FROM SALES;

Q- how to find 1st ,2nd, and 3rd largest mark obtained

SELECT TOP 3 MARKS

FROM STUDENTS

WHERE SUBJECT=’SCIENCE’

ORDER BY MARKS DESC;

Q- query the number of occurences of each occupation .sort in ascending order and output them
in the format.

There are total of occupation count, and occupation name

TABLE

Name occupation

Ram Actor

Hari Actor
Sam comedian

[here we have to use count, order by to sort, for combine use concat function ,lower function to
print lower case]

[there are total of 2 actor, 15 comedians]

SELECT CONCAT (“THERE ARE A TOTAL OF”, COUNT (*),” ”, LOWER (OCCUPATION ), “S”)

FROM OCCUPATION

GROUP BY OCCUPATION

ORDER BY COUNT (OCCUPATION), LOWER (OCCUPATION);

You might also like