You are on page 1of 23

Table of Contents

Introduction to PL/SQL ........................................................................................................................4


Advantages of PL/SQL .................................................................................................................... 4
What is SQL? ........................................................................................................................................4
A Brief History of SQL ..................................................................................................................... 4
SQL Query Process .......................................................................................................................... 5
Types of SQL Commands ................................................................................................................ 5
Data Definition Language (DDL) ............................................................................................. 5
Data Manipulation Language (DML) ....................................................................................... 5
Data Control Language (DCL) .................................................................................................. 5
Transaction Control Language (TCL) ....................................................................................... 5
What is RDBMS? ..................................................................................................................................6
What is a Table? ............................................................................................................................. 6
What is a field? ............................................................................................................................... 6
What is a Record or a Row? ............................................................................................................ 6
What is a column? .......................................................................................................................... 6
What is a NULL value? .................................................................................................................... 7
SQL Constraints....................................................................................................................................7
NOT NULL Constraint ...................................................................................................................... 7
DEFAULT Constraint........................................................................................................................ 7
UNIQUE Constraint ......................................................................................................................... 7
PRIMARY Key .................................................................................................................................. 7
FOREIGN Key .................................................................................................................................. 8
CHECK Constraint............................................................................................................................ 8
INDEX.............................................................................................................................................. 8
Data Integrity.......................................................................................................................................8
Entity Integrity ................................................................................................................................ 8
Domain Integrity............................................................................................................................. 8
Referential integrity ....................................................................................................................... 8
User-Defined Integrity .................................................................................................................... 8
Database Normalization ......................................................................................................................8
Problem Without Normalization .................................................................................................... 9
Update Anomaly..................................................................................................................... 9
Insertion Anomaly .................................................................................................................. 9
Deletion Anomaly ................................................................................................................... 9
Database First Normal Form (1NF) ............................................................................................... 9
First Rule of 1NF ..................................................................................................................... 9
Second Rule of 1NF ............................................................................................................... 10
Third Rule of 1NF .................................................................................................................. 11
Database Second Normal Form (2NF) ........................................................................................ 11
Database Third Normal Form (3NF) ........................................................................................... 12
Oracle SQL Developer ........................................................................................................................13
Creating a Database Connection................................................................................................... 13
SQL SYNTAX .......................................................................................................................................16
CREATE DATABASE Statement ...................................................................................................... 16
DROP DATABASE Statement......................................................................................................... 16
CREATE TABLE Statement ............................................................................................................. 16
TRUNCATE Statement ................................................................................................................... 16
CREATE INDEX Statement ............................................................................................................. 16
DROP INDEX Statement ................................................................................................................ 17
DROP TABLE Statement ................................................................................................................ 17
ALTER TABLE Statement ............................................................................................................... 17
INSERT INTO Statement ................................................................................................................ 17
UPDATE Statement ....................................................................................................................... 18
DELETE Statement ........................................................................................................................ 18
SELECT Statement ......................................................................................................................... 18
CREATE TABLE AS Statement ........................................................................................................ 18
INSERT INTO SELECT Statement .................................................................................................... 19
DISTINCT Clause ............................................................................................................................ 19
WHERE Clause............................................................................................................................... 19
ROWNUM Clause .......................................................................................................................... 19
ORDER BY Clause .......................................................................................................................... 19
GROUP BY Clause.......................................................................................................................... 19
HAVING Clause ............................................................................................................................. 19
AS (ALIASES) Clause ...................................................................................................................... 19
JOIN Clause ................................................................................................................................... 20
SQL View ............................................................................................................................................20
Creating View ............................................................................................................................... 20
Updating View .............................................................................................................................. 20
Deleting View ............................................................................................................................... 21
SQL Functions ....................................................................................................................................21
COUNT / SUM / AVG Functions .................................................................................................... 21
MIN / MAX Functions ................................................................................................................... 21
NVL Function ................................................................................................................................ 21
ROUND Function........................................................................................................................... 21
SQL Operators....................................................................................................................................21
Arithmetic Operators.................................................................................................................... 21
Comparison Operator ................................................................................................................... 22
Compound Operators ................................................................................................................... 22
Logical Operators IN Operator ...................................................................................................... 22
BETWEEN Operator .............................................................................................................. 22
LIKE Operator ....................................................................................................................... 22
EXISTS Operator............................................................................................................................ 23
ANY Operator ....................................................................................................................... 23
ALL Operator ........................................................................................................................ 23
AND/OR Clause ............................................................................................................................. 23
Introduction to PL/SQL
The PL/SQL programming language was developed by Oracle in the late 1980s as procedural language
extension for SQL and the Oracle relational database which is also available in other relational database
such as IBM DB2 and TimeTen in-memory database. PL/SQL is based on from ADA and Pascal
programming language
Advantages of PL/SQL
Better Performance - PL/SQL is a completely portable, high-performance transaction processing
language
Full Portability - PL/SQL provides a built-in, interpreted and OS independent programming
environment
Higher Productivity - PL/SQL can also directly be called from the command-line SQL*Plus interface
and external programming language calls to database. PL/SQL extends tools such as Oracle Forms
and Oracle Reports.
Tight Integration with SQL - PL/SQL is tightly integrated with SQL. You do not have to translate
between SQL and PL/SQL datatypes: a NUMBER or VARCHAR2 column in the database is stored in
a NUMBER or VARCHAR2 variable in PL/SQL.
Support for Object-Oriented Programming - PL/SQL supports Object types which are ideal object-
oriented modeling tool and can use to reduce the cost and time required to build complex
applications.
Tight Security - PL/SQL stored procedures move application code from the client to the server,
where you can protect it from tampering, hide the internal details, and restrict who has access.
But before anything else you need to understand first the Structured Query Language (SQL) before
going to PL/SQL.

