SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Syntax to create a Table:
CREATE TABLE <table name>
(
{<column name> <data type> [(<size>)]
[DEFAULT <value>]
{[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ]
}
[ , …]
[ , <table level constraints> ] [ … ]
);
Example (without Constraints):
CREATE TABLE customer
( customer_id NUMBER (4),
customer_name VARCHAR2(30),
customer_dob DATE,
customer_income NUMBER(8,2),
customer_type VARCHAR2(15)
);
SQL (DDL - Create Table)
Example (with Default Value):
CREATE TABLE customer
( customer_id NUMBER (4),
customer_name VARCHAR2(30),
customer_dob DATE,
customer_income NUMBER(8,2),
customer_type VARCHAR2(15) DEFAULT ‘PERMANENT’
);
Example (with Column Constraints):
CREATE TABLE customer
( customer_id NUMBER (4) CONSTRAINT pk1 PRIMARY KEY,
customer_name VARCHAR2(30) CONSTRAINT nn1 NOT NULL,
customer_dob DATE,
customer_income NUMBER(8,2) CHECK (customer_income >= 0),
customer_type VARCHAR2(15) DEFAULT ‘P’
CONSTRAINT type1 CHECK (customer_type IN (‘P’, ‘T’))
CONSTRAINT type2 NOT NULL,
customer_PAN VARCHAR2(30) CONSTRAINT PAN1 UNIQUE
);
SQL (DDL - Create Table)
Example (with Table Level Constraints):
CREATE TABLE customer
( customer_id NUMBER (4),
customer_name VARCHAR2(30),
customer_dob DATE,
customer_income NUMBER(8,2),
customer_type VARCHAR2(15),
customer_PAN VARCHAR2(30),
CONSTRAINT pk1 PRIMARY KEY (customer_id, customer_dob),
CONSTRAINT uk1 UNIQUE (customer_PAN),
CONSTRAINT chk1 CHECK (customer_income >= 0),
);
Example (with Column Level FK Constraints):
CREATE TABLE sales
( sales_id NUMBER (8) PRIMARY KEY,
sales_date DATE,
sales_type VARCHAR2(15),
customer_id NUMBER(4) REFERENCES customer (customer_id)
);
SQL (DDL - Create Table)
Example (with Table Level FK Constraints):
CREATE TABLE sales
( sales_id NUMBER (8) PRIMARY KEY,
sales_date DATE,
sales_type VARCHAR2(15),
customer_id NUMBER(4),
FOREIGN KEY customer_id REFERENCES customer (customer_id)
);
SQL (DDL – Create Table)
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)
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)
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)
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)
Syntax to Drop Table:
DROP TABLE <table name> [CASCADE CONSTRAINT];
Example:
DROP TABLE customer;
DROP TABLE customer CASCADE CONSTRAINT;
SQL (DDL – Drop Table)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
• 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)
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)
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)
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)
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)
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)
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)
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)
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)
• 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)
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)
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Sql commands
Sql commandsSql commands
Sql commands
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
SQL
SQLSQL
SQL
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
8. sql
8. sql8. sql
8. sql
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
SQL select clause
SQL select clauseSQL select clause
SQL select clause
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
Less06 networking
Less06 networkingLess06 networking
Less06 networking
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | Edureka
 
Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)ppt
 
Sql select
Sql select Sql select
Sql select
 

Andere mochten auch

Como crear usuarios y asignar permisos en postgre sql blog de alevsk
Como crear usuarios y asignar permisos en postgre sql   blog de alevskComo crear usuarios y asignar permisos en postgre sql   blog de alevsk
Como crear usuarios y asignar permisos en postgre sql blog de alevskantoniorua1
 
Bn 1016 demo postgre sql-online-training
Bn 1016 demo  postgre sql-online-trainingBn 1016 demo  postgre sql-online-training
Bn 1016 demo postgre sql-online-trainingconline training
 
U456 postgre sql
U456 postgre sqlU456 postgre sql
U456 postgre sqlJr. Serrano
 
Documentacion postgresql
Documentacion postgresqlDocumentacion postgresql
Documentacion postgresqlCesar Martinez
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql SyntaxReka
 
Database - SQL Joins
Database - SQL JoinsDatabase - SQL Joins
Database - SQL JoinsMudasir Qazi
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries Prabu Cse
 
Database - Normalization
Database - NormalizationDatabase - Normalization
Database - NormalizationMudasir Qazi
 
Exchange Server 2013 and SharePoint Server 2013 Integration
Exchange Server 2013 and SharePoint Server 2013 IntegrationExchange Server 2013 and SharePoint Server 2013 Integration
Exchange Server 2013 and SharePoint Server 2013 IntegrationSharePoint Saturday New Jersey
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query OptimizationBrian Gallagher
 
+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II Notes+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II NotesAndrew Raj
 
SQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12cSQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12cTanel Poder
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were PossibleLukas Eder
 
CBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationCBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationGuru Ji
 
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NFDatabase Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NFOum Saokosal
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answersiimjobs and hirist
 

Andere mochten auch (20)

Como crear usuarios y asignar permisos en postgre sql blog de alevsk
Como crear usuarios y asignar permisos en postgre sql   blog de alevskComo crear usuarios y asignar permisos en postgre sql   blog de alevsk
Como crear usuarios y asignar permisos en postgre sql blog de alevsk
 
Postgre sql unleashed
Postgre sql unleashedPostgre sql unleashed
Postgre sql unleashed
 
Bn 1016 demo postgre sql-online-training
Bn 1016 demo  postgre sql-online-trainingBn 1016 demo  postgre sql-online-training
Bn 1016 demo postgre sql-online-training
 
U456 postgre sql
U456 postgre sqlU456 postgre sql
U456 postgre sql
 
Documentacion postgresql
Documentacion postgresqlDocumentacion postgresql
Documentacion postgresql
 
Taller 080364 sgbd-0102 - java&amp;postgre sql
Taller 080364 sgbd-0102 - java&amp;postgre sqlTaller 080364 sgbd-0102 - java&amp;postgre sql
Taller 080364 sgbd-0102 - java&amp;postgre sql
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql Syntax
 
Database - SQL Joins
Database - SQL JoinsDatabase - SQL Joins
Database - SQL Joins
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries
 
Database - Normalization
Database - NormalizationDatabase - Normalization
Database - Normalization
 
Exchange Server 2013 and SharePoint Server 2013 Integration
Exchange Server 2013 and SharePoint Server 2013 IntegrationExchange Server 2013 and SharePoint Server 2013 Integration
Exchange Server 2013 and SharePoint Server 2013 Integration
 
Sql joins
Sql joinsSql joins
Sql joins
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query Optimization
 
+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II Notes+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II Notes
 
SQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12cSQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12c
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible
 
CBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationCBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL Presentation
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NFDatabase Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answers
 

Ähnlich wie Sql (20)

Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
 
Lab
LabLab
Lab
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
New tsql features
New tsql featuresNew tsql features
New tsql features
 
Les09
Les09Les09
Les09
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)
 
Sql commands
Sql commandsSql commands
Sql commands
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
SQL introduction
SQL introductionSQL introduction
SQL introduction
 
Query
QueryQuery
Query
 
My Sql concepts
My Sql conceptsMy Sql concepts
My Sql concepts
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
SQL
SQLSQL
SQL
 
Basic sql(oracle) queries
Basic sql(oracle) queriesBasic sql(oracle) queries
Basic sql(oracle) queries
 
Sql
SqlSql
Sql
 
Sqlbysandeep
SqlbysandeepSqlbysandeep
Sqlbysandeep
 
Lecture 3 sql {basics ddl commands}
Lecture 3 sql {basics  ddl commands}Lecture 3 sql {basics  ddl commands}
Lecture 3 sql {basics ddl commands}
 

Kürzlich hochgeladen

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Kürzlich hochgeladen (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Sql

  • 1. Syntax to create a Table: CREATE TABLE <table name> ( {<column name> <data type> [(<size>)] [DEFAULT <value>] {[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ] } [ , …] [ , <table level constraints> ] [ … ] ); Example (without Constraints): CREATE TABLE customer ( customer_id NUMBER (4), customer_name VARCHAR2(30), customer_dob DATE, customer_income NUMBER(8,2), customer_type VARCHAR2(15) ); SQL (DDL - Create Table)
  • 2. Example (with Default Value): CREATE TABLE customer ( customer_id NUMBER (4), customer_name VARCHAR2(30), customer_dob DATE, customer_income NUMBER(8,2), customer_type VARCHAR2(15) DEFAULT ‘PERMANENT’ ); Example (with Column Constraints): CREATE TABLE customer ( customer_id NUMBER (4) CONSTRAINT pk1 PRIMARY KEY, customer_name VARCHAR2(30) CONSTRAINT nn1 NOT NULL, customer_dob DATE, customer_income NUMBER(8,2) CHECK (customer_income >= 0), customer_type VARCHAR2(15) DEFAULT ‘P’ CONSTRAINT type1 CHECK (customer_type IN (‘P’, ‘T’)) CONSTRAINT type2 NOT NULL, customer_PAN VARCHAR2(30) CONSTRAINT PAN1 UNIQUE ); SQL (DDL - Create Table)
  • 3. Example (with Table Level Constraints): CREATE TABLE customer ( customer_id NUMBER (4), customer_name VARCHAR2(30), customer_dob DATE, customer_income NUMBER(8,2), customer_type VARCHAR2(15), customer_PAN VARCHAR2(30), CONSTRAINT pk1 PRIMARY KEY (customer_id, customer_dob), CONSTRAINT uk1 UNIQUE (customer_PAN), CONSTRAINT chk1 CHECK (customer_income >= 0), ); Example (with Column Level FK Constraints): CREATE TABLE sales ( sales_id NUMBER (8) PRIMARY KEY, sales_date DATE, sales_type VARCHAR2(15), customer_id NUMBER(4) REFERENCES customer (customer_id) ); SQL (DDL - Create Table)
  • 4. Example (with Table Level FK Constraints): CREATE TABLE sales ( sales_id NUMBER (8) PRIMARY KEY, sales_date DATE, sales_type VARCHAR2(15), customer_id NUMBER(4), FOREIGN KEY customer_id REFERENCES customer (customer_id) ); SQL (DDL – Create Table)
  • 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