You are on page 1of 49

SQL Document

DDL - Data Definition Language


Data Definition Language or DDL commands in standard query language (SQL) are used to describe/define the database
schema - DDL commands are CREATE, ALTER, DROP, TRUNCATE.

Command Description
CREATE Used for creating database objects like a database and a database table.
ALTER Used for modifying and renaming elements of an existing database table.
DROP Used for removing an entire database or a database table.
TRUNCATE Used to remove all the records from a database table.
COMMENT Used to write comments within SQL queries. Single-line comment -- , Multi-line comment -
/* …… */

CREATE TABLE:

Syntax: -
CREATE TABLE table_name (
column_1 data_type column_constraint,
column_2 data_type column_constraint,
...
table_constraint
);
Query: -
CREATE TABLE supplier_details (
suplier_id NUMBER NOT NULL,
supplier_name VARCHAR2(20),
city VARCHAR2(20),
state_name VARCHAR2(25),
total_spent NUMBER(9, 2)
);

Output: -
Inserting values into table: -
INSERT INTO supplier_details (
suplier_id,
supplier_name,
city,
state_name,
total_spent)
WITH names AS (
SELECT 200,'Instant_Assemblers','Reedwood_City','California',90500.00 FROM dual UNION ALL
SELECT 300,'Time_manifacturers','Newyork_City','Newyork',78150.00 FROM dual UNION ALL
SELECT 400,'Roundhoude_Inc','Portland','Georgia',32000.00 FROM dual UNION ALL
SELECT 500,'Smiths_and_Barries','Yuma','Alaska',114600.00 FROM dual
)
SELECT * FROM names

Output: -

Select query to view the inserted values:

Select * from supplier_details;


ALTER:

Syntax for renaming table name: -


ALTER TABLE table_name_1
RENAME TO table_new_name;

Query: -
ALTER TABLE supplier_details
RENAME TO Suppliers;

Output: -

Syntax for adding new column in existing table: -


ALTER TABLE table_name
ADD (Columnname_1 datatype);

Query: -
ALTER TABLE Suppliers
ADD (Inactive_Active varchar2(20));

Output: -

Syntax for deleting a column in existing table: -


ALTER TABLE table_name
DROP COLUMN columnname_1 , columnname_2, ...;

Query: -
ALTER TABLE Suppliers
DROP column Inactive_Active;

Output: -
TRUNCATE:

Syntax: -
TRUNCATE TABLE table_name;

Query: -
TRUNCATE TABLE Suppliers_drop;

Output: -

DROP:

Syntax: -
DROP TABLE table_name;

Query: -
DROP TABLE Suppliers_drop;

Output: -
DML - Data Manipulation Language
Data Manipulation Language (DML) commands in SQL deals with manipulation of data records stored within the
database tables. It does not deal with changes to database objects and its structure. The commonly known DML
commands are INSERT, UPDATE and DELETE.

Command Description
INSERT Used to insert new data records or rows in the database table
UPDATE Used to set the value of a field or column for a particular record to a
new value.
DELETE Used to remove one or more rows from the database table

INSERT:

Syntax for inserting single record: -


INSERT INTO table_name (column_name_1, column_name_2, column_name_3, ...)
VALUES (value1, value2, value3, ...);

Query: -
INSERT
INTO suppliers (suplier_id,
supplier_name,
city,
state_name,
total_spent
)
values ( 800,'Instant_Assemblers','Reedwood_City','California',90500.00 );

Query for inserting multiple records: -


INSERT INTO suppliers (
suplier_id,
supplier_name,
city,
state_name,
total_spent)
WITH names AS (
SELECT 200,'Instant_Assemblers','Reedwood_City','California',90500.00 FROM dual UNION ALL
SELECT 300,'Time_manifacturers','Newyork_City','Newyork',78150.00 FROM dual UNION ALL
SELECT 400,'Roundhoude_Inc','Portland','Georgia',32000.00 FROM dual UNION ALL
SELECT 500,'Smiths_and_Barries','Yuma','Alaska',114600.00 FROM dual
)
SELECT * FROM names;
UPDATE:

Syntax: -
UPDATE table_name
SET column_name_1 = value1, column_name_2 = value2, ...
WHERE condition;

Query: -
UPDATE suppliers
SET
suplier_id = 600,
total_spent = 10500.00
WHERE
suplier_id = 800
AND total_spent = 90500.00;

Output: -