What is SQL?
SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in a relational database. SQL is the standard language for Relational Database
System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle,
Sybase, Informix, Postgres and SQL Server use SQL as their standard database language.

A Brief History of SQL


1970 Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational databases. He
publishes the Definition of Relational Model.
1975 Structured Query Language appeared. Initial version of SQL Implemented (D.
Chamberlin).
1978 IBM worked to develop Codd's ideas and released an experimental version named
System/R.
Early 1980s IBM developed the first prototype of relational database and standardized by
ANSI. The first relational database was released by Relational Software which later came to be
known as Oracle. IBM releases a commercial version, SQL/DS and DB2. The first relational
database was released by Relational Software which later came to be known as Oracle.
1886/87 - IBM SQL becomes standard ANSI and ISO. Commonly called SQL-86.
SQL Query Process
SQL Query Execution
When you are executing an SQL
command for any Relational
Database Management System, the
system determines the best way to
carry out your request and SQL
engine figures out how to interpret
the task.
Types of SQL Commands
1. Data Definition Language (DDL)
SQL Commands that define and alter the different structures in a Database.

COMMAND DESCRIPTION
CREATE Creates a new table, a view of a table, or another object in the
database.
ALTER Modifies an existing database object, such as a table
Deletes an entire table, a view of a table or other objects in the
DROP
database.
2. Data Manipulation Language (DML)
SQL Commands that are used to retrieve, store, modify, delete, and update records in database.

COMMAND DESCRIPTION
SELECT Retrieves certain records from one or more tables.
INSERT Creates or insert a new record.
UPDATE Modifies records.
DELETE Deletes records.
3. Data Control Language (DCL)
SQL Commands that control the level of access that users have on database objects.

COMMAND DESCRIPTION
GRANT allows users to read/write on certain database objects
REVOKE keeps users from read/write permission on database objects
4. Transaction Control Language (TCL)
SQL Commands that control and manage transactions to maintain the integrity of data within
SQL statements.

