Professional Documents
Culture Documents
Points
Points
ALTER
ALTER TABLE <Existing Table_name>ADD<New_Column_name><Data Type><Size>;
ALTER TABLE Customer ADD Mob number(10);
Note: in case of multiple column use ().
DROP
The complete structure of the table can be deleted using DROP command.
DROP TABLE <Table_name>;
Note: when the table is dropped it make a copy of it but same can be retrieved by DBA.
Select * from tab; (this would return 10 table)
Drop table emp; (emp is one of the table, after using drop command we could still see 10 table)
RENAME
Rename the table_name.
RENAME <Existing_table_name> to <New_table_name>;
INSERT
INSERT INTO <Table_name> VALUES (value1, value2,…..);
INSERT INTO Customer VALUES (1, ‘GURU’,’BANG’); ----- insert single record.
INSERT INTO Customer VALUES (&ID, ‘&NAME’,’&LOC’); ----- multiple record use back slash “/”
How to insert blank value?
INSERT INTO Customer VALUES(NULL, ‘PAR’, ‘BNG’);
INSERT INTO Customer VALUES(“ “, ‘PAR’, ‘BNG’);
insert into customer2 values(1, AAA', 'BTM');
ORA-01756: quoted string not properly terminated
insert into customer2 values(1, '"AAA"', 'BTM');
1 "AAA" BTM
insert into customer2 values(1, 'BBB' 'BTM','BNG');
ORA-00917: missing comma
insert into customer2 values(1, 'BBB', 'BTM','BNG');
ORA-00913: too many value
insert into customer2 values(&id, &name', '&address);
7 'HHHH JC ROAD'
Entering value for specific column say id and name only?
insert into customer2(id, name) values (9, 'kkk');
INSERT INTO Z VALUES ( , 'R');
ORA-00936: missing expression
Temporary storage
RedoLog1
RedoLog2
DELETE
We can delete the data from the table.
DELETE FROM <Table_name>;
DELETE <Table_name>;
Delete the data from table customer2 where id is 1 and 3?
delete customer2 where id in(1,3);
Delete Vs Rollback
Delete: delete the data from the table, after commit.
Rollback: delete the data from buffer, before commit.
TRUNCATE
Removes the data from the table.
TRUNCATE TABLE <table_name>;
DELETE VS TRUNCATE
Aggregate/group function
These are used to summarize the detailed data.
Count the number of records in a table.
Select count (emp) from emp;
select count(*) from emp;
count() will not count the NULL values. Count(*) will count all the columns count
and display the highest count.
Count() Select count(1) from emp; //count the records using first column
summarize the detailed value of specified column
Sum() select sum(sal) from emp where deptno=10;
returns max/highest value from the specified column
Max() select max(sal) from emp;
returns min/lowest value from the specified column
Min() select min(sal) from emp;
returns the average value of the specified column
Avg() select avg(sal) from emp;
Character function
Alias
It basically gives the name to the column for display purpose.
Select count(empno) ENO from emp;
Select count(empno) as ENO from emp;
Select count(empno) ENO, sum(sal) ‘TOTAL SAL’, max(sal) HIGH_SAL, min(sal) LOW_SAL,
avg(sal) AVG_SAL from emp;
Note: while defining the alias, in case of space it should be into single inverted commas (‘ ‘).
CONSTRAINTS
UNIQUE
create table customer(id number, name varchar2(10) UNIQUE, loc varchar2(10));
insert into customer values(1,'SIVA', 'BNG');
insert into customer values( NULL,'RAM', 'BNG')
insert into customer values(1,'SIVA', 'BNG');
ORA-00001: unique constraint (SCOTT.SYS_C005988) violated
insert into customer values( ,'SURESH', 'BNG');
ORA-00936: missing expression
CREATE TABLE WELL1(
WNO NUMBER(5) CONSTRAINT PK PRIMARY KEY,
WNAME VARCHAR2(10),
WLOC VARCHAR2(10))
CREATE TABLE WELL(
ID NUMBER(5) CONSTRAINT PK PRIMARY KEY,
NAME VARCHAR2(10) CONSTRAINT NN NOT NULL,
PASSPORT VARCHAR(10) CONSTRAINT UNQ UNIQUE,
SAL NUMBER(7),
CONSTRAINT CHK CHECK (SAL BETWEEN 2000 AND 5000),
WNO NUMBER(5) CONSTRAINT REF REFERENCES WELL1(WNO))
BANK
EMPNO ENAME ADDRESS SAL DNO DNAME PAN PASSPORT A/C PF MOBILE
No
PK NN NN NN NN NN UNQ UNQ UNQ UNQ Constraint
Composite primary key
- 32 columns can be assigned to composite key.
- In a composite key the combination of the column should be unique
- In the flight reservation table it is difficult to put the primary key on a particular column
so we combine the column and make it unique. (FNO, SEAT, JDATE, TRIP NO)
TABLE: Flight reservation
FNO SEAT JDATE FRM DESTINATION TRIP NO
J001 5 1-Jun-14 BNG CHN 1
J001 5 1-Jun-14 CHN BNG 2
Column level constraints: constraint applied for more than one column is called column level
constraint. Ex: NOT NULL
Table level constraints:constraints applied to the table are called table level constraints. Ex:
primary key, unique.
What if the report says the PK is there but still able to insert the duplicate and null values?
- Check the constraint on table
- Check the status of the constraint - ENABLE/DISABLED
There might be possibility the developer would have disabled the constraint because:
he might have forgot to enable it OR when he created the table at that time it would not be
used
Referential integrity:
- Master table should have primary key. Master table should be created first with data.
- Reference column may or may not be same (dno-dno, deptno-dno)
- Relational column – data type should be same.
- Child table column should not be primary key.
- Reference will check the data and display
- It helps to avoid the inconsistency of data
- Referential integrity is defined on Child/detailed table.
- Relationship is created with referential integrity but not with foreign key.
Create table dept(dno number(5) primary key, dname varchar2(10), loc varchar2(10);
Create table emp(eno number(5) primary key, ename varchar2(10), sal number(3), dno
number(5) REFERENCES dept(dno));
Description constraint name Alias C Search condition
NOT NULL SYS_C005998 NN2 C "NAME" IS NOT NULL
CHECK SYS_C005999 CHK C SAL BETWEEN 2000 AND 5000
PRIMARY SYS_C006000 PK_ID P
UNIQUE SYS_C006001 UNQ U
REFERENTIAL SYS_C006002 REF R
On delete cascade
Used to delete the records from the parent table even though records exist in the child table.
Create table emp(eno number(5) primary key, ename varchar2(10), sal number(3), dno
number(5) REFERENCES dept(dno) on delete cascade);
SET OPERATOR
There are four SET operators: Point to considered using SET operators:
1) UNION ➢ The column count should be same.
2) UNION ALL ➢ The column data type should be same
3) MINUS ➢ The column order should be same
4) INTERSECT
UNION
Combine the query result set (not the table), do sorting, remove duplicate and return unique
result set.
Table removing
A Table B Combining sorting duplicate result
X Y 1 1 1 1
1 6 2 1 2 2
2 7 3 2 3 3
3 1 4 2 4 4
4 8 5 2 5 5
5 2 SELECT X FROM A 6 3 6 6
3 UNION 7 3 7 7
9 SELECT Y FROM B 1 4 8 8
2 8 5 9 9
2 6
3 7
9 8
2 9
UNION ALL
Combine the query result set with no sorting and not removing duplicate. This is faster than
UNION as sorting and removing of duplicate activity does not happen.
Table
A Table B Combining result
X Y 1 1
1 6 2 2
2 7 3 3
3 1 4 4
4 8 SELECT X FROM A 5 5
5 2 UNION ALL 6 6
3 SELECT Y FROM B 7 7
9 1 1
2 8 8
2 2
3 3
9 9
2 2
MINUS
Returns all the rows in the first query that are not returned in the second query. The data is
sorted.
Table
A Table B Combining Remove result
X Y 1 Y 4
1 6 SELECT X FROM A 2 Y 5
2 7 MINUS 3 Y
3 1 SELECT Y FROM B 4 N
4 8 5 N
5 2
3
9
2
INTERSECT
Returns rows/records common in both the query set. Sort the data before displaying.
Table
A Table B result
X Y SELECT X FROM A 1
1 6 INTERSECT 2
2 7 SELECT Y FROM B 3
3 1
4 8
5 2
3
9
2
DISTINCT CLAUSE
Removes the duplicate from the result set.Applied on columns. Used with SELECT statement.
select DISTINCT JOB from emp;
select DISTINCT JOB, DEPTNO from emp;
ORDER BY CLAUSE
Sort the records in the result set.Used with select statement.Should be used at the last of the
query.- By default ASC
Select * from <table> order by <column> ASC OR DESC.
Select * from emp order by sal; OR select EMPNO, ENAME, SAL from emp order by sal ASC;
Select * from emp order by saldesc;
LIKE CLAUSE
Allow to use wildcard (%,_). Used for pattern matching ('%h', '_i%a', '____',). Used with select,
update and delete statement
select * from emp where name like '%r%';
GROUP BY CLAUSE
Used with select statement to collect data across mutliple records and group the results by one
or more particular field and apply an aggregate function to the subset.- Normally used with
aggregate expressions (like sum, count, avgetc). while group by (by deptno), the deptno should
be in selection also, otherwise error.
selectdeptno, sum(sal) from emp group by deptno;
HAVING CLAUSE
Used in combination with GROUP BY clause. Used for filtering the data.Used in select
statement. This was introduced because WHERE clause does not works with aggregate
functions. WHERE clause can be used by group by clause but it has to be used before the group
by clause.
selectdeptno, sum(sal) SALARY from emp group by deptno having sum(sal)>9000;
selectdeptno, sum(sal) SALARY from emp group by deptno having SALARY>9000;
ORA-00904: "SALARY": invalid identifier
Select deptno, sum(sal) SALARY from emp where deptno not in 30 group by deptno
having sum(sal)>9000;
Clause sequence
Clause Order
ORDER
BY 7
FROM 3
WHERE 4
DISTINCT 2
HAVING 6
GROUP
BY 5
SELECT 1
Using clause sequence
SELECT DISTINCT JOB, SUM(SAL) FROM EMP WHERE SAL > 1000 GROUP BY JOB, SAL HAVING
SUM(SAL)>2000 ORDER BY SUM(SAL)
JOINS
It is a query that combines rows from two or more tables, based on a relationship between
certain columns in the table.
If no relationship between the tables, still we can join the table.
Joins are faster than sub-queries.
EMP1 DEPT1
ENO ENAME SAL DNO DNO DNAME LOC
1 PADMAJA 30000 10 10 IT BNG
2 LAKSHMI 25000 20 20 HR CHN
3 ANAND 25000 30 30 FINANCE HYD
4 ASHWINI 40000 10
5 RUDRA 90000 40
EQUI/INNER/SIMPLE/DEFAULT JOIN
- A join with a join condition containing an equality operator (=).
- It combines rows that have equivalent values for the specified columns.
selecte.empno, e.ename, e.job, e.sal, e.deptno, d.dname, d.loc from emp e, dept d where
e.deptno=d.deptno;
SQL> select e.empno, e.ename, e.job, m.ename manager from emp e, emp m where
e.mgr=m.empno;
OUTER JOIN G H
(+) Operator is used for outer joins in oracle. X Y
1 1
2 2
3 3
4 5
LEFT OUTER JOIN
Return all rows from the left table, even if there is no matches in the right table.
SQL> SELECT G.X, H.Y FROM G, H WHERE G.X=H.Y(+); ---- (by oracle db)
or
SELECT * FROM G g LEFT OUTER JOIN H h on g.X=h.Y; ---- (by all db)
SELECT * FROM G g LEFT JOIN H h on g.X=h.Y;
X Y
---------- ----------
1 1
2 2
3 3
4
RIGHT OUTER JOIN
Return all rows from the right table, even if there are no matches in the left table.
SQL> SELECT G.X, H.Y FROM G, H WHERE G.X (+) =H.Y; ---- (by oracle db)
SELECT * FROM G g RIGHT OUTER JOIN H h on g.X=h.Y; ---- (by all db)
SELECT * FROM G g RIGHT JOIN H h on g.X=h.Y;
X Y
---------- ----------
1 1
2 2
3 3
5
X Y
---------- ----------
1 1
2 2
3 3
4
5
A A A A A A A A A A
B B B B B B B B B B
C C C C C C C C C C
D E D _ _ E D _
_ E
SUB-QUERIES
- Sub query or inner query or nested query is a query in a query.
- Usually added in the WHERE clause.
- Used when we know how to search for a value using a SELECT statement, but do not
know the exact value.
- Its an alternate way of returning data from multiple tables.
- Operators used like, =, <, >, >=, <= etc.
selectename,sal,deptno from emp a where a.sal< (select avg(sal) from emp b where
a.deptno=b.deptno);
Difference between sub-query and co-related sub-query
In sub-query the inner query can be executed separated. The inner query is not dependent on
main/outer query. Hence it is independent.
In co-related sub-query inner query is dependent on the outer query. Hence both the
dependent on each other.
PSEUDO COLUMNS
There are two pseudo columns:
1) ROWNUM
2) ROWID
ROWNUM
- Can be used in any column
- ROWNUM will support “=” only for first record not for other records.
- ROWNUM will support <, =, <= only.
- ROWNUM does not support “>”.
ROWID
- Will add a unique id for each row. This is the provided by ORACLE DB.
Delete all the duplicate records and keeping the original ones
selectrowid, id from duplicate a where a.rowid>(select min(rowid ) from duplicate b where
b.id=a.id; //6 rows
delete from duplicate a where a.rowid>(select min(rowid ) from duplicate b where b.id=a.id);
Delete all the original records and keeping the duplicate ones
selectrowid, id from duplicate a where a.rowid< (select max(rowid ) from duplicate b where
b.id=a.id); //6 rows
delete from duplicate a where a.rowid< (select max(rowid ) from duplicate b where b.id=a.id);
Write a single statement with using ROWNUM and ROWID
select ROWNUM, ROWID, EMPNO, ENAME from EMP;
Select all the negative and positive values from the Table?
Select * from emp where sal< 0;//negative
Select * from emp where sal> 0;//positive
CAST FUNCTION
- Use to convert the one data type to another data type.
- Used in SELECT statement.
- It’s for temporary for display purpose only (temporary DB / Buffer).
- Varchar2 can be converted to Char whereas Char cannot be converted to Varchar2.
NSR1 NSR2
NO
ID (number) NAME (varchar2) (number) NAME (char)
1 RAM 1 RAM
2 SIVA 2 SIVA
DCL
Two command:
1) Grant
2) Revoke
Login as
username = sys/admin as sysdba
password and host string =blank or nothing
DATE FUNCTIONS
CASE STATEMENT
It uses WHEN and THEN. Can be used for select, update and delete statement.
SELECT EMPNO, ENAME, SAL,
CASE
WHEN SAL > 4000 THEN ‘GRADE-A’
WHEN SAL > 2000 AND SAL < 4000 THEN ‘GRADE-B’
ELSE
‘GRADE-C’
END
GRADE
FROM EMP ORDER BY SAL DESC;
Note: The Grade after END is the alias. The case statement starts from beginning and check for
matched record, if matched then exit.
STRING FUNCTION
INSTR() FUNCTION
✓ By using the INSTR FUNCTION we will get the position of char from a string.
✓ If the start position is not mentioned in query, By default, it will consider 1st position.
✓ If the start position is negative, the function counts back start position number of
characters from end of string and then searches towards the beginning of string.
SUBSTR() FUNCTION
✓ We can get piece of char from string or substring of a string.
✓ Substr() has three parameters:
SUBSTR(<string>,<start position>,<length>);
- <string> is the source string
- <start position> is the position for extraction
- <length> number of character to extract
INLINE QUERY
Any query that start after the FROM clause is an inline query where as the query that starts
after WHERE clause is sub-query.
Inline == after FROM
Sub-query == after WHERE
SELECT EMPNO,ENAME,SAL,HIGH_SAL ,HIGH_SAL-SAL AS DIFF_SAL FROM (SELECT
EMPNO,ENAME,SAL,(SELECT MAX(SAL) FROM EMP) AS HIGH_SAL FROM EMP);
DENSE_RANK()
SQL>SELECT EMPNO,ENAME,SAL,DENSE_RANK() OVER (ORDER BY SAL) AS RANK FROM EMP;
RANK()
SQL>SELECT EMPNO,ENAME,SAL,RANK() OVER (ORDER BY SAL) AS RANK FROM EMP;
Nth HIGEST SALARY:
SELECT * FROM (SELECT EMP.*,DENSE_RANK() OVER (ORDER BY SAL DESC) AS RANK FROM
EMP) WHERE RANK = &RANK