DELETE:

Syntax: -
DELETE FROM table_name WHERE condition;

Before execution: -
Query: -

DELETE FROM Suppliers WHERE suplier_id=1000;

Output: -

Query: -

DELETE FROM Suppliers WHERE suplier_id=1300 or TOTAL_SPENT=78150 ;

DCL - Data Control Language


DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions, and other controls
of the database system.

Command Description
GRANT This command gives users access privileges to the database
REVOKE This command withdraws the user’s access privileges given by using the GRANT
command.

GRANT:

Query:-

GRANT SELECT ON sa_application FROM PRDMMISHBT;


DQL - Data Query Language
SELECT command or statement in SQL is used to fetch data records from the database table.

Command Description
SELECT Used to query or fetch selected fields or columns from a database table

SELECT:

Syntax: -
SELECT column_name1, column_name2, …
FROM table_name
WHERE condition_ expression;

Query: -
SELECT supplier_name, state_name, suplier_id, total_spent
FROM suppliers
WHERE state_name IN ('Georgia', 'Alaska')
AND (suplier_id = 400 OR suplier_id > 600)
AND total_spent < 50000;

Output: -

TCL - Transaction Control Language


Transaction Control Language commands are used to manage transactions in the database. These are used to manage
the changes made by DML-statements.

Command Description
COMMIT Commit command is used to permanently save any transaction into the database.
ROLLBACK This command restores the database to last committed state. It is also used with
savepoint command to jump to a savepoint in a transaction.
SAVEPOINT Savepoint command is used to temporarily save a transaction so that you can rollback to
that point whenever necessary.
JOINS
Joins - Definition
A join is a concept that allows us to retrieve data from two or more tables in a single query.

TYPES OF JOINS:-

Natural join
Inner join
Outer join
Self join
Cross join
Equi join
Non-equi join

TABLES USED FOR BELOW QUERIES:-


SUPPLIERS table:

SUPPILER_JOIN table:-
SUPPLIER_LOCATION table:-

Suppiler_Non-equijoin table:

NATURAL JOIN:-

In Natural joins, Common columns are written just once in the output.
SYNTAX:

SELECT column FROM table1 NATURAL JOIN table2;

EXAMPLE :-

Query:

SELECT * FROM suppliers NATURAL JOIN suppiler_join;

Output:
SPECIFY COLUMNS:
SELECT
suplier_id,
supplier_name,
status_cid,
total_spent
FROM
suppliers NATURAL JOIN suppiler_join;

HANDLING AMBIGUOUS COLUMN NAMES:-


Query:
SELECT
suplier_id,
supplier_name,
status_cid,
total_spent,
application_sid
FROM
suppliers
JOIN suppiler_join USING ( suplier_id );

Output:

To avoid ambiguous column name error , We use Alias name for tables.
Query:

SELECT
suplier_id,
ss.supplier_name,
sj.status_cid,
ss.total_spent,
sj.application_sid
FROM
suppliers ss
JOIN suppiler_join sj USING ( suplier_id );

Output:

Inner join:-
Return all the rows from both the tables that satisfy the join condition or the expression of the ON /USING clause.

SYNTAX:-

SELECT column FROM table1 INNER JOIN table2

ON (join condition);

QUERY:-

SELECT
sj.application_sid,
ss.suplier_id,
sj.status_cid,
ss.total_spent,
ss.supplier_name
FROM
suppliers ss
INNER JOIN suppiler_join sj ON (SS.suplier_id=SJ.suplier_id AND ss.supplier_name=SJ.supplier_name );
OUTPUT:-

MULTIPLE JOIN OPRATION:-


Query:-

SELECT
sj.application_sid,
ss.suplier_id,
sj.status_cid,
ss.total_spent,
ss.supplier_name,
l.location_id,
l.POSTAL_CODE
FROM
suppliers ss
INNER JOIN suppiler_join sj ON (SS.suplier_id=SJ.suplier_id )
join Suppiler_Location l ON (ss.suplier_id=l.suplier_id) ;

Output:

SELF-JOIN :-
Joining a table with itself is called self-join.
A self-join is used for comparing rows in the same table.
Outer join:-
The outer join returns the matching rows from the joined tables, plus, unmatched rows from one or both tables.

There are three types of outer joins:-


1- Left outer join
2- Right outer join
3- Full outer join

Left outer join:-