COMMAND DESCRIPTION
BEGIN Transaction opens a transaction
COMMIT Transaction commits a transaction
ROLLBACK Transaction ROLLBACK a transaction in case of any error
What is RDBMS?
A Relational database management system (RDBMS) is a database management system (DBMS) that is
based on the relational model as introduced by E. F. Codd, such as MS SQL Server, IBM DB2, Oracle,
MySQL, Microsoft Access, and PostgreSQL
What is a Table?
The data in an RDBMS is stored in database objects which are called as tables. This table is basically a
collection of related data entries and it consists of numerous columns and rows.
Below is an example of EMPLOYEE table:

+------+-------------+--------+-------------------+---------------+
| ID | LNAME | AGE | CITY | SALARY |
+------+-------------+--------+-------------------+---------------+
| 1 | Go | 23 | Danao City | 2500.00 |
| 2 | Arante | 52 | Cebu City | 3500.00 |
| 3 | Caraan | 32 | Davao City | 4800.00 |
| 4 | Lasala | 28 | Manila | 8500.00 |
| 5 | Capoy | 26 | Butuan City | 6400.00 |
| 6 | Tui | 21 | Dumaguete | 4300.00 |
+-----+-------------+--------+--------------------+--------------+
What is a field?
Every table is broken up into smaller entities called fields. The fields in the EMPLOYEE table consist of
ID, LNAME, AGE, ADDRESS and SALARY. A field is a column in a table that is designed to maintain
specific information about every record in the table.
What is a Record or a Row?
A record is also called as a row of data is each individual entry that exists in a table. For example, there
are 7 records in the above CUSTOMERS table. Following is a single row of data or record in the
EMPLOYEE table:

| 2 | Arante | 52 | Cebu City |

What is a column?
A column is a vertical entity in a table that contains all information associated with a specific field in a
table. For example, a column in the EMPLOYEE table is SALARY, which represents the employees salary
and would be as shown below:
+---------------+
| SALARY |
+---------------+
| 2500.00 |
| 3500.00 |
| 4800.00 |
| 8500.00 |
| 6400.00 |
+---------------+
What is a NULL value?
A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL
value is a field with no value. It is very important to understand that a NULL value is different than a
zero value or a field that contains spaces. A field with a NULL value is the one that has been left blank
during a record creation.

SQL Constraints
Constraints are the rules enforced on data columns on a table. These are used to limit the type of data
that can go into a table. This ensures the accuracy and reliability of the data in the database.
Constraints can either be column level or table level. Column level constraints are applied only to one
column whereas, table level constraints are applied to the entire table.
Following are some of the most commonly used constraints available in SQL:
NOT NULL Constraint: Ensures that a column cannot have a NULL value.

CREATE TABLE STUDENT (


ID INT NOT NULL,
Name VARCHAR (255) NOT NULL,
Age INT
);
DEFAULT Constraint: Provides a default value for a column when none is specified.

CREATE TABLE UserLogin (


ID INT NOT NULL,
username VARCHAR (25) NOT NULL,
password VARCHAR (255) NOT NULL,
type VARCHAR (5) DEFAULT User,
);

UNIQUE Constraint: Ensures that all the values in a column are different.

CREATE TABLE STUDENT (


ID INT NOT NULL UNIQUE,
Name VARCHAR (255) NOT NULL,
email VARCHAR (100) NOT NULL
);

PRIMARY Key: Uniquely identifies each row/record in a database table.

CREATE TABLE STUDENT (


ID INT NOT NULL PRIMARY KEY,
Name VARCHAR (255) NOT NULL,
Email VARCHAR (255) NOT NULL
);
FOREIGN Key: Uniquely identifies a row/record in any another database table.

CREATE TABLE Orders (


OrderID INT NOT NULL PRIMARY KEY,
OrderNumber INT NOT NULL,
CustomerID INT FOREIGN KEY REFERENCES Customers(CustomerID)
);

CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.

CREATE TABLE Persons (


ID INT NOT NULL,
LastName VARCHAR (255) NOT NULL,
FirstName VARCHAR (255),
Age INT CHECK (Age>=18)
);

INDEX: Used to create and retrieve data from the database very quickly.

CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);

Creates a unique index on a table. Duplicate values are not allowed:

