5. Syntax to Alter a Table (Adding Columns):
ALTER TABLE <table name>
ADD
(
{<column name> <data type> [(<size>)]
[DEFAULT <value>]
{[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ]
}
[ , …]
[ , <table level constraints> ] [ … ]
);
Example:
ALTER TABLE customer
ADD
( customer_phone VARCHAR2(30) NOT NULL,
customer_email VARCHAR2(30) UNIQUE
);
SQL (DDL – Alter Table)
6. Syntax to Alter a Table (Modifying Columns):
ALTER TABLE <table name>
MODIFY
(
{<column name> <data type> [(<size>)]
[DEFAULT <value>]
{[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ]
}
[ , …]
);
Example:
ALTER TABLE customer
MODIFY
( customer_name VARCHAR2(40) NULL,
customer_email VARCHAR2(50)
);
SQL (DDL – Alter Table)
7. Syntax to Alter a Table (Dropping Columns):
ALTER TABLE <table name>
DROP COLUMN <column name>;
Example:
ALTER TABLE customer DROP COLUMN customer_email;
SQL (DDL – Alter Table)
8. Syntax to Alter Table Level Constraints:
ALTER TABLE <table name>
{ ADD | DROP | ENABLE |DISABLE }
[ CONSTRAINT <constraint name> ]
[ <constraint definition> ];
Example:
ALTER TABLE customer ADD CONSTRAINT pk1 PRIMARY KEY (customer_id);
ALTER TABLE customer ADD CONSTRAINT uk1 UNIQUE (customer_PAN);
ALTER TABLE customer ADD CONSTRAINT chk1 CHECK (customer_income >= 0);
ALTER TABLE sales ADD CONSTRAINT fk1
FOREIGN KEY customer_id REFERENCES customer (customer_id);
ALTER TABLE customer DROP CONSTRAINT pk1;
ALTER TABLE customer DISABLE CONSTRAINT uk1;
ALTER TABLE customer ENABLE CONSTRAINT uk1;
SQL (DDL – Alter Table)
9. Syntax to Drop Table:
DROP TABLE <table name> [CASCADE CONSTRAINT];
Example:
DROP TABLE customer;
DROP TABLE customer CASCADE CONSTRAINT;
SQL (DDL – Drop Table)
10. Syntax to Insert Record:
INSERT INTO <table name> [(<column list>)]
{ VALUES (<value list>) | <query> };
Example:
INSERT INTO customer VALUES (1, ‘Mr. Ashok’, ’01-Jan-1970’, 10000, ‘P’);
INSERT INTO customer (customer_id, customer_name) VALUES (1, ‘Mr. Ashok’);
INSERT INTO customer_copy (customer_id, customer_name)
SELECT customer_id, customer_name FROM customer;
SQL (DML – Insert)
11. Syntax to Update Record:
UPDATE <table name>
SET { <column name> = { <value> | <query> }
[ , … ]
[ WHERE <filter condition> ];
Example:
UPDATE customer SET customer_income = 15000;
UPDATE customer SET customer_income = 15000 WHERE customer_id = 1;
UPDATE customer
SET customer_income = customer_income * 1.1, customer_type = ‘P’
WHERE customer_id = 1;
UPDATE customer
SET customer_income = (SELECT customer_income * 1.1
FROM customer_history
WHERE customer_id = 1)
WHERE customer_id = 1;
SQL (DML – Update)
12. Syntax to Delete Record:
DELETE [FROM] <table name>
[ WHERE <filter condition> ];
Example:
DELETE FROM customer;
DELETE customer;
DELETE FROM customer WHERE customer_id = 1;
SQL (DML – Delete)
13. Syntax to Select Records:
SELECT { * | <column name | expression> [<column alias] }
FROM { {<table name> | <query>} [<table alias>] } [ , … ]
[ WHERE <condition> ]
[ START WITH <condition CONNECT BY PRIOR <relation> ]
[ GROUP BY <column list | expression> [HAVING <group filter condition>] ]
[ ORDER BY <column list> ];
Example:
SELECT * FROM customer;
SELECT customer_id, customer_name FROM customer;
SELECT customer_id ID, customer_name Name FROM customer;
SELECT customer_id, customer_income * 1.1 NewIncome FROM customer;
SELECT * FROM (SELECT customer_id, customer_name FROM customer) Cust;
SQL (DQL – Select)
14. Row Functions:
These functions are grouped into 5 categories.
1. Number Functions
These functions receive number values & return number value.
2. Character Functions
These receive character or combination of number & character values and return
character or number value.
3. Date Functions
These receive date values or combination of date and number values and returns
date or number value.
4. Conversion Functions
These are used to convert data type of the value. Parameters may be number or
date or character and return value will be other than the parameter data type.
5. Other Functions
The functions that do not fall in the above types are grouped under this category.
SQL (Row Function)
15. Number Functions:
1. Abs(<val>): Returns positive value.
SELECT abs(-10) FROM dual; -----> 10
2. Mod(<val>,<n>): Returns remainder of division. Value is divided by <n>.
SELECT mod(10,3) DROM dual; ------> 1
3. Power(<val>,<n>): Returns value raised up to <n>
SELECT power (10,2) FROM dual; ----> 100
4. Sign(<val>): Returns 1 if value is positive, 0 if value is 0 and -1 if value is negative.
SELECT sign(10), sign(0), sign(-10) FROM dual; -------> 1 0 -1
5. Round(<val> [,<n>]):
Returns rounded value up to specified <n> decimal digits. If <n> not specified, no
decimal digits are included in the output.
SELECT round (10) FROM dual; --------> 10
SELECT round (10.4) FROM dual; --------> 10
SELECT round (10.5) FROM dual; --------> 11
SELECT round (10.523,2) FROM dual; --------> 10.52
SELECT round (10.525,2) FROM dual; --------> 10.53
SQL (Number Function-1)
16. Number Functions:
6. Trunc (<val>[,<n>]): Same as round(), but instead of rounding, it truncates the
value up to specified digits.
SELECT trunc (10) FROM dual; ----------> 10
SELECT trunc (10.4) FROM dual; ----------> 10
SELECT trunc (10.5) FROM dual; ----------> 10
SELECT trunc (10.523,2) FROM dual; ----------> 10.52
SELECT trunc (10.525,2) FROM dual; ----------> 10.52
7. Ceil (<val>): Returns smallest integer but greater or equal to value.
SELECT ceil (10.5) FROM dual; ---------> 11
SELECT ceil (-10.5) FROM dual; ---------> -10
8. Floor (<val>): Returns greatest integer but less than or equal to value.
SELECT floor (10.5) FTOM dual; ---------> 10
SELECT floor (-10.5) FROM dual; ---------> -11
SQL (Number Function-2)
17. Character Functions:
1. Substr (<str>, <start pos> [,<no. of chars>]);
Extracts no. of chars. from string starting from starting position. If, no.of chars not
specified, it extracts till end of the string.
SELECT substr ('computer',1,3) FROM dual; com
SELECT substr ('computer', 4) FROM dual; puter
SELECT substr ('computer', -2) FROM dual; er
SELECT substr ('computer', -4, 2) FROM dual; ut
2. Length (<str>):
Returns length of string in terms of number of characters within the string.
SELECT length (ename) FROM emp;
3. Instr (<str>, <search pattern>):
Returns the position of pattern if found within the string. Otherwise returns 0.
SELECT instr (‘Ramesh’, ‘E') FROM dual; 0
SELECT instr ('employee', 'e') FROM dual; 1
4. Upper (<str>): Returns the string in upper case characters.
SELECT upper ('usha') FROM dual; USHA
SQL (Character Function-1)
18. Character Functions:
5. Lower (<str>): Returns the string in lower case characters.
SELECT lower ('USHA') FROM dual; usha
6. Rpad (<str>,<output size> [,<filler chars>]):
Used to pad the filler character within the string during output to the right side of
the string. filler character is used when size is greater than the string length
SELECT Rpad (‘Ramesh’,10, '*‘ ) FROM dual; Ramesh****
7. Lpad (<str>,<output size> [,<filler chars>]):
Same as Rpad but starts padding from left side of the string.
SELECT Rpad (‘Ramesh’,10, '*‘ ) FROM dual; ****Ramesh
8. Rtrim (<str> [,<char set>]):
Trims or removes the character set from the right side of the string. If character
set is not defined, then spaces are removed.
SELECT Rtrim (‘Ramesh ‘) FROM emp; Ramesh
SELECT Rtrim (‘Ramesh‘, ‘sh’) FROM emp; Rame
9. Ltrim (<str> [,<char set>]): Same as Rtrim but trims from left side of the string.
SELECT Ltrim (‘Ramesh‘, ‘Ra’) FROM emp; mesh
SQL (Character Function-2)
19. Character Functions:
10. Initcap (<str>):
First character of each word will be converted in capital and rest in lower case.
SELECT initcap (‘raj kumar’) FROM dual; Raj Kumar
11. Ascii (<char>): Returns ascii value of given character.
SELECT Ascii (‘A’) FROM dual; 65
12. Chr (<ascii value>): Returns the character represented by ascii value.
SELECT Chr (65) FROM dual; A
SQL (Character Function-3)
20. Date Functions:
1. Add_Months (<date>, <n>):
Returns a new date by adding or subtracting number of months to or from the
given date. <n> can be positive (add) or negative (subtract).
SELECT Add_Months (hiredate, 2) FROM emp;
SELECT Add_Months (hiredate, -2) FROM emp;
2. Months_Between (<date1>, <date2>):
Returns a number indicating the difference between two dates in terms of
months. Return value may be positive or negative. Positive if first date is higher
than the second date. Negative if second date is higher.
SELECT Months_Between (sysdate, hiredate) FROM dual;
3. Sysdate: Returns system date.
SELECT sysdate FROM dual;
4. Last_Day (<date>): Returns a new date with last day of the month for the date.
SELECT Last_Day (sysdate) FROM dual;
5. Next_Day (<date> , <day name>): Returns a new date for the day mentioned as
<day name> which comes after the <date>.
SELECT Next_Day (sysdate, 'SUNDAY') FROM dual;
SQL (Date Function-1)
21. Cobversion Functions:
1. To_Char (<n/d> [,<output format>]):
Converts number or date value into character as per the output format
mentioned.
SELECT to_char (sysdate, ‘dd/mm/yyyy’) FROM dual;
SELECT to_char (sysdate,'dd-mm-yyyy:hh24:mi:ss') FROM dual;
SELECT to_char (sal,'$9999.99') FROM emp;
SELECT to_char (sal,'$0999.99') from emp;
2. To_Date (<char>, <input format>):
Converts character value in to date as per the given input format.
INSERT INTO emp (empno, hiredate)
VALUES (1, To_Date ('12/04/2001', 'dd/mm/yyyy'));
SQL (Conversion Function-1)
22. Other Functions:
1. NVL (<val>, <return val if val is null>):
Returns <val> is it is not null else returns the other value.
2. GREATEST (<value list>):
Returns greatest value from the value list of values.
3. LEAST (<value list>):
Returns smallest value from the list of values.
4. USER:
Returns current user name.
SQL (Conversion Function-1)
23. Other Functions:
DECODE ( <value / expression>
{,<search pattern>, <return value>}
[,...]
[,<default return value>]
)
if <value / expression> matches with any of the search pattern then return value for
the pattern will be returned. If <value /expression> do not match with any pattern then
default value will be returned. If default return value is not mentioned then null Is the
return value. For example: Display the grades as defined below:
1 as Poor
2 as Average
3 as Good
Rest as Excellent
SELECT DECODE (grade, 1, ‘Poor’, 2, ‘Average’, 3, ‘Good’, ‘Excellent’)
FROM salgrade;
SQL (DECODE Function)
24. Group Functions:
• Group Functions process more than one record at a time and return single value.
• Group Functions are only with SELECT and HAVING clauses.
• Group Functions output can not be clubbed with individual column output or Row
Functions output without Group By clause.
SUM(<column> | <value> | <expression>)
AVG(<column> | <value> | <expression>)
MAX(<column> | <value> | <expression>)
MIN(<column> | <value> | <expression>)
COUNT(* | <column> | <value> | <expression>)
Example:
SELECT SUM(sal) FROM emp;
SELECT job, SUM(sal) FROM emp GROUP BY job;
SELECT COUNT(*), COUNT(comm) FROM emp;
SQL (Group Function)
25. GROUP BY Clause:
Group By clause groups related records based on one or more columns. If Group
Functions are used with Group By clause, we get the summary output based on one
or more group columns. Whatever individual columns or expressions are used in
combination with Summary Function output, they must be defined with Group By
clause.
Group By <Column List>
Example:
• SELECT job, sum(sal), avg(sal) FROM emp GROUP BY job;
• SELECT job, to_char(hiredate, ‘yyyy’), sum(sal), avg(sal)
FROM emp GROUP BY job, to_char(hiredate, ‘yyyy’);
HAVING Clause:
This clause is same as WHERE clause but the difference is where clause works on
single record while having clause works on multiple records. Having Clause is
dependent on Group By clause i.e. without using Group By clause, Having Clause
can not be used.
Having <group filter condition>
Example:
• SELECT job, sum(sal), avg(sal) FROM emp
GROUP BY job HAVING sum(sal) > 3000;
SQL (GROUP BY Clause)
26. Sub Query:
What is sub-query:
It is a method to retrieve data from a table and pass the same to its parent query.
At least two queries are must in sub query method. Different queries used in sub-
queries are:
• Root Query: Top most query is referred as Root Query.
• Parent Query: A Query that receives values from other queries.
• Child Query / Sub-query: A Query called by another query.
When Sub Query is required:
• When output is required from one table and condition(s) require another table. For
example: Display those employees whose department is SALES.
SELECT * FROM emp
WHERE deptno = (SELECT deptno FROM dept WHERE dname = ‘SALES’)
• When output is required from one or more records and condition requires another
record(s) from the same table. For example: Display those employees who are
working under KING.
SELECT * FROM emp
WHERE mgr = (SELECT empno FROM emp WHERE ename = ‘KING’)
SQL (Sub Query-1)
27. • When manipulation is required on one table and condition(s) require another table.
For example: Delete those employees who are in SALES department.
DELETE FROM emp
WHERE deptno = (SELECT deptno FROM dept WHERE dname = ‘SALES’)
Independent or simple Sub-query:
An Independent Sub-query is processed once for its parent query. After receiving
values from Sub-query, Parent Query is processed. In case of Independent
Sub-query, Parent Query’s columns are not used.
SELECT * FROM emp
WHERE deptno = (SELECT deptno FROM dept WHERE dname = ‘SALES’)
Correlated Sub Query:
In correlated Sub Query method, Sub-query is processed for each record of Parent
Query i.e. Sub-query is processed as many times as the number of records
processed by Parent Query.
In case of correlated Sub-query, table aliases are must since the columns from
Parent Table and Child Tables are used in a single condition. So to refer the columns
from Parent Table into Sub-query, we need to use Table Name or Alias Name with
Columns. If Parent and Child both tables are same then Alias is must.
SQL (Sub Query-2)
28. Process Logic of Correlated Sub-query:
Unlike Independent Sub-query, here Parent and Child both tables are processed
simultaneously. Both the tables are opened with the record pointers placed at first
records of respective tables. For each movement of record pointer in Parent table,
Child table will be processed for all records and values are returned.
In case of correlated Sub-query, there will be minimum two conditions. One condition
that is to relate Parent and Child table and another condition as filter condition. For
example:
SELECT E.*
FROM emp E
WHERE E.sal = (SELECT M.sal FROM emp M WHERE M.empno = E.mgr);
DELETE FROM emp E
WHERE E.hiredate > ( SELECT M.hiredate FROM emp M
WHERE M.empno = E.mgr);
SQL (Sub Query-3)
29. Join Query:
Is another method used to relate two or more tables in the form of Parent/Child
relationship.
Only one select statement is required to define multiple tables but all the tables
must be related with the help of a condition known as Join Condition.
Generally Number of Join Conditions are “ Number of Tables - 1. If Join
Conditions is not defined then output will be Multiple of Records from all the
Tables.
Example:
SELECT dept.dname, emp.ename
FROM dept, emp
WHERE dept.deptno = emp.deptno;
SELECT emp.ename, salgrade.grade
FROM emp, salgrade
WHERE emp.sal BETWEEN salgrade.losal AND salgrade.hisal;
SQL (Join Query-1)
30. Type of Joins:
There are following types of Joins:
• Equi Join
• Non-equi Join
• Self Join
• Outer Join
Equi Join:
When two tables relation is based on Common Columns / Values (or based on
Equality). For example: EMP and DEPT tables are related via DEPTNO common
column (like emp.deptno = dept.deptno).
Non-equi Join:
When two tables relation is based on Range of Values (or based on other than
Equality). For example: EMP and SALGRADE tables are related via SAL from emp
table and LOSAL & HISAL from salgrade table (like emp.sal BETWEEN
salgrade.losal AND salgrade.hisal).
SQL (Join Query-2)
31. Self Join :
When a table is related to itself because it keeps data for two entities within it. Like
EMP table keeps Employee and Manager entities. In case of self join table alias are
must since same table is used two or more times. For example:
• Display Employee Name & Manager Name for all employees.
• Display those employees who joined the company before their Managers
Outer Join:
When we need to select Matching Records as well as Non Matching Records from
two tables. For Outer Join Query we need to use Outer Join Operator (+). For
Example:
• Display all Department names and Employee names including the Department not
having any employee.
SELECT D.dname, E.ename FROM emp, dept
WHERE emp.deptno (+) = dept.deptno;
• Display all Employees name and Managers name including the Employee not
having a Manager.
SELECT E.ename, M.ename FROM emp E, emp M
WHERE E.mgr (+)= M.empno;
SQL (Join Query-3)
32. START WITH, CONNECT BY PRIOR Clauses:
These clauses are used to get the output in tree walk style. Tree walk style defines
the output in relational hierarchy like:
KING
|_JONES
| |_ AAA
| |_ BBB
|_BLAKE
|_ CCC
|_ DDD
Tree walk style query is possible for those tables that keep two related columns in the
form of parent and child like emp table with empno and mgr columns.
Syntax : START WITH <Condition>
CONNECT BY PRIOR <parent col> = <child col>;
Connect By prior establishes relation between records while start with clause defines
the filter for records selection and it works just like where clause. With tree walk
output, SQL provides one additional column that keeps the level number of each
record as per their relationship in the hierarchy. This column name is LEVEL.It is a
virtual column and is not part of any real table, can be used with any table while
displaying output in tree walk style. Tree walk hierarchy starts with level no. 1.
SQL (Query – Connect By-1)
33. Example:
1. SELECT ename FROM emp
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr;
2. SELECT level, ename FROM emp
WHERE MOD (level,2) = 0
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr;
3. SELECT LPAD (ename, LENGTH(ename) + level, ‘ ‘)
FROM emp
WHERE MOD (level,2) = 0
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr;
SQL (Query – Connect BY-2)
34. Set Operator:
These Operators are used to join output of two queries. Number of columns selected
in Query-1and in Query-2 must be same and the data types of respective columns
must also be same.
<Query-1> <Set Operator> <Query-2>
UNION:
Accumulates data from both the Queries and returns All unique values.
SELECT deptno FROM dept UNION SELECT deptno FROM emp;
INTERSECT:
Accumulates data from both the Queries and returns Common unique values.
SELECT deptno FROM dept INTERSECT SELECT deptno FROM emp;
MINUS:
Returns unique data from first query if they are not available in second query.
SELECT deptno FROM dept MINUS SELECT deptno FROM emp;
UNION ALL:
Returns all the data from both the queries including duplicate values.
SELECT deptno FROM dept UNION ALL SELECT deptno FROM emp;
SQL (Set Operator)
35. Data Control Language Commands:
Commands under this group are used to grant or revoke privileges on System
Resource or on Objects. There are two commands under this:
• GRANT { <system privileges> | <roles> | ALL PRIVILEGES }
TO { <user name> | <role name> | PUBLIC }
[ IDENTIFIED BY <password> ]
[ WITH ADMIN OPTION ];
2. GRANT { <object privileges> | ALL | ALL PRIVILEGES }
[ (<column name list>) ]
ON <object name>
TO { <user name> | <role name> | PUBLIC }
[ WITH GRANT OPTION ];
Example:
1. GRANT CREATE TABLE, CREATE VIEW TO Scott WITH ADMIN OPTION;
2. GRANT ALL PRIVILEGES TO Scott WITH ADMIN OPTION;
3. GRANT INSERT, UPDATE (ename,sal) ON emp TO Scott;
4. GTANT ALL ON emp TO Scott WITH GRANT OPTION;
SQL ( DCL - 1)
36. • REVOKE { <system privileges> | <roles> | ALL PRIVILEGES }
FROM { <user name> | <role name> | PUBLIC };
2. REVOKE { <object privileges> | ALL | ALL PRIVILEGES }
ON <object name>
FROM { <user name> | <role name> | PUBLIC };
Example:
1. REVOKE CREATE TABLE, CREATE VIEW FROM Scott;
2. REVOKE ALL PRIVILEGES FROM Scott;
3. REVOKE INSERT, UPDATE (ename,sal) FROM emp TO Scott;
4. REVOKE ALL ON emp FROM Scott;
SQL ( DCL - 2)
37. Transaction Control Language Commands:
These commands are to control effects of DML commands on Database. There are
following three commands:
1. SAVEPOINT <savepoint name>;
Savepoint is a portion within a Transaction to which you may rollback. It allows to
rollback portion of current transaction.
2. COMMIT [WORK];
To make changes to data permanent.
3. ROLLBACK [ WORK ] [ TO [ SAVEPOINT ] <savepoint> ];
To discard the changes up to specific savepoint or till the last Commit or Rollback
point.
Example:
SAVEPOINT A;
DELETE FROM emp;
SAVEPOINT B;
DELETE FROM dept;
DELETE FROM salgrade;
ROLLBACK TO B;
COMMIT;
SQL ( TCL - 1)
38. View:
View is like a table but does not keep any data. A view is created on table(s) using
select statement:
CREATE [ OR REPLACE ] [ FORCE ] VIEW <view name>
AS
<query> [ WITH READ ONLY ];
Example:
1. CREATE VIEW v1 AS SELECT * FROM emp;
1. CREATE FORCE VIEW v2
AS
SELECT E.empno, E.ename, D.deptno, D.dname, (E.sal + NVL(E.comm,0)) Net
FROM emp E, dept D
WHERE E.deptno = D.deptno;
3. CREATE VIEW v3
AS
SELECT v2.ename, v2.dname, S.grade
FROM v2, salgrade S
WHERE v2.Net BETWEEN S.losal AND S.hisal;
View
39. Synonym:
It is used to provide another name to objects. So a single object can be accessed by
many different names. It is very useful for Remote Objects to provide them short cut
Name. It is used for Tables, Views, Synonyms, Sequences, Procedures, etc.
Syntax :
CREATE [PUBLIC] SYNONYM <synonym name>
FOR [<schema name>.] <object name> [@<dblink name>];
Example:
1. CREATE SYNONYM s1 FOR scott.emp;
2. CREATE PUBLIC SYNONYM s2 FOR scott.dept;
Sequence:
CREATE SEQENCE <sequence name>
[ START WITH <n>] - default 1
[ INCREMENT BY <n> ] - default 1
[ MAXVALUE <n> | NOMAXVALUE ] - default NOMAXVALUE
[ MINVALUE <n> | NOMINVALUE ] - default 1
[ CYCLE | NOCYCLE ] - default NOCYCLE
[ CACHE <n> | NOCHACHE ]; - default 20
Synonym