The Left outer join returns all the matching rows of both tables and the unmatched rows of the left table. For the
unmatched rows, the column values of other tables are shown as NULL.

Query:-

SELECT
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
l.location_id,
l.POSTAL_CODE
FROM
suppliers ss
LEFT OUTER JOIN Suppiler_Location l ON (ss.suplier_id=l.suplier_id) ;
Output:-

Right outer join:-


The Right outer join returns all the matching rows of both tables and the unmatched rows of the right table. For the
unmatched rows, the column values of other tables are shown as NULL.

SYNTAX:

SELECT
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
l.location_id,
l.POSTAL_CODE
FROM
suppliers ss
RIGHT OUTER JOIN Suppiler_Location l ON (ss.suplier_id=l.suplier_id) ;

OUTPUT:

FULL OUTER JOINS:-


Retrieves of the rows from both tables. If a match is found, then, it displays the matching rows, If not , It displays NULL
values.
Full outer join is combination of the left outer join and right outer join.

Query:

SELECT
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
l.location_id,
l.POSTAL_CODE
FROM
suppliers ss
FULL OUTER JOIN Suppiler_Location l ON (ss.suplier_id=l.suplier_id) ;

Output:
CROSS JOIN (Cartesian Product & Cross Product)
Cross join are used to return every combination of rows from two tables.
Cross join is also called as Cartesian product.

Example:-

Suppiler_Location table have 8 Rows


Suppliers table have 9 Rows
Output result is 72 Rows.
Query:

SELECT
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
l.location_id,
l.POSTAL_CODE
FROM
suppliers ss
CROSS JOIN Suppiler_Location l ;

Output:
EQUI JOINS:-

Retrieving data from the multiple tables based on an equality condition (=).
Cannot use the following operators are (<, > , <= , >= , !< , !> , <> / !=).

NON-EQUI JOINS (Joining unequal tables) :-


If two tables do not match with column , We can join these tables using BETWEEN operator , or comparison operators (<
, > , <= , >= , <>).
Query:

SELECT

ss.suplier_id,
ss.total_spent,
ss.supplier_name,
nq.max_spent
FROM
suppliers ss
JOIN suppiler_Nonequijoin nq ON ss.total_spent < nq.max_spent;

Output:

NON-EQUI JOIN USAGES:-

1- Checking for duplicates.


2- Matching against a range of values
3- Computing running totals
CONSTRAINTS
Constraints restrict data entry (insert, delete, update) and prevent invalid entries. We can add constraints while creating
the table or we can add them later on. Constraints can be at the column level and table level. The functionality of table
level and column level is same. Constraint names must be unique to the schema.

THERE ARE 5 TYPES OF CONSTRAINTS: -

1. Not null constraint


2. Unique constraint
3. Primary key constraint
4. Foreign key constraint
5. Check constraint

NOT NULL CONSTRAINT:-

NOT NULL constraints prevent the insertion of NULL values into a column. NOT NULL constraints can only be created at
the column-level.

Query:

CREATE TABLE supplier_const (


suplier_id NUMBER NOT NULL,
supplier_name VARCHAR2(20)
CONSTRAINT namenn NOT NULL,
city VARCHAR2(20),
state_name VARCHAR2(25),
total_spent NUMBER(9, 2) NOT NULL
);

Output:

EXAMPLE shows error when inserting NULL values: -


INSERT INTO supplier_const (
suplier_id,
supplier_name,
city,
state_name,
total_spent
) VALUES (
1,
'swiggy',
'chennai',
'india',
NULL
);

UNIQUE CONSTRAINT:-

A UNIQUE constraints ensures uniqueness of a column which means no duplicate values will be inserted.
UNIQUE constraints based on multiple columns are called as composite unique keys.

Query:

CREATE TABLE supplier_const (


supply_code NUMBER ,
suplier_id NUMBER,
supplier_name VARCHAR2(20),
city VARCHAR2(20),
state_name VARCHAR2(25),
CONSTRAINT UQ_supp UNIQUE(suplier_id)
);

PRIMARY KEY Constraint: -

A PRIMARY KEY constraint is the combination of a NOT NULL and a UNIQUE constraint.

There can only be one PRIMARY KEY on a table.

Query:

CREATE TABLE suppliers (


supply_code NUMBER ,
suplier_id NUMBER
CONSTRAINT nameuq UNIQUE,
supplier_name VARCHAR2(20),
city VARCHAR2(20),
state_name VARCHAR2(25),
CONSTRAINT Pk_supply PRIMARY KEY(supply_code)
);
FOREIGN KEY constraint: -
A foreign key is a column or combination of columns used to enforce a relationship between a parent table and a child
table.