CREATE INDEX index_name ON table_name (column1, column2, ...);

Data Integrity
The following categories of data integrity exist with each RDBMS:
Entity Integrity: There are no duplicate rows in a table.
Domain Integrity: Enforces valid entries for a given column by restricting the type, the format, or
the range of values.
Referential integrity: Rows cannot be deleted, which are used by other records.
User-Defined Integrity: Enforces some specific business rules that do not fall into entity, domain or
referential integrity.

Database Normalization
Database normalization is the process of efficiently organizing data in a database. There are two reasons
of this normalization process:
Eliminating redundant data. For example, storing the same data in more than one table.
Ensuring data dependencies make sense.
It is your choice to take it further and go to the fourth normal form, fifth normal form and so on, but in
general, the third normal form is more than enough.
Problem Without Normalization
Without Normalization, it becomes difficult to handle and update the database, without facing data
loss. Insertion, Updates and Deletion Anomalies are very frequent if Database is not Normalized. To
understand these anomalies let us take an example of Student table.
ID STUDNAME ADDRESS SUBJECTS
1 Adrian Cebu Biology, Physics
2 Dexter Iloilo Mathematics
3 Stanley Davao Mathematics
Update Anomaly: To update address of a student who occurs twice or more than twice in a table, we
should update Address column in all the rows, else data will become inconsistent.
Insertion Anomaly: Suppose for a new admission, we have a Student ID (ID), name (STUDNAME) and
address(ADDRESS) of a student but if student has not opted for any subjects yet then we must insert
NULL there, leading to Insertion Anomaly.
Deletion Anomaly: If Id 1 has only one subject and temporarily he drops it, when we delete that row,
entire student record will be deleted along with it.
Database First Normal Form (1NF)
The First normal form (1NF) sets basic rules for an organized database:
Define the data items required, because they become the columns in a table.
Place the related data items in a table.
Ensure that there are no repeating groups of data.
Ensure that there is a primary key.
First Rule of 1NF
You must define the data items. This means looking at the data to be stored, organizing the data into
columns, defining what type of data each column contains and then finally putting the related columns
into their own table.
For example, you put all the columns relating to locations of meetings in the Location table, those
relating to student in the Student table and so on. Defining Student Table shown below:

CREATE TABLE STUDENT (


ID INT NOT NULL,
STUDNAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL
ADDRESS VARCHAR (25),
SUBJECT VARCHAR (50)
);
Second Rule of 1NF
The next step is ensuring that there are no repeating groups of data. So, if we populate this table for a
single student having multiple subjects, then it would be something as shown below:

STUDENT TABLE
ID STUDNAME AGE ADDRESS SUBJECTS
1 Adrian 21 Cebu Biology
2 Dexter 20 Iloilo Mathematics
3 Stanley 19 Davao Mathematics
4 Adrian 21 Cebu Physics

But as per the 1NF, we need to ensure that there are no repeating groups of data. So, let us break the
above table into two parts and then join them using a key as shown in the following program:
Customer Table
CREATE TABLE STUDENT (
ID INT NOT NULL PRIMARY KEY,
STUDNAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL
ADDRESS VARCHAR (25)
);

This table would have the following record:

STUDENT TABLE
ID STUDNAME AGE ADDRESS
1 Adrian 21 Cebu
2 Dexter 20 Iloilo
3 Stanley 19 Davao
Subject Table

CREATE TABLE SUBJECT (


ID INT NOT NULL PRIMARY KEY,
CODE VARCHAR (10) NOT NULL,
DESCRIPTION VARCHAR (20) NOT NULL
);

This table would have the following record:


SUBJECT TABLE
ID CODE DESCRIPTION
1 MATH1 Mathematics 1
2 MATH2 Algebra
3 PHYS1 Physics
Third Rule of 1NF
The final rule of the first normal form, create a primary key for each table which we have already
created.
Database Second Normal Form (2NF)
The Second Normal Form states that it should meet all the rules for 1NF and there must be no partial
dependences of any of the columns on the primary key:
Consider a student-subject relation and you want to store student ID, student name, subject ID, and
school year detail and address:

