SQL - PLSQL Document
SQL - PLSQL Document
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: -
Query: -
ALTER TABLE supplier_details
RENAME TO Suppliers;
Output: -
Query: -
ALTER TABLE Suppliers
ADD (Inactive_Active varchar2(20));
Output: -
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:
Query: -
INSERT
INTO suppliers (suplier_id,
supplier_name,
city,
state_name,
total_spent
)
values ( 800,'Instant_Assemblers','Reedwood_City','California',90500.00 );
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: -
Output: -
Query: -
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:-
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: -
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
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:
EXAMPLE :-
Query:
Output:
SPECIFY COLUMNS:
SELECT
suplier_id,
supplier_name,
status_cid,
total_spent
FROM
suppliers NATURAL JOIN suppiler_join;
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:-
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:-
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.
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:-
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:
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:-
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 (<, > , <= , >= , !< , !> , <> / !=).
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:
NOT NULL constraints prevent the insertion of NULL values into a column. NOT NULL constraints can only be created at
the column-level.
Query:
Output:
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:
A PRIMARY KEY constraint is the combination of a NOT NULL and a UNIQUE constraint.
Query:
Query:
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:
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: -
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.
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.
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:
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;
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:
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:
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
Query:
SELECT
suplier_id,
supplier_name,
total_spent
FROM
suppliers
where
total_spent=78150 and supplier_name='Time_manifacturers' ;
Output:
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: -
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:
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:
Types of Subqueries:
1- Single-row subqueries
2- Multi-row subqueries
Single-row subquery:
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.
1- A rollback occurs
2- The system crashes
3- A sequence is used in another table
Simple 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:
To drop view:
DROP VIEW view;
Advantages of Views:
SYNTAX:
Query:
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.
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:-
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.
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:
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:
Aggregate functions
Aggregate functions in SQL are used for performing calculations on an entire column(which could have thousands of
rows).
SYNTAX:
USING TABLE:
SUPPLIERS table
COUNT
Query:
Output:
SUM
Query:
Output:
AVG
Query:
Output:
MIN
Query:
SELECT MIN(total_spent) FROM suppliers;
Output:
MAX
Query:
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:
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)
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:
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.
SYNTAX:
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
Syntax:-
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.
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.
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.