Query:

CREATE TABLE supplier_const (


supply_code NUMBER,
suplier_id NUMBER
CONSTRAINT nameuq UNIQUE,
supplier_name VARCHAR2(20),
city VARCHAR2(20),
state_name VARCHAR2(25),
CONSTRAINT fk_supply FOREIGN KEY ( supply_code )
REFERENCES suppliers ( supply_code )
);

CHECK CONSTRAINT:-
A CHECK constraint ensures a column or a group of column meets a specific condition.
We can use check constraint in arithmetic operations or conditional operations.

Query:

CREATE TABLE supplier_const (


supply_code NUMBER
CONSTRAINT pri_cons PRIMARY KEY,
suplier_id NUMBER
CONSTRAINT namechec CHECK ( supplier_id IN (
1,
2,
3,
4,
5
)
supplier_name VARCHAR2(20),
city VARCHAR2(20),
state_name VARCHAR2(25),
phone NUMBER(10),
CONSTRAINT chk_phone CHECK ( length(phone) = 10 )
);
DATE FUNCTIONS

Function Definition
ROUND Round date
TRUNC Truncate date
TIMESTAMP Return the date or datetime expression
NEXT_DATE Next day of the date given
LAST_DATE Last day of the month
ADD_MONTHS Add calendar months to date
MONTH_BETWEEN Number of month between two dates

Example: -

ASSUME SYSDATE= ‘20-JUL-22’;

Function Result
ROUND (SYSDATE,’MONTH’) 01-AUG-22
ROUND (SYSDATE,’YEAR’) 01-JAN-23
TRUNC (SYSDATE,’MONTH’) 01-JUL-22
TRUNC (SYSDATE,’YEAR’) 01-JAN-22
NEXT_DATE (SYSDATE,’WEDNESDAY’) 27-JUL-22
LAST_DATE (SYSDATE) 31-JUL-22
ADD_MONTHS(SYSDATE,’8’) 20-MAR-23

OPERATORS
SQL Operators:

Operators do calculations between the data items and execute the Query result. It provides a condition in SQL
statements or also combines multiple conditions and executes them.

Types of SQL Operators: -

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. String Operators

Arithmetic Operators: -
These operators are used to calculations like addition, multiplication, division, subtraction and other modulus numeric
values in the SQL query.

Syntax: Select <expression 1> operator <expression 2>


Query 1: -

SELECT
suplier_id,
supplier_name,
total_spent,
total_spent+100 AS EXTRA_SPENT
FROM
suppliers;

Output: -

Query 2: -

SELECT
suplier_id,
supplier_name,
total_spent,
total_spent - 1000 AS Discount_spent
FROM
suppliers;

Output:
Comparison Operators or Relational Operators:

It does the operations such as equal to (=), lesser than (<), greater than (>) or greater than equal to (>=) and
not equal to (!=) or inequality(<>).

Syntax:

SELECT column FROM table WHERE condition1 Relational Operator condition2;

a) Equal to (=)
This operator checks the value of the two operands is the same or not. If it is equal then it returns true, if not returns
false.

Query:

SELECT
suplier_id,
supplier_name
FROM
suppliers
where
total_spent=32000;

b) Not equal to or Inequality (! =), (<>)


It verifies whether the two operands’ values are equal or not. If they are not equal then the statement returns True.

Query:

SELECT
suplier_id,
supplier_name
FROM
suppliers
where
total_spent<>32000;

Output:
C) Greater than (>)
It is used in SQL to check for the greater than a value between two operands.

Query:

SELECT
suplier_id,
supplier_name
FROM
suppliers
where
total_spent>32000;

Output:

D) Greater than equal to (> =)


It is used in SQL to check for the greater than or equal to a value between two operands.

Query:

SELECT
suplier_id,
supplier_name
FROM
suppliers
where
total_spent>=32000;

Output:
e) Lesser than (<)
This operator in SQL is used to check whether a left operand is lesser than the right operand. If it is true it results in the
result.

Query:

SELECT
suplier_id,
supplier_name,
total_spent
FROM
suppliers
where
total_spent<78150;

Output:

f) Lesser than or Equal to (<=)