CREATE TABLE STUDENT (


STUDID INT NOT NULL PRIMARY KEY,
STUDNAME VARCHAR (20) NOT NULL,
SUBJECTID INT NOT NULL,
SCHOOLYEAR VARCHAR (15) NOT NULL,
ADDRESS VARCHAR (25)
);

This table is in the first normal form; in that it obeys all the rules of the first normal form. In this table,
the primary key consists of the STUDID and the SUBJECTID. Combined, they are unique assuming the
same customer would hardly order the same thing.
However, the table is not in the second normal form because there is partial dependencies of primary
keys and columns. STUDNAME is dependent on STUDID and there's no real link between a customer's
name and what he purchased. The SCHOOLYEAR is also dependent on the SUBJECTID, but they are not
dependent on the STUDID, because there is no link between a STUDID and an SCHOOLYEAR.
To make this table comply with the second normal form, you need to separate the columns into three
tables.
First, create a table to store the student details as shown in the code block below:

CREATE TABLE STUDENT (


STUDID INT NOT NULL PRIMARY KEY,
STUDNAME VARCHAR (20) NOT NULL,
ADDRESS VARCHAR (25)
);

The next step is to create a table to store the details of each subject:

CREATE TABLE SUBJECT (


SUBJECTID INT NOT NULL PRIMARY KEY,
SUBJECTCODE VARCHAR (10) NOT NULL,
DESCRIPTION VARCHAR (20) NOT NULL
);
Finally, create a third table storing just the STUDID and the SUBJECTID to keep a track
of all the subjects taken by the student:

CREATE TABLE ENROLLEDSUBJECTS (


STUDID INT NOT NULL PRIMARY KEY,
SUBJECTID INT NOT NULL,
SCHOOLYEAR VARCHAR (15)
);

Database Third Normal Form (3NF)


A table is in a third normal form when the following conditions are met:
It is in the second normal form.
All non-primary fields are dependent on the primary key.
The dependency of these non-primary fields is between the data. For example, in the following table
the street name, city and the state are unbreakably bound to their zip code.

CREATE TABLE STUDENT (


STUDID INT NOT NULL PRIMARY KEY,
STUDNAME VARCHAR (20) NOT NULL,
DOB DATE,
STREET VARCHAR (200),
CITY VARCHAR (100),
PROVINCE VARCHAR (100),
ZIP VARCHAR (12),
EMAIL_ID VARCHAR (256),
);

The dependency between the ZIPCODE and the ADDRESS is called as a transitive dependency. To
comply with the third normal form, all you need to do is to move the STREET, CITY and the STATE fields
into their own table, which you can call as the ADDRESS table.

CREATE TABLE ADDRESS (


ZIP VARCHAR (12) PRIMARY KEY,
STREET VARCHAR (200),
CITY VARCHAR (100),
PROVINCE VARCHAR (100),
EMAIL_ID VARCHAR (256),
);
The next step is to alter the STUDENTS table as shown below.

CREATE TABLE STUDENT (


STUDID INT NOT NULL PRIMARY KEY,
STUDNAME VARCHAR (20) NOT NULL,
DOB DATE,
ZIP VARCHAR (12),
EMAIL_ID VARCHAR (256),
);

The advantages of removing transitive dependencies are mainly two-fold. First, the amount of data
duplication is reduced and therefore your database becomes smaller. The second advantage is data
integrity. When duplicated data changes, there is a big risk of updating only some of the data, especially
if it is spread out in many different places in the database.
For example, if the address and the zip code data were stored in three or four different tables, then any
changes in the zip codes would need to ripple out to every record in those three or four tables.

Oracle SQL Developer


