You are on page 1of 45

Topic

DDL
CREATE
ALTER
TRUNCATE
DROP
RENAME

DML
INSERT
UPDATE
DELETE
TCL
COMMIT
ROLLBACK
DCL
GRANT
REVOKE

Purpose

The CREATE TABLE statement is used to create a table in a databa


The ALTER TABLE statement is used to add, delete, or modify colum
The SQL TRUNCATE TABLE command is used to delete complete data
Indexes, tables, and databases can easily be deleted/removed wi
RENAME allows you to rename an existing table

The INSERT INTO statement is used to insert new records in a tabl


The UPDATE statement is used to update existing records in a tabl
The DELETE statement is used to delete rows in a table.

Use the COMMIT statement to end your current transaction and ma


The ROLLBACK command is the transactional command used to
undo transactions that have not already been saved to the
database.
The ROLLBACK command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued.
SQL GRANT is a command used to provide access or privileges on
the
objects to removes
the users.
The database
REVOKE command
user access rights or privileges
The
following
types
of privileges can be granted:
to
the
database
objects.
Delete
datatypes
from of
a specific
table.
The
following
privileges
can be revoked:
Insert data into a specific table.
Create
a foreign
reference
to the named table or to a
Delete data
fromkey
a specific
table.
subset
ofdata
columns
a table.
Insert
into afrom
specific
table.
Select
data
from
a
table,
view, to
or the
a subset
of table
columns
Create a foreign key reference
named
or toinaa
table.
subset of columns from a table.
Create
a trigger
a table.
Select data
fromon
a table,
view, or a subset of columns in a
Update data in a table or in a subset of columns in a table.
table.
Run
a specified
or procedure.
Create
a triggerfunction
on a table.
Use
a
sequence
generator
user-defined
type.in a table.
Update data in a table or inora asubset
of columns
Run a specified routine (function or procedure).
Use a sequence generator or a user-defined type.

Syntax

CREATE TABLE <TABLE NAME> (COL1 DATATYPE, COL2


DATATYPE........COLN
DATATYPE)
ADD:ALTER
TABLE
<TABLE
NAME>
ADD <COL DATATYPE>
TRUNCATE
TABLE
<TABLE
NAME>
DROP:DROP
TABLE
<TABLE NAME> TO <NEW_TABLE_NAME>
RENAME
<OLD_TABLE_NAME>
ALTER TABLE
TABLE <TABLE NAME> DROP COLUMN
<COLUMN NAME>
MODIFY:ALTER TABLE <TABLE NAME> MODIFY <COL NEW DATA
TYPE>
INSERT INTO ALL COLUMNS USING VALUE
RENAME:METHOD:UPDATE <TABLE_NAME> SET COL=NEW_VALUE WHERE
ALTER
<TABLE NAME> RENAME
INSERTTABLE
INTO <TABLE_NAME>
VALUES COLUMN
DELETES
WHOLE
TABLE
DATA:<OLD_COLUMN_NAME> TO <NEW_COLUMN_NAME>
(VALUE1,VALUE2.....VALUEN)
DELETE FROM <TABLE NAME>
DELETE FROM PRODUCT_TRANSACTIONS
INSERT INTO SPECIFIC COLUMNS:INSERT INTO <TABLE_NAME> (COL1, COL2) VALUES
DELETES SPECIFIC ROWS ON CONDITION :(VALUE1, VALUE2)
DELETE
COMMIT FROM <TABLE NAME> WHERE (CONDITION)
DELETE
FROM PRODUCT_TRANSACTIONS WHERE
ROLLBACK
INSERT INTO ALL COLUMNS USING ADDRESS
PRODUCT_CODE=1
METHOD:insert into product_transaction values
(&col1,&col2,....&coln)
GRANT privilege_name
INSERT
INTO
SPECIFIC COLUMNS USING ADDRESS
ON
object_name
REVOKE
privilege_name
METHOD:TO {user_name
ON
object_name|PUBLIC |role_name}
INSERT
INTO PRODUCT_TRANSACTION
[WITH
GRANT
OPTION];
FROM {user_name
|PUBLIC |role_name}
(PRODUCT_CODE,PRICE) VALUES
(&PRODUCT_CODE,&PRICE)

Example