This operator in SQL is used to check whether a left operand is lesser than or equal to the right operand. If it is true it
results in the result.

Query:

SELECT
suplier_id,
supplier_name,
total_spent
FROM
suppliers
where
total_spent<=78150;

Output:
Logical Operators:
• AND
• OR
• NOT
• BETWEEN
• ANY

1. AND Operator - TRUE if all the conditions separated by AND is TRUE.

Query:
SELECT
suplier_id,
supplier_name,
total_spent
FROM
suppliers
where
total_spent=78150 and supplier_name='Time_manifacturers' ;

Output:

2. OR - TRUE if any of the conditions separated by OR is TRUE.

Query: -

SELECT
suplier_id,
supplier_name,
total_spent
FROM
suppliers
where
total_spent=32000 or supplier_name='Time_manifacturers' ;

Output:
3. NOT - Displays a record if the condition(s) is NOT TRUE.

Query: -

SELECT
suplier_id,
supplier_name,
total_spent
FROM
suppliers
where not
total_spent=32000 ;

Output:

4. BETWEEN - This operator is used when there is a limit range between the values.

Query:

SELECT
suplier_id,
supplier_name,
total_spent
FROM
suppliers
where
total_spent between 32000 and 90500;

Output:
String operators:
The string operators in SQL are used to perform important operations such as pattern matching, concatenation.

1. Concatenation Operator
The concatenation operation is used to combine character strings, columns of a table or it can also be used for the
combination of column and strings.

Query:
SELECT supplier_name || ' ' || suplier_id AS ConcatenatedName FROM Suppliers;

Output:

2. Like Operator
This operator is used to decide if the specific character string matches the specific pattern where the pattern can be a
regular or wildcard character.

Query: -
select * from suppliers where supplier_name like 'I%' ;

Output:
Query: -
select * from suppliers where supplier_name like '%n_' ;

Output:

Query: -
select * from suppliers where city like '____l%' ;

Output:

Order By:

ORDER BY clause in SQL helps us to categorize our data in either ascending or descending order, depending on the
columns of our tables. ORDER BY is the keyword used in our query to help us sort through the data. By default, a few
databases categorize the results returned by the query in ascending order. To sort the data present in the records in
descending order, we utilize the keyword DESC in our query.

Query:-

SELECT
suplier_id,
supplier_name,
city
FROM
suppliers
WHERE
city = 'Reedwood_City'
OR city = 'Yuma'
order
by suplier_id desc;

Output:
Sort By Ascending:-

Query: -

SELECT
suplier_id,
supplier_name,
total_spent,
city
FROM
suppliers
WHERE
city = 'Reedwood_City'
OR city = 'Yuma'
order
by 3 asc;

Output: -

Sort By Relative Position:


We can also arrange our data by the relative position of the columns, where 1 represents the first field, 2 represents the
second field, 3 represents the third field and so on.

Query: -
SELECT
suplier_id,
supplier_name,
city
FROM
suppliers
WHERE
city = 'Reedwood_City'
OR city = 'Yuma'
order
by 3 ;

Output: -
GROUP BY:

The GROUP BY statement groups rows that have the same values into summary rows.
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the
result-set by one or more columns.

Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s);

Example 1:

SELECT
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
count(ss.supplier_name)
FROM
suppliers ss
INNER JOIN suppiler_join sj ON (SS.suplier_id=SJ.suplier_id )
join Suppiler_Location l ON (ss.suplier_id=l.suplier_id)
group by ss.suplier_id,
ss.total_spent,
ss.supplier_name;

Output:

Example 2:

SELECT
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
COUNT(ss.supplier_name)
FROM
suppliers ss
INNER JOIN suppiler_join sj ON ( ss.suplier_id = sj.suplier_id )
JOIN suppiler_location l ON ( ss.suplier_id = l.suplier_id )
GROUP BY
ss.suplier_id,
ss.total_spent,
ss.supplier_name
ORDER BY
ss.suplier_id DESC;

Output:

HAVING CLAUSE:

The HAVING clause is used because the WHERE keyword cannot be used with aggregate functions.

Syntax:

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Example 1:

Query:

SELECT
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
ss.city,
AVG(ss.total_spent)
FROM
suppliers ss
INNER JOIN suppiler_join sj ON ( ss.suplier_id = sj.suplier_id )
JOIN suppiler_location l ON ( ss.suplier_id = l.suplier_id )
GROUP BY
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
ss.city
HAVING
AVG(ss.total_spent)>80000
ORDER BY
ss.suplier_id DESC;
Output:

Example 2:

Query:

SELECT
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
ss.city,
AVG(ss.total_spent)
FROM
suppliers ss
INNER JOIN suppiler_join sj ON ( ss.suplier_id = sj.suplier_id )
JOIN suppiler_location l ON ( ss.suplier_id = l.suplier_id )
where
ss.suplier_id>500
GROUP BY
ss.suplier_id,
ss.total_spent,
ss.supplier_name,
ss.city
HAVING
AVG(ss.total_spent)>80000
ORDER BY
ss.suplier_id DESC;

Output:
DISTINCT:-

Distinct command in SQL is used along with the Select command in order to retrieve only distinct or unique values from
a table. It is mainly used as a method to filter duplicate records and fetch only unique records from a given table, where
there is a possibility of fields having multiple duplicate records.

Syntax:

Select DISTINCT(column_name) from table_name;

Query:-

SELECT
distinct supplier_name
FROM
suppliers;

Output:

Query:

SELECT
count(distinct supplier_name)
FROM
Suppliers;

Output:
SUBQUERY

A Subquery is a SQL SELECT statement that is contained within another SELECT statement.
Inner query is executed first and result of the subquery is use input of the outer query.
Subqueries can be used with the SELECT, WHERE,FROM and HAVING clauses.

Using tables:
SUPPLIERS table

SUPPILER_LOCATION table

Query:

SELECT
supplier_name,
total_spent,
suplier_id
FROM
suppliers
WHERE
suplier_id=
(
SELECT
suplier_id
FROM
suppliers
WHERE
suplier_id =500
);
Output:

Using a Subqueries:

1- Enclose subqueries in parentheses.


2- Place subqueries on the right side of the comparison condition.
3- Use single-row operators with single-row subqueries, and use multiplerow operators with multiple-row
subqueries.

Types of Subqueries:
1- Single-row subqueries
2- Multi-row subqueries

Single-row subquery:

1- Return only one row


2- Use single-row comparison operators(< ,>,=, <=,>= <>)

Multi-row subquery:
1- Return more than one row.
2- Use multi-row comparison operators(IN,ANY,ALL)

Example 1:

Query:

SELECT
COUNT(city)
FROM
suppliers
WHERE
city IN (
SELECT
city
FROM
suppliers
WHERE
total_spent > 50000
);

Output:
Example 2:
Query:

SELECT
ss.supplier_name,
ss.total_spent,
ss.suplier_id,
l.location_id,
l.postal_code
FROM
suppliers ss join suppiler_location l on ss.suplier_id=l.suplier_id
WHERE
ss.supplier_name in (
SELECT
supplier_name
FROM
suppliers
WHERE
supplier_name ='Instant_Assemblers'
);

Output:
SEQUENCES
Sequence:
1- Can automatically generate unique numbers.
2- Is a sharable object.
3- Can be used to create a primary key value.
4- Replaces application code.
5- Speeds up the efficiency of accessing sequence values when cached in memory.

Define a sequence to generate sequential numbers automatically:

CREATE SEQUENCE sequence


[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | nocache}]

NEXTVAL and CURRVAL Pseudocolumns:


NEXTVAL returns the next available sequence value. It returns a unique value every time it is referenced, even for
different users.
CURRVAL obtains the current sequence value.

Caching Sequence Values:

Caching sequence values in memory gives faster access to those values.

Gaps in sequence values can occur when:

1- A rollback occurs
2- The system crashes
3- A sequence is used in another table

To remove a Sequence, use DROP statement.


VIEWS
It is the user object.
View is the virtual table.
It saves query permanently in the database.
It does not occupy table space.

Simple View:

1- Simple views are views that are created on a single table.


2- We can perform only basic SQL operations in simple views. That means, we cannot perform analytical and
aggregate operations by grouping, sets, etc. in simple views.
3- We can perform insert, update, delete directly from a simple view, but for that, we must have the primary
key column in the view.

Complex View:

1- Complex views as the name suggest are a bit complicated compared to simple views.
2- Complex views are created on more than one database table. We can perform analytical and aggregate
operations in complex views, but unlike simple views.
3- we cannot perform insert, delete, and update directly from a complex view.

SYNTAX:

CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view


alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];

To drop view:
DROP VIEW view;

Advantages of Views:

1- To restrict data access.