Oracle SQL Developer is a free graphical tool that enhances productivity and simplifies database
development tasks. Using SQL Developer, users can browse database objects, run SQL statements, edit
and debug PL/SQL statements and run reports, whether provided or created.
Developed in Java, SQL Developer runs on Windows, Linux and the Mac OS X. This is a great advantage
to the increasing numbers of developers using alternative platforms. Multiple platform support also
means that users can install SQL Developer on the Database Server and connect remotely from their
desktops, thus avoiding client server network traffic. Default connectivity to the database is through the
JDBC Thin driver, so no Oracle Home is required.
Creating a Database Connection
The first step to managing database objects using Oracle SQL Developer is to create a database
connection. Perform the following steps:
1. Open Oracle SQL Developer.
2. In the Connections navigator, right-click Connections and select New Connection.
3. Enter HR_ORCL for the Connection Name (or any other name that identifies your connection), hr
for the Username and Password, specify your localhost for the Hostname and enter ORCL for the
SID. Click Test.

4. The status of the connection was tested successfully. The connection was not saved however.
Click Save to save the connection, and then click Connect.

5. The connection was saved and you see the database in the list.
6. Expand HR_ORCL.

Note: When a connection is opened, a SQL Worksheet is opened automatically. The SQL
Worksheet allows you to execute SQL against the connection you just created.
7. Expand Tables.

8. Select the Table EMPLOYEES to view the table definition. Then click the Data tab.
SQL SYNTAX
CREATE DATABASE Statement
This is used to create a new SQL database.

CREATE DATABASE database_name;

DROP DATABASE Statement


This is used to drop an existing SQL database.

DROP DATABASE database_name;

CREATE TABLE Statement


This is used to create a new table in a database.

CREATE TABLE table_name (


column1 datatype PRIMARY KEY,
column2 datatype,
.....
columnN datatype,
);

Example:

CREATE TABLE STUDENT (


STUDID INT NOT NULL PRIMARY KEY,
STUDNAME VARCHAR (20) NOT NULL,
DOB DATE,
ZIP VARCHAR (12),
EMAIL_ID VARCHAR (256)
);

TRUNCATE Statement
This is used to delete the data inside a table, but not the table itself.

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE STUDENT;

CREATE INDEX Statement


This is used to create indexes in tables. Indexes are used to retrieve data from the database very fast.
The users cannot see the indexes; they are just used to speed up searches/queries.

CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ..., columnN);

Example:

CREATE UNIQUE INDEX ZipIndex ON STUDENT (STUDNAME, DOB, ZIP);


DROP INDEX Statement
DROP INDEX index_name;
This is used to delete an index in a table.

DROP INDEX ZipIndex;

Example:
DROP TABLE Statement
This is used to drop an existing table in a database.

DROP TABLE table_name;

Example:

DROP TABLE STUDENT;

ALTER TABLE Statement


This is used to add, delete, or modify columns in an existing table.

ALTER TABLE table_name {ADD|DROP COLUMN|MODIFY} column_name {data_type};

Example:

ALTER TABLE Student ADD Status INT DEFAULT 0 NOT NULL;


ALTER TABLE Student ADD Year INT DEFAULT 1 NOT NULL;

ALTER TABLE Student MODIFY Year VARCHAR (6) DEFAULT 'FIRST' NOT NULL;

ALTER TABLE Student DROP COLUMN Year;

INSERT INTO Statement


This is used to insert new records in a table.

INSERT INTO table_name(column1, column2....columnN) VALUES ( value1, value2....valueN);

Example:

INSERT INTO STUDENT (STUDID, STUDNAME, DOB)


VALUES (201500231, 'John Doe', TO_DATE ('1986/05/31', 'YYYY/MM/DD'));
INSERT INTO STUDENT (STUDID, STUDNAME, DOB)
VALUES (201500232, 'Jason Lava', TO_DATE ('1980/03/21', 'YYYY/MM/DD'));
INSERT INTO STUDENT (STUDID, STUDNAME, DOB)
VALUES (201500233, 'Kate Lane', TO_DATE ('1990/02/01', 'YYYY/MM/DD'));
INSERT ALL
INTO STUDENT (STUDID, STUDNAME, DOB)
VALUES (201500234, 'Randy Moore', TO_DATE ('1985/03/22', 'YYYY/MM/DD'))
INTO STUDENT (STUDID, STUDNAME, DOB)
VALUES (201500235, 'Diana Morgan', TO_DATE ('1981/12/15', 'YYYY/MM/DD'))
INTO STUDENT (STUDID, STUDNAME, DOB)
VALUES (201500236, 'Lisa Ohare', TO_DATE ('1995/06/12', 'YYYY/MM/DD'))
SELECT * FROM dual;