CREATE TABLE PRODUCT_TRANSACTION(PRODUCT_CODE NUMBER(10),


PRICE
ADD:- DECIMAL(8,2), ADDRESS VARCHAR(50), NAME VARCHAR(50))
ALTER
TABLE
PRODUCT_TRANSACTION
ADD DISCOUNT VARCHAR(2)
TRUNCATE
TABLE
PRODUCT_TRANSACTION
DROP TABLE PRODUCT_TRANSACTION
DROP:RENAME
PRODUCT_TRANSACTION
TO PRODUCT_TRANSACTIONS
ALTER TABLE
PRODUCT_TRANSACTION
DROP COLUMN DISCOUNT
MODIFY:ALTER TABLE PRODUCT_TRANSACTION MODIFY PRODUCT_CODE
VARCHAR(10)
RENAME
:INSERT INTO
ALL COLUMNS USING VALUE METHOD:ALTER
TABLE
PRODUCT_TRANSACTION RENAME
PRODUCT_CODE
INSERT
INTO
PRODUCT_TRANSACTIONS
VALUES COLUMN
(001,120,'HYD','BADRI')
UPDATE PRODUCT_TRANSACTIONS SET PRICE=160
WHERE PRODUCT_CODE=1
TO PRODUCT_CODES
DELETES WHOLE TABLE DATA:INSERT INTO SPECIFIC COLUMNS:DELETE FROM PRODUCT_TRANSACTIONS
INSERT INTO PRODUCT_TRANSACTIONS (PRICE,PRODUCT_CODE) VALUES
(150,002)
DELETES SPECIFIC ROWS ON CONDITION :DELETE FROM PRODUCT_TRANSACTIONS WHERE PRODUCT_CODE=1
INSERT INTO ALL COLUMNS USING ADDRESS METHOD:COMMIT
insert into product_transaction values
ROLLBACK
(&product_code,&price,'&address','&name')
INSERT INTO SPECIFIC COLUMNS USING ADDRESS METHOD:INSERT INTO PRODUCT_TRANSACTION (PRODUCT_CODE,PRICE) VALUES
(009,112)
GRANT SELECT ON TABLE XYZ TO ABC
REVOKE SELECT ON TABLE XYZ FROM ABC

UCT_CODE=1

TOPIC

Arithmetic Operators
+
*
/
Concatenation Operator
||
Comparison Operators
=
<>
>
<
>=
<=
IN
NOT IN
BETWEEN
NOT BETWEEN
LIKE (%,_)
NOT LIKE
IS NULL
IS NOT NULL

Logical Operators

AND
OR

Set Operators

UNION

UNION ALL

MINUS

INTERSECT

EXAMPLE

SELECT
SELECT
SELECT
SELECT

sal
sal
sal
sal

+ comm FROM emp


- comm FROM emp
* 12 FROM emp
/ 30 FROM emp

SELECT 'Name is ' || ename FROM emp;

SELECT
SELECT
SELECT
SELECT
SELECT
SELECT

*
*
*
*
*
*

FROM emp WHERE sal = 1500;


FROM emp WHERE sal <> 1500;
FROM emp WHERE sal >1500;
FROM emp WHERE sal <1500;
FROM emp WHERE sal >= 1500;
FROM emp WHERE sal <= 1500;

SELECT * FROM emp WHERE job IN


('CLERK', ANALYST');
SELECT * FROM emp WHERE job NOT IN
('CLERK', ANALYST');
SELECT * FROM emp WHERE sal
BETWEEN 2000 AND 3000;
SELECT * FROM emp WHERE sal
NOT BETWEEN 2000 AND 3000;
SELECT * FROM EMP WHERE ENAME LIKE 'SM%'
SELECT * FROM EMP WHERE ENAME NOT LIKE 'SM%'
SELECT ename, deptno FROM emp
WHERE comm IS NULL;
SELECT ename, deptno FROM emp
WHERE comm IS NOT NULL;

SELECT * FROM emp WHERE job = 'CLERK'


AND deptno
= emp
10; WHERE job = 'CLERK'
SELECT
* FROM
OR deptno = 10;

SELECT CUST_ID FROM TABLE1


UNION
SELECT CUST_ID FROM TABLE2
SELECT CUST_ID FROM TABLE1
UNION ALL
SELECT CUST_ID FROM TABLE2

SELECT CUST_ID FROM TABLE1


MINUS
SELECT CUST_ID FROM TABLE2

PURPOSE
You can use an arithmetic operator in an
expression to negate, add, subtract, multiply,
and divide numeric values. The result of the
operation is also a numeric value.

Concatenates character strings.

Comparison operators compare one expression


with another. The result of such a comparison
can be TRUE, FALSE, or UNKNOWN.

A logical operator combines the results of two


component conditions to produce a single result
based on them or to invert the result of a single
condition.
Returns TRUE if both component conditions are
TRUE. Returns
either is FALSE.
Returns
TRUE ifFALSE
eitherifcomponent
condition is
Otherwise
returns
UNKNOWN.
TRUE.
Returns
FALSE
if both are FALSE.
Otherwise returns UNKNOWN.

Set operators combine the results of two


component queries into a single result. Queries
containing set operators are called compound
queries.
Combine two or more query results. Eliminate
duplicates..Data types must be same for
number of columns in both statements.
All rows selected by either query, including all
duplicates. .Data types must be same for
number of columns in both statements.

All distinct rows selected by the first query but


not the second..Data types must be same for
number of columns in both statements.
Used to combine two select statements, but
only returns the records which are common
from both SELECT statements.Data types must
be same for number of columns in both
statements.

TOPIC

SQL Functions
Number Functions
CEIL
FLOOR

ROUND
MOD
ABS
POWER

TRUNC
Character Functions

LTRIM

RTRIM
TRIM
LOWER
UPPER
INIPCAP

LPAD

RPAD
SUBSTR
REPLACE

Character Functions Returning Number Values

INSTR
LENGTH
LENGTHB

Date Functions

CURRENT_DATE
CURRENT_TIMESTAMP
SYSDATE

SYSTIMESTAMP
EXTRACT

ADD_MONTHS

TO_CHAR

LAST_DAY

MONTHS_BETWEEN
NEXT_DAY
YEAR,MONTH,DAY,HH,MM,SS,YY,MM,DD,MON,DY

Conversion Functions

CAST

TO_DATE

Grouping FunctionsOR Aggregate Functions

MAX
MIN
SUM
AVG
COUNT
Other Functions

CASE
NVL

DECODE

EXAMPLE

SELECT CEIL(15.7) "Ceiling" FROM DUAL;


SELECT FLOOR(15.7) "Floor" FROM DUAL;
SELECT ROUND (54.339, 2) FROM DUAL;
SELECT MOD(11,4) "Modulus" FROM DUAL;
SELECT ABS(-15) "Absolute" FROM DUAL;
SELECT POWER(3,2) "Raised" FROM DUAL;
SELECT TRUNC(29.792333,1) "Truncate" FROM DUAL;
SELECT TRUNC(29.792333,-1) "Truncate" FROM DUAL;

SELECT LTRIM ('xyxXxyLAST WORD','xy') "LTRIM example" FROM DUAL

SELECT RTRIM ('TURNERyxXxy', 'xy') "RTRIM example" FROM DUAL;


SELECT TRIM ('OLD' FROM 'OLDMAN') FROM DUAL;
SELECT LOWER('LOWER') FROM DUAL;
SELECT UPPER('Carol') FROM DUAL;
SELECT INITCAP('the soap') "Capitals" FROM DUAL;
SELECT LPAD('Page 1',15,'*') "LPAD example"
FROM DUAL;
SELECT RPAD('BADRI',15,'*') FROM DUAL
SELECT SUBSTR('ABCDEFG',3,4) "Substring"
FROM DUAL;
SELECT REPLACE('JACK and JUE','J','BL') "Changes"
FROM DUAL;

SELECT INSTR('CORPORATE FLOOR','O')


"Instring" FROM DUAL;
SELECT LENGTH('CANDIDE') "Length in characters"
FROM DUAL;
SELECT LENGTHB ('CANDIDE') "Length in bytes"
FROM DUAL;

SELECT CURRENT_DATE FROM DUAL


SELECT CURRENT_TIMESTAMP FROM DUAL
SELECT SYSDATE FROM DUAL

SELECT SYSTIMESTAMP FROM DUAL;


SELECT EXTRACT (YEAR FROM SYSDATE) FROM DUAL
SELECT ADD_MONTHS ('12-MAR-2013', 3) FROM DUAL;

SELECT TO_CHAR(SYSDATE,'MONTH') FROM DUAL


select last_day(sysdate) from dual
SELECT SYSDATE,
LAST_DAY(SYSDATE) "Last",
LAST_DAY(SYSDATE) - SYSDATE "Days Left"
FROM DUAL;

select MONTHS_BETWEEN(sysdate,'30-MAR-12') from dual


SELECT NEXT_DAY('12-MAR-2014','WEDNESDAY') "NEXT DAY" FROM D

SELECT CAST(IP_NAME AS VARCHAR(50)) FROM INVOLVED_PARTY

SELECT TO_DATE('JAN 15, 19', 'MON DD, YY') FROM DUAL

SELECT
SELECT
SELECT
SELECT
SELECT

MAX(sal) "Maximum" FROM emp


MIN(SAL) "MININUM" FROM EMP
SUM(SAL) "SUM" FROM EMP
AVG(sal) "Average" FROM emP
COUNT(*) "Total" FROM emp

SELECT SAL, CASE WHEN SAL>1000 AND SAL < 2000 THEN 'A'
WHEN SAL >2000 AND SAL <3000 THEN 'B' END AS RANK
FROM EMP
SELECT COMM, NVL(COMM,0) FROM EMP

SELECT DECODE (SAL,5000, 'HIGHSAL') FROM EMP

PURPOSE
SQL functions are similar to SQL operators in that both manipulate data items
and both return a result. SQL functions differ from SQL operators in the
format in which they appear with their arguments.
Number functions accept numeric input and return numeric values.
Returns smallest integer greater than or equal to n.
Returns largest integer equal to or less than n.
Returns n rounded to m places to the right of the decimal point; if m is
omitted, to 0 places. m can be negative to round off digits left of the decimal
point. m must be an integer.
MOD returns the remainder of n2 divided by n1. Returns n2 if n1 is 0.
ABS returns the absolute value of n.
POWER returns n2 raised to the n1 power.
The TRUNC (number) function returns n1 truncated to n2 decimal places. If
n2 is omitted, then n1 is truncated to 0 places.
Single row character functions accept character input and can return both
character and number values.
Returns the string argument char, with its left-most characters removed up to
the first character which is not in the string argument set, which defaults to
(a single space).
Returns the string argument char, with its right-most characters removed
following the last character which is not in the string argument set. This
defaults to ' ' (a single space).
Removes leading and/or trailing blanks (or other characters) from a string.
Returns a string argument char, with all its letters in lowercase.
Returns the string argument char with all its letters converted to uppercase.
Returns char, with the first letter of each word in uppercase, all other letters
in lowercase.
LPAD returns expr1, left-padded to length n characters with the sequence of
characters in expr2. This function is useful for formatting the output of a
query.
RPAD returns expr1, right-padded to length n characters with expr2,
replicated as many times as necessary. This function is useful for formatting
the output of a query.
The SUBSTR functions return a portion of char, beginning at character
position, substring_length characters long.
REPLACE returns char with every occurrence of search_string replaced with
replacement_string.

Some character functions return only number values.


The INSTR functions search string for substring. The function returns an
integer indicating the position of the character in string that is the first
character of this occurrence.
The LENGTH functions return the length of char. LENGTH calculates length
using characters as defined by the input character set.
LENGTHB uses bytes instead of characters.
Date functions operate on values of the DATE datatype. All date functions
return a value of the DATE datatype, except the MONTHS_BETWEEN function
which returns a number.
CURRENT_DATE returns the current date in the session time zone, in a value
in the Gregorian calendar of datatype DATE.
CURRENT_DATE returns the current date in the session time zone, in a value
in the Gregorian calendar of datatype DATE.
SYSDATE returns the current date and time set for the operating system on

which the database resides.


SYSTIMESTAMP returns the system date, including fractional seconds and time

zone, of the system on which the database resides.


EXTRACT extracts and returns the value of a specified datetime field from a
datetime or interval value expression.
TO_CHAR (datetime) converts a datetime or interval value of DATE,
TIMESTAMP, TIMESTAMP WITH TIME ZONE, or TIMESTAMP WITH LOCAL TIME
ZONE datatype to a value of VARCHAR2 datatype in the format specified by
the date format fmt.

LAST_DAY returns the date of the last day of the month that contains date.
The return type is always DATE
MONTHS_BETWEEN returns number of months between dates date1 and
date2. If date1 is later than date2, then the result is positive. If date1 is
earlier than date2, then the result is negative.
NEXT_DAY returns the date of the first weekday named by char that is later
than the date date.

Conversion functions convert a value from one datatype to another.


Generally, the form of the function name follows the convention datatype TO
datatype. The first datatype is the input datatype; the last datatype is the
output datatype.

CAST converts one built-in datatype or collection-typed value into another


built-in datatype or collection-typed value.
TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2
datatype to a value of DATE datatype. The fmt is a datetime model format
specifying the format of char. If you omit fmt, then char must be in the
default date format.

Aggregate functions return a single result row based on groups of rows,


rather than on single rows. Aggregate functions can appear in select lists and
in ORDER BY and HAVING clauses.
MAX returns maximum value of expr.
MIN returns MINIMUM value of expr.
SUM returns the sum of values of expr.
AVG returns average value of expr.
COUNT returns the number of rows returned by the query.

CASE expressions let you use IF ... THEN ... ELSE logic in SQL statements
NVL lets you replace null (returned as a blank) with a string in the results of a query.
DECODE compares expr to each search value one by one. If expr is equal to a
search, then Oracle Database returns the corresponding result.

sults of a query.

TOPIC
WHERE

EXAMPLE
SELECT* FROM EMP WHERE COMM IS NULL

GROUP BY

SELECT DEPTNO,SUM(SAL) TOTAL FROM EMP GROUP

HAVING

SELECT EMPNO,COUNT(*) FROM EMP GROUP BY


EMPNO HAVING COUNT(*)>1
SELECT * FROM EMP

FROM

SELECT ENAME,DEPTNO FROM EMP


SELECT DISTINCT DEPTNO FROM EMP

DISTINCT
ORDER BY

SELECT ENAME,SAL TOTAL FROM EMP ORDER BY SAL


DESC

PURPOSE
A WHERE clause is an optional part of a SelectExpression, DELETE statement, or UPDATE statement.

A GROUP BY clause, part of a SelectExpression, groups a result into subsets that have matching value
more columns. In each group, no two rows have the same value for the grouping column or columns.
considered equivalent for grouping purposes.

A HAVING clause restricts the results of a GROUP BY in a SelectExpression. The HAVING clause is appli
group of the grouped table, much as a WHERE clause is applied to a select list. If there is no GROUP B
the HAVING clause is applied to the entire result as a single group.

The FROM clause is a mandatory clause in a SelectExpression. It specifies the tables (TableExpression
the other clauses of the query can access columns for use in expressions.
The DISTINCT clause acts as a filter to remove duplicate records from a result set. It ensures that any
are returned are unique for the column or columns specified in the SELECT statement.
The ORDER BY clause is an optional element of a SELECT statement. An ORDER BY clause allows you
the order in which rows appear in the ResultSet.

TOPIC

JOINS
EQUI JOIN
NON EQUI JOIN
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
CROSS JOIN
SELF JOIN

EXAMPLE

SELECT E.ENAME,D.DEPTNO FROM EMP E, DEPT D


WHERE E.DEPTNO=D.DEPTNO
SELECT E.ENAME,D.DEPTNO FROM EMP E, DEPT D
WHERE E.DEPTNO<>D.DEPTNO
SELECT * FROM emp INNER JOIN dept ON emp.Deptno = dept.Deptno;
SELECT * FROM emp LEFT OUTER JOIN dept ON emp.Deptno = dept.Deptno;
SELECT * FROM EMP RIGHT OUTER JOIN DEPT ON EMP.Deptno = DEPT.Deptno
SELECT * FROM EMP FULL OUTER JOIN DEPT ON EMP.Deptno = DEPT.Deptno
SELECT * FROM EMP CROSS JOIN DEPT

PURPOSE
A
join is a query that combines rows from two or more tables.If any
two of these tables have a column name in common, then you must
qualify all references to these columns throughout the query with
table names to avoid ambiguity. The columns in the join conditions
need
not also
appear
in the
select
list. containing an equality
An
equijoin
is a
join with
a join
condition
operator.
An equijoin
combines
have
equivalent
values for
An
NONEQUI
JOIN returns
rows rows
from that
the left
side
of the predicate
for
the specified
columns.
which
there are
no corresponding rows on the right side of the
predicate.
It returns rows
failAto
match
IN)Bthe
subquery
on
Inner
Join compares
each that
row of
with
each(NOT
row of
to find
all pairs
the
right
side.
of rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are
combined
into
a
result
row.
The
result
of a
left
outer
join
(orclosely
simplyresembles
left join) for
tables
A and
A
right
outer
join
(or
right
join)
a left
outer
join,B
always with
contains
all recordsof
ofthe
thetables
"left" table
(A), even
the from
join- the
except
the treatment
reversed.
Everyifrow
condition
does
any
matching
record
in at
the
"right"
table
(B).
"right"
table
(B)
willfind
appear
in combines
the joined
table
least
once.
If both
no
Conceptually,
anot
full
outer
join
the
effect
of
applying
matching
rowouter
from the
"left"
table
(A) exists,
appear
in
left
and right
joins.
Where
records
in theNULL
FULLwill
OUTER
JOINed
columns
A for those
records
match
in B.for every
tables
dofrom
not match,
the result
setthat
willhave
haveno
NULL
values
column of the table that lacks a matching row. For those records that
do match,
a returns
single row
be produced
in of
the
result
settables in the
CROSS
JOIN
thewill
Cartesian
product
rows
from
join. In other words, it will produce rows which combine each row from
the first table with each row from the second table
A self-join is joining a table to itself

TOPIC
Column Level

PRIMARY KEY

FOREIGN KEY

NOT NULL

UNIQUE

CHECK

DEFAULT

Table Level

PRIMARY KEY

UNIQUE

ALTERING CONSTRAINTS

DEFAULT

PRIMARY KEY

FOREIGN KEY

UNIQUE

CHECK

DROP CONSTRAINTS

EXAMPLE
CREATE TABLE PRODUCTS
CREATE
TABLE TRANSACTIONS1
(
(PRODUCT_CODE NUMBER(10) PRIMARY KEY,
PRODUCT_CODE
PRODUCT_NAME NUMBER(10),
VARCHAR(50),
PRODUCT_NAME
VARCHAR(50),
PRICE NUMBER (5)
QTY
NUMBER
(3),
)
PRICE NUMBER (5) NOT NULL,
TOTAL_PRICE NUMBER(5),
CREATE
TABLETRANS_PROD_CODE
PRODUCTS
CONSTRAINT
FOREIGN KEY (PRODUCT_CODE) REFERENCES PRODUCTS (PRODUC
()
PRODUCT_CODE NUMBER(10) ,
CREATE
TABLE PRODUCTS
PRODUCT_NAME
VARCHAR(50) NOT NULL,
(PRICE NUMBER (5) NOT NULL
PRODUCT_CODE
NUMBER(10) PRIMARY KEY,
)CREATE TABLE CONSTR_CHECK
PRODUCT_NAME VARCHAR(50) NOT NULL,
(PRICE NUMBER (5) NOT NULL,
AC
NUMBER
(10) (10)
PRIMARY
KEY,
PHONE
NUMBER
UNIQUE
CREATE
TABLE IP_Profile_t
TRANS_AMOUNT
NUMBER
(10)
NOT NULL,
)(
PHONE NUMBER(10) UNIQUE ,
cid
int NOT NULL,
WITHDRAW_AMOUNT
NUMBER (5),
LastName
varchar(255)
NULL,
CONSTRAINT abc CHECKNOT
(WITHDRAW_AMOUNT
between 100 and 25000)
FirstName
varchar(255),
)
Address varchar(255),
City varchar(255) DEFAULT 'NA'
)

CREATE TABLE TABLE_LEVEL_PK


(
COL1 CHAR(2),COL2 CHAR(3), COL3 CHAR(4), COL4 CHAR(5),
CONSTRAINT PK_TABLE_LEVEL_PK PRIMARY KEY (COL1,COL2)
CREATE
TABLE TABLE_LEVEL_UNIQUE
)
(
COL1 CHAR(2),COL2 CHAR(3), COL3 CHAR(4), COL4 CHAR(5),
CONSTRAINT UNIQUE_TABLE_LEVEL_PK unique (COL1,COL2)
)

ALTER TABLE Persons


MODIFY city DEFAULT 'koti'
alter table
persons
alter
table
add constraint
persons
pkk_p_id primary key (firstname)
add constraint
fk_cust_name FOREIGN KEY (p_id)
references
alter
table (product_code)
products
persons
add constraint
nn_price unique (p_id)
alter table
persons
add constraint
chk_city check (p_id in (123,124))

alter table CONSTR_CHECK drop constraint ABC

PURPOSE

A primary key constraint combines a NOT NULL constraint and a unique constraint in a single declarat

A foreign key constraint requires values in one table to match values in another table.

A NOT NULL constraint prohibits a database value from being null.

A unique constraint prohibits multiple rows from having the same value in the same column or combin

A check constraint requires a value in the database to comply with a specified condition.
The DEFAULT constraint is used to insert a default value into a column.The
default value will be added to all new records, if no other value is specified.

aint in a single declaration. That is, it prohibits multiple rows from having the same value in the same column o

same column or combination of columns but allows some values to be null.

condition.

n the same column or combination of columns and prohibits values from being null.

TOPIC

EXAMPLE

Nested Subquery

SELECT DEPTNO
DEPT(SELECT
d.deptno,FROM
d.dname,
WHERE DEPTNO
NOTeAS
IN SOURCE_TABLE
count(*)
FROM emp
SELECT
'IP_PROFILE'
(
WHERE
e.deptno =
,'SEQ#12-IP_NAME'
AS SOURCE_COLUMN
SELECT
EMP.DEPTNO
FROm
EMP
d.deptno)
AS "Num
,CURRENT_DATE
AS Dept"
DAY_EXECUTED
FROM deptAS
d;COUNTER
,COUNT(*)
);
,CASE
WHEN
COUNT(*)
=0 FROM
THEN 'PASS'
SELECT empno,
ename,sal
emp e
ELSE
'FIAL'
END
AS
REULTS
WHERE sal >
FROM
(
(SELECT AVG(sal) FROM emp WHERE deptno
SELECT
DEPTNO FROM DEPT
= e.deptno
MINUS
)
SELECT DEPTNO FROM EMP
)

Inline View
Scalar Subquery
Correlated Subquery

PURPOSE
The subquery appears in the WHERE clause of the SQL.
The subquery appears in the FROM clause of the SQL.
The subquery appears in the SELECT clause of the SQL
This is a type of nested subquery that uses columns from the
outer query in its WHERE clause. A correlated subquery is
evaluated once for each row.

SubQueries.txt

Topic
ROWID
ROWNUM
EXISTS
NOT EXISTS
ON DELETE CASCADE

column2 datatype null/not null,


...
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
Example
REFERENCES
parent_table (column1, column2, ... column_n)
SELECT
ROWID, ENAME
ON
DELETE
CASCADE
FROM EMP
); WHERE DEPTNO= 20;
SELECT ROWNUM,ENAME,EMPNO FROM EMP
SELECTan
DISTINCT
store_type
FROM stores
Using
ALTER TABLE
statement
WHERE EXISTS (SELECT * FROM cities_stores
You can use ROWNUM to limit the number of rows returned by a
WHERE
cities_stores.store_type
SELECT
DISTINCT
store_type
FROM stores = stores.store_type);
ALTER
table_name
query, TABLE
as in this
example:
WHERE
NOT EXISTS
(SELECT * FROM cities_stores
ADD
CONSTRAINT
constraint_name
WHERE
cities_stores.store_type
= stores.store_type);
FOREIGN
KEY
(column1,
... column_n)
SELECT * FROM employeescolumn2,
WHERE ROWNUM
< 11;
REFERENCES parent_table (column1, column2, ... column_n)
ON DELETE CASCADE;

The data block in the datafile in which the row resides


The position of the row in the data block (first row is 0)
Purpose
The datafile in which the row resides (first file is 1). The file
For
each
row
returned
by tablespace.
aisquery,
the
ROWNUM pseudocolumn
The
SQL is
EXISTS
condition
used in
combination
with a subquery
number
relative
to the
returns
a number indicating
order
in which
Oracle
the
and
is considered
to be met,the
if the
subquery
returns
atselects
least one
row fromEXISTS
a tablesubquery
or set of joined
selected
a
row.The
is usedrows.
whenThe
we first
wantrow
to display
allhas
rows
ROWNUM
of
1,with
the
second has
2, and
on.
where
wekey
have
a matching
column
in so
both
tables.
In most
A
foreign
cascade
delete
means
that
if a record
in cases,
the
this type
of subquery
can
be the
re-written
with a standard
to
parent
table
is deleted,
then
corresponding
records join
in the
improve
performance.
child table with automatically be deleted. This is called a cascade
The NOT
delete
in EXISTS
Oracle. subquery is used to display cases where a
selected column does not appear in another table.
A foreign key with a cascade delete can be defined in either a
CREATE TABLE statement or an ALTER TABLE statement.

You might also like