2- To make complex query easy.
3- To provide data independence.
4- To present different views of the same data.

SYNTAX:
Query:

SELECT * FROM user_views WHERE view_name='sa_application';


EXPRESSIONS:-

If
Then
Else
Case
Decode

Case…When…Else…. Expression:

1- CASE: It is an essential keyword that is always used to mark the beginning of a CASE statement.
2- WHEN when_condition_1: It is a simple conditional expression like IF condition which is evaluated for TRUE
or FALSE, based on that result_expression_1 is returned if WHEN is evaluated to TRUE or ELSE statement is
evaluated if WHEN is evaluated to FALSE.
3- ELSE result_expression: Simple conditional expression which is evaluated WHEN condition is evaluated to
FALSE.
4- END: It is an essential keyword that is always used to mark the ending of a CASE statement. We can provide
an alias to the CASE using AS.

Syntax:

CASE
WHEN when_condition_1 THEN result_expression_1
WHEN when_condition_2 THEN result_expression_2
.
.
.
WHEN when_condition_n THEN result_expression_n
ELSE result_expression
END AS case_name;

DECODE:
DECODE (expression , search_1, result_1[, search_2, result_2], ...,[,search_n,result_n] [, default]);

SET Operators

- You can combine multiple queries using the set operators UNION, UNION ALL, INTERSECT, and MINUS.
- Expressions in the select lists of the component queries of a compound query must match in number and must be in
the same datatype.

Restrictions on the Set Operators :

1- The set operators are not valid on columns of type BLOB, CLOB, BFILE, VARRAY, or nested table.
2- The UNION, INTERSECT, and MINUS operators are not valid on LONG columns.
SET OPERATORS:-

UNION All distinct rows selected by either query.


UNION ALL All rows selected by either query, including all duplicates.
INTERSECT All distinct rows selected by both queries.
MINUS All distinct rows selected by the first query but not the second.

USING TABLE:

SUPPLIERS table

SUPPILER_LOCATION table

UNION
Query:

SELECT
location_id
FROM
suppiler_location
union
select
suplier_id
from
suppliers;

Output:
UNION ALL
Query:

SELECT
location_id
FROM
suppiler_location
union all
select
suplier_id
from
suppliers;

Output:
Handling Duplicates: -
Using DISTINCT:
The SQL DISTINCT keyword, used with the SELECT statement to eliminate all the duplicate records and by fetching only
the unique records.

The basic syntax of a DISTINCT keyword to eliminate duplicate records.

SELECT DISTINCT column1, column2,.....columnN


FROM table_name
WHERE [condition]

Query: -
SELECT distinct
ss.supplier_name,
ss.total_spent,
ss.suplier_id,
l.location_id,
l.postal_code
FROM
suppliers ss join suppiler_location l on ss.suplier_id=l.suplier_id ;

Output:

Using subquery to delete duplicate rows:

DELETE FROM
table_name A
WHERE
a.rowid >
ANY (
SELECT
B.rowid
FROM
table_name B
WHERE
A.col1 = B.col1
AND
A.col2 = B.col2
);

SYNONYMS

A synonym is a database object created to give an alternated name to another database object.
We can think of synonyms simply as an alias.
No need for additional privileges for the synonyms.
Useful for hiding the identity and location of the related object.

Synonym will be created in the one schema to see the table which are granted in another schema.

SYNTAX:

CREATE OR REPLACE SYNONYM table_name FOR DBdetails.table_name;

Aggregate functions

Aggregate functions in SQL are used for performing calculations on an entire column(which could have thousands of
rows).

SYNTAX:

SELECT AGGREGATE_FUNCTION (column_name)


FROM table_name
WHERE condition;
The SQL aggregate functions are
1- AVG
2- COUNT
3- MIN / MAX
4- SUM

USING TABLE:

SUPPLIERS table
COUNT

Query:

SELECT count(city) FROM suppliers WHERE STATE_NAME='California';

Output:

SUM

Query:

SELECT SUM(total_spent) FROM suppliers WHERE CITY='Reedwood_City';

Output:

AVG

Query:

SELECT Round(AVG(total_spent),2) FROM suppliers WHERE CITY='Reedwood_City';

Output:

MIN

Query:
SELECT MIN(total_spent) FROM suppliers;

Output:
MAX

Query:

SELECT MAX(total_spent) FROM suppliers;

Output:

PLSQL Document
TRIGGERS:
- 12 Triggers applied for maximum single table.
- Trigger is a special type of stored procedure.
- Trigger can be executed automatically fire in insert or update / delete invoke table modification time.
- Trigger one of use in auditing purpose.

Types of Triggers:

Triggers can be classified based on the following parameters.


Classification based on the timing

BEFORE Trigger: It fires before the specified event has occurred.


AFTER Trigger: It fires after the specified event has occurred.
INSTEAD OF Trigger: A special type. You will learn more about the further topics. (only for DML )

Classification based on the level

STATEMENT level Trigger: It fires one time for the specified event statement.
ROW level Trigger: It fires for each record that got affected in the specified event. (only for DML)

Classification based on the Event

DML Trigger: It fires when the DML event is specified (INSERT/UPDATE/DELETE)


DDL Trigger: It fires when the DDL event is specified (CREATE/ALTER)
DATABASE Trigger: It fires when the database event is specified (LOGON/LOGOFF/STARTUP/SHUTDOWN)

NOTE:
- A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT operation is executed.
- It indicates that the trigger will fire before the INSERT operation is executed.
- Generating some derived column values automatically
- Preventing invalid transactions
SYNTAX:

CREATE [ OR REPLACE ] TRIGGER <trigger_name>

[BEFORE | AFTER | INSTEAD OF ]

[INSERT | UPDATE | DELETE......]

ON<name of underlying object>

[FOR EACH ROW]

[WHEN<condition for trigger to get execute> ]

DECLARE
<Declaration part>
BEGIN
<Execution part>
EXCEPTION
<Exception handling part>
END;

Compound Trigger:

The Compound trigger is a trigger that allows you to specify actions for each of four timing points in the single trigger
body.
The four different timing points are below.

BEFORE STATEMENT – level


BEFORE ROW – level
AFTER ROW – level
AFTER STATEMENT – level

SYNTAX:

CREATE [ OR REPLACE ] TRIGGER <trigger_name>


FOR
[INSERT | UPDATE | DELET.......]
ON <name of underlying object>
<Declarative part>
BEFORE STATEMENT IS
BEGIN
<Execution part>;
END BEFORE STATEMENT;

BEFORE EACH ROW IS


BEGIN
<Execution part>;
END EACH ROW;
AFTER EACH ROW IS
BEGIN
<Execution part>;
END AFTER EACH ROW;

AFTER STATEMENT IS
BEGIN
<Execution part>;
END AFTER STATEMENT;
END;

Exceptions:-

An exception is an error which disrupts the normal flow of program instructions. PL/SQL provides us the exception block
which raises the exception thus helping the programmer to find out the fault and resolve it.
There are two types of exceptions defined in PL/SQL

User defined exception.


System defined exceptions.

Syntax:-

WHEN exception THEN


statement;

DECLARE
declarations section;
BEGIN
executable command(s);
EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2 THEN
statement2;
[WHEN others THEN]
/* default exception handling code */
END;

Note:

When other keyword should be used only at the end of the exception handling block as no exception handling part
present later will get executed as the control will exit from the block after executing the WHEN OTHERS.

System defined exceptions:


These exceptions are predefined in PL/SQL which get raised WHEN certain database rule is violated.
System-defined exceptions are further divided into two categories:
Named system exceptions.
Unnamed system exceptions.
Named system exceptions: They have a predefined name by the system like ACCESS_INTO_NULL, DUP_VAL_ON_INDEX,
LOGIN_DENIED etc. the list is quite big.

NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement returns no rows.

TOO_MANY_ROWS:It is raised WHEN a SELECT INTO statement returns more than one row.

VALUE_ERROR:This error is raised WHEN a statement is executed that resulted in an arithmetic, numeric, string,
conversion, or constraint error. This error mainly results from programmer error or invalid data input.

ZERO_DIVIDE = raises exception WHEN dividing with zero.

Unnamed system exceptions:Oracle doesn’t provide name for some system exceptions called unnamed system
exceptions.These exceptions don’t occur frequently.These exceptions have two parts code and an associated message.
The way to handle to these exceptions is to assign name to them using Pragma EXCEPTION_INIT
Syntax:
PRAGMA EXCEPTION_INIT(exception_name, -error_number);
error_number are pre-defined and have negative integer range from -20000 to -20999.

User defined exceptions:


This type of users can create their own exceptions according to the need and to raise these exceptions
explicitly raise command is used.

You might also like