UPDATE Statement
This is used to modify the existing records in a table.

UPDATE table_name SET column1 = value1, ..., columnN=valueN [WHERE {CONDITION}];


UPDATE table_name SET column1 = value1, ..., columnN=valueN;

Example:

UPDATE STUDENT SET DOB = TO_DATE ('1985/03/25', 'YYYY/MM/DD') WHERE STUDID=200500234;


UPDATE STUDENT SET DOB = TO_DATE ('1985/03/25', 'YYYY/MM/DD');

DELETE Statement
This is used to delete existing records in a table.

DELETE FROM table_name [WHERE {CONDITION}];


Example:

DELETE FROM STUDENT; -- DELETE ALL RECORDS


DELETE FROM STUDENT WHERE DOB >= TO_DATE ('06', 'MM');

SELECT Statement
This is used to retrieve the all records of the columns specified from a table. It can also have WHERE
clause to filter the records to retrieve.

SELECT column1, column2....columnN FROM table_name [WHERE {CONDITION}];

This is also used to retrieve the all records of the all columns from a table.

SELECT * FROM table_name [WHERE {CONDITION}];

CREATE TABLE AS Statement


This copies data from one table (all columns) into a new table.
CREATE TABLE new_table AS SELECT * FROM old_table;

This also copies data some columns of a table into a new table.

CREATE TABLE new_table AS SELECT column_name(s) FROM old_table;

It can also be used to create a new, empty table using the schema of another. Just add a WHERE clause
that causes the query to return no data:

CREATE TABLE new_table AS SELECT column_name(s) FROM old_table WHERE 1 = 0;


INSERT INTO SELECT Statement
This copies data from one table and inserts it into another table.
INSERT INTO SELECT requires that data types in source and target tables match
The existing records in the target table are unaffected
It copies all columns from one table to another table.

INSERT INTO table_name2 SELECT * FROM table_name1 WHERE CONDITION;


It copies only some columns from one table to another table.

INSERT INTO table2 (column1, column2, ..., columnN)


SELECT column1, column2, ..., columnN FROM table1 WHERE CONDITION;
DISTINCT Clause
This is used to return only distinct (unique) values.

SELECT DISTINCT column1, column2....columnN FROM table_name;

WHERE Clause
This is used to extract only those records that fulfill a specified condition.

SELECT column1, column2....columnN FROM table_name [WHERE {CONDITION}];

ROWNUM Clause
This is used to specify the number of records to return.

SELECT column1,, columnN FROM table_name WHERE CONDITION AND ROWNUM <= 3;
ORDER BY Clause
This is used to sort the result-set in ascending or descending order.

SELECT column1, column2....columnN FROM table_name [WHERE CONDITION


ORDER BY column_name {ASC|DESC}];
GROUP BY Clause
This is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by
one or more columns.

SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name;

HAVING Clause
This was added to SQL because the WHERE keyword could not be used with aggregate functions.

SELECT SUM(column_name) FROM table_name WHERE CONDITION


GROUP BY column_name HAVING (ARITHMETIC_CONDITION);
AS (ALIASES) Clause
Aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to
make column names more readable. An alias only exists for the duration of the query.

SELECT column_name AS alias_name, column_nameN AS alias_nameN FROM table_name;


SELECT column_name(s) FROM table_name AS alias_name;
JOIN Clause
This is used to combine rows from two or more tables, based on a related column between them.
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right
table.
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the
left table.
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

SELECT column_name(s) FROM table_name1 INNER JOIN table_name2


ON table_name1.column_name1= table_name2.column_name1;
SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2
ON table_name1.column_name = table_name2.column_name;
SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2
ON table_name1.column_name = table_name2.column_name;
SELECT column_name(s) FROM table_name1 FULL OUTER JOIN table_name2
ON table_name1.column_name = table_name2.column_name;

SQL View
A view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns,
just like a real table. The fields in a view are fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data
were coming from one single table.
Creating View
Note: A view always shows up-to-date data! The database engine recreates the data, using the view's

CREATE VIEW view_name AS


SELECT column1, column2, ..., columnN FROM table_name WHERE condition;

SQL statement, every time a user queries a view.


Now, we can use our view_name in our query:

SELECT * FROM [view_name] WHERE CONDITION;

Updating View
You can update a view by using the following syntax:

CREATE OR REPLACE VIEW view_name AS


SELECT column1, column2, ..., columnN FROM table_name WHERE condition;
Deleting View

DROP VIEW view_name;


You can delete a view by using the following syntax:

SQL Functions
COUNT / SUM / AVG Functions
The COUNT function returns the number of rows that matches a specified criterion.
The AVG function returns the average value of a numeric column.

SELECT COUNT(column_name) FROM table_name WHERE CONDITION;


SELECT AVG(column_name) FROM table_name WHERE CONDITION;
SELECT SUM(column_name) FROM table_name WHERE CONDITION;

The SUM function returns the total sum of a numeric column.


MIN / MAX Functions
Min/Max functions return the smallest/largest value of the selected column.

SELECT MIN(column_name) FROM table_name WHERE CONDITION;


SELECT MAX(column_name) FROM table_name WHERE CONDITION;

NVL Function
This function is used to replace NULL value with another value. The function accepts 2 expressions
(parameters), and returns the first expression if it is not NULL, otherwise NVL returns the second
expression.

SELECT column_name1, column_name2 * (column_name3 + NVL (column_name4, 0)) FROM


table_name;

ROUND Function
ROUND function returns a number rounded to a certain number of decimal places.

SELECT ROUND(column_name [, decimal_places] ) FROM table_name WHERE CONDITION;

SQL Operators
Arithmetic Operators
Operator Description
+ Addition Operator
- Subtraction Operator
* Multiplication Operator
/ Division Operator
% Modulo / Remainder Operator
Comparison Operator
Operator Description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to

Compound Operators
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
&= Bitwise AND equals
^-= Bitwise exclusive equals
|*= Bitwise OR equals

Logical Operators
IN Operator

SELECT column1, column2....columnN FROM table_name WHERE column_name IN (val-1, ..., val-N);
SELECT column_name(s) FROM table_name WHERE column_name IN (SELECT STATEMENT);
This allows you to specify multiple values in a WHERE clause.
BETWEEN Operator

SELECT column1, column2....columnN FROM table_name WHERE column_name BETWEEN val-1


AND val-2;
This selects values within a given range. The values can be numbers, text, or dates.
LIKE Operator
This is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
% - The percent sign represents zero, one, or multiple characters
_ - The underscore represents a single character
SELECT column1, column2....columnN FROM table_name WHERE column_name LIKE { PATTERN };
EXISTS Operator
This is used to test for the existence of any record in a subquery. It returns true if the subquery returns
one or more records.
SELECT column_name(s) FROM table_name
WHERE EXISTS (SELECT column_name FROM table_name WHERE condition);

ANY Operator
It returns true if any of the subquery values meet the condition.

SELECT column_name(s) FROM table_name WHERE column_name operator


ANY (SELECT column_name FROM table_name WHERE condition);

ALL Operator
It returns true if any of the subquery values meet the condition.

SELECT column_name(s) FROM table_name WHERE column_name operator


ALL (SELECT column_name FROM table_name WHERE condition);

AND/OR Clause
These are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND is TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.

SELECT column1, column2....columnN FROM table_name WHERE CONDITION1 {AND|OR}


CONDITION2;
SELECT column1, column2, , columnN FROM table_name WHERE NOT condition;

You might also like