Oracle/Plsql: Select Statement: Description

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

ORACLE/PLSQL: SELECT STATEMENT

Learn how to use the Oracle SELECT statement with syntax, examples, and practice exercises.
DESCRIPTION
The Oracle SELECT statement is used to retrieve records from one or more tables in an Oracle database.
SYNTAX
The syntax for the Oracle SELECT statement is:
SELECT expressions
FROM tables
WHERE conditions;
PARAMETERS OR ARGUMENTS
expressions are the columns or calculations that you wish to retrieve.
tables are the tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
conditions are conditions that must be met for the records to be selected.
EXAMPLE - SELECT ALL FIELDS FROM ONE TABLE
Let's look at how to use an Oracle SELECT query to select all fields from a table.
SELECT *
FROM homes
WHERE bathrooms >= 2
ORDER BY home_type ASC;
In this Oracle SELECT statement example, we've used * to signify that we wish to select all fields from the homes table
where the number of bathrooms is greater than or equal to 2. The result set is sorted by home_type in ascending order.
EXAMPLE - SELECT INDIVIDUAL FIELDS FROM ONE TABLE
You can also use the Oracle SELECT statement to select individual fields from the table, as opposed to all fields from the
table.
For example:
SELECT home_id, home_type, bathrooms
FROM homes
WHERE home_id < 500
AND home_type = 'two-storey'
ORDER BY home_type ASC, bathrooms DESC;
This Oracle SELECT example would return only the home_id, home_type, and bathrooms fields from the homes table
where the home_id is less than 500 and the home_type is 'two-storey'. The results are sorted by home_type in ascending
order and then bathrooms in descending order.
EXAMPLE - SELECT FIELDS FROM MULTIPLE TABLES
You can also use the Oracle SELECT statement to retrieve fields from multiple tables by using a join.
SELECT homes.home_id, customers.customer_name
FROM customers
INNER JOIN homes
ON customers.customer_id = homes.customer_id
ORDER BY home_id;
This Oracle SELECT example joins two tables together to gives us a result set that displays
the home_id and customer_name fields where the customer_id value matches in both the customers and homes table.
The results are sorted by home_id in ascending order.
PRACTICE EXERCISE #1:
Based on the contacts table below, select all fields from the contacts table whose last_name is 'Smith', contact_id is
greater than or equal 1000 and contact_id is less than or equal to 2000 (no sorting is required):
CREATE TABLE contacts
( contact_id number(10) not null,
last_name varchar2(50) not null,
first_name varchar2(50) not null,
address varchar2(50),
city varchar2(50),
state varchar2(2),
zip_code varchar2(10),
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
SOLUTION FOR PRACTICE EXERCISE #1:
The following Oracle SELECT statement would select these records from the employees table:
SELECT *
FROM contacts
WHERE last_name = 'Smith'
AND contact_id >= 1000
AND contact_id <= 2000;
Or you could write the solution using the BETWEEN clause as follows:
SELECT *
FROM contacts
WHERE last_name = 'Smith'
AND contact_id BETWEEN 1000 AND 2000;

ORACLE/PLSQL: INSERT STATEMENT
Learn how to use the Oracle INSERT statement with syntax and examples. We've also added some practice exercises
that you can try for yourself.
DESCRIPTION
The Oracle INSERT statement is used to insert a single record or multiple records into a table in Oracle.
SYNTAX
The syntax for the Oracle INSERT statement when inserting a single record using the VALUES keyword is:
INSERT INTO table
(column1, column2, ... )
VALUES
(expression1, expression2, ... );
Or the syntax for the Oracle INSERT statement when inserting multiple records using a SELECT statement is:
INSERT INTO table
(column1, column2, ... )
SELECT expression1, expression2, ...
FROM source_table
WHERE conditions;
PARAMETERS OR ARGUMENTS
table is the table to insert the records into.
column1, column2 are the columns in the table to insert values.
expression1, expression2 are the values to assign to the columns in the table. So column1 would be assigned the value
of expression1, column2 would be assigned the value of expression2, and so on.
source_table is the source table when inserting data from another table.
conditions are conditions that must be met for the records to be inserted.
NOTE
When inserting records into a table using the Oracle INSERT statement, you must provide a value for every NOT
NULL column.
You can omit a column from the Oracle INSERT statement if the column allows NULL values.
EXAMPLE - USING VALUES KEYWORD
The simplest way to create an Oracle INSERT query to list the values using the VALUES keyword.
For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
VALUES
(5000, 'Apple');
This Oracle INSERT statement would result in one record being inserted into the suppliers table. This new record would
have a supplier_id of 5000 and a supplier_name of 'Apple'.
EXAMPLE - USING SELECT STATEMENT
You can also create more complicated Oracle INSERT statements using SELECT statements.
For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE customer_id > 5000;
By placing a SELECT statement within the INSERT statement, you can perform multiples inserts quickly.
With this type of insert, you may wish to check for the number of rows being inserted. You can determine the number of
rows that will be inserted by running the following Oracle SELECT statement before performing the insert.
SELECT count(*)
FROM customers
WHERE customer_id > 5000;
FREQUENTLY ASKED QUESTIONS
Question: I am setting up a database with clients. I know that you use the Oracle INSERT statement to insert
information in the database, but how do I make sure that I do not enter the same client information again?
Answer: You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following Oracle INSERT
statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE NOT EXISTS (SELECT *
FROM clients
WHERE clients.client_id = suppliers.supplier_id);
This Oracle INSERT statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following Oracle INSERT statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE NOT EXISTS (SELECT *
FROM clients
WHERE clients.client_id = 10345);
The use of the dual table allows you to enter your values in a select statement, even though the values are not currently
stored in a table.

Question: How can I insert multiple rows of explicit data in one INSERT command in Oracle?
Answer: The following is an example of how you might insert 3 rows into the suppliers table in Oracle, using an Oracle
INSERT statement:
INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM')
INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft')
INTO suppliers (supplier_id, supplier_name) VALUES (3000, 'Google')
SELECT * FROM dual;
PRACTICE EXERCISE #1:
Based on the contacts table, insert a contact record whose contact_id is 1000, last_name is Smith, first_name is Jane,
and address is 10 Somewhere St.:
CREATE TABLE contacts
( contact_id number(10) not null,
last_name varchar2(50) not null,
first_name varchar2(50) not null,
address varchar2(50),
city varchar2(50),
state varchar2(20),
zip_code varchar2(10),
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
SOLUTION FOR PRACTICE EXERCISE #1:
The following Oracle INSERT statement would insert this record into the employees table:
INSERT INTO contacts
(contact_id, last_name, first_name, address)
VALUES
(1000, 'Smith', 'Jane', '10 Somewhere St.');
PRACTICE EXERCISE #2:
Based on the contacts and customers table, insert into the contacts table all customers who reside in the state of 'Florida'.
CREATE TABLE contacts
( contact_id number(10) not null,
last_name varchar2(50) not null,
first_name varchar2(50) not null,
address varchar2(50),
city varchar2(50),
state varchar2(20),
zip_code varchar2(10),
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);

CREATE TABLE customers
( customer_id number(10) not null,
last_name varchar2(50) not null,
first_name varchar2(50) not null,
address varchar2(50),
city varchar2(50),
state varchar2(20),
zip_code varchar2(10),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);
SOLUTION FOR PRACTICE EXERCISE #2:
The following Oracle INSERT statement would insert this record into the suppliers table:
INSERT INTO contacts
(contact_id, last_name, first_name, address, city, state, zip_code)
SELECT customer_id, last_name, first_name, address, city, state, zip_code
FROM customers
WHERE state = 'Florida';
Since the number of fields in the contacts and customers table are the same and the fields are listed in the same order,
you could write the solution as follows (though it is generally better practice to list the column names in case the table
definitions change):
INSERT INTO contacts
SELECT *
FROM customers
WHERE state = 'Florida';

ORACLE/PLSQL: UPDATE STATEMENT
Learn how to use the Oracle UPDATE statement with syntax, examples, and practice exercises.
DESCRIPTION
The Oracle UPDATE statement is used to update existing records in a table in an Oracle database. There are 2 syntaxes
for an update query in Oracle depending on whether you are performing a traditional update or updating one table with
data from another table.
SYNTAX
The syntax for the Oracle UPDATE statement when updating one table is:
UPDATE table
SET column1 = expression1,
column2 = expression2,
...
WHERE conditions;
OR
The syntax for the Oracle UPDATE statement when updating one table with data from another table is:
UPDATE table1
SET column1 = (SELECT expression1
FROM table2
WHERE conditions)
WHERE conditions;
PARAMETERS OR ARGUMENTS
column1, column2 are the columns that you wish to update.
expression1, expression2 are the new values to assign to the column1, column2. So column1 would be assigned the
value of expression1, column2 would be assigned the value ofexpression2, and so on.
conditions are the conditions that must be met for the update to execute.
EXAMPLE - UPDATE SINGLE COLUMN
Let's look at a very simple Oracle UPDATE query example.
UPDATE customers
SET last_name = 'Anderson'
WHERE customer_id = 5000;
This Oracle UPDATE example would update the last_name to 'Anderson' in the customers table where the customer_id is
5000.
EXAMPLE - UPDATE MULTIPLE COLUMNS
Let's look at an Oracle UPDATE example where you might want to update more than one column with a single UPDATE
statement.
UPDATE customers
SET state = 'California',
customer_rep = 32
WHERE customer_id > 100;
When you wish to update multiple columns, you can do this by separating the column/value pairs with commas.
This Oracle UPDATE statement example would update the state to 'California' and the customer_rep to 32 where
the customer_id is greater than 100.
EXAMPLE - UPDATE TABLE WITH DATA FROM ANOTHER TABLE
Let's look at an Oracle UPDATE example that shows how to update a table with data from another table.
UPDATE customers
SET c_details = (SELECT contract_date
FROM suppliers
WHERE suppliers.supplier_name = customers.customer_name)
WHERE customer_id < 1000;
This UPDATE example would update only the customers table for all records where the customer_id is less than 1000.
When the supplier_name from the suppliers table matches the customer_name from the customerstable,
the contract_date from the suppliers table would be copied to the c_details field in the customers table.
EXAMPLE - USING EXISTS CLAUSE
You can also perform more complicated updates in Oracle.
You may wish to update records in one table based on values in another table. Since you can't list more than one table in
the Oracle UPDATE statement, you can use the Oracle EXISTS clause.
For example:
UPDATE suppliers
SET supplier_name = (SELECT customers.customer_name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS (SELECT customers.customer_name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);
In this Oracle UPDATE example, whenever a supplier_id matched a customer_id value, the supplier_name would be
overwritten to the customer_name from the customers table.
PRACTICE EXERCISE #1:
Based on the suppliers table populated with the following data, update the city to "San Francisco" for all records
whose supplier_name is "IBM".
CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
city varchar2(50),
CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)
);

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5001, 'Microsoft', 'Chicago');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5002, 'IBM', 'Chicago');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5003, 'Red Hat', 'Detroit');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5004, 'NVIDIA', 'New York');
SOLUTION FOR PRACTICE EXERCISE #1:
The following UPDATE statement would perform this update in Oracle.
UPDATE suppliers
SET city = 'San Francisco'
WHERE supplier_name = 'IBM';
The suppliers table would now look like this:
SUPPLIER_ID SUPPLIER_NAME CITY
5001 Microsoft Chicago
5002 IBM San Francisco
5003 Red Hat Detroit
5004 NVIDIA New York
PRACTICE EXERCISE #2:
Based on the suppliers and customers table populated with the following data, update the city in the suppliers table with
the city in the customers table when the supplier_name in the suppliers table matches thecustomer_name in
the customers table.
CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
city varchar2(50),
CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)
);

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5001, 'Microsoft', 'New York');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5002, 'IBM', 'Chicago');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5003, 'Red Hat', 'Detroit');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5005, 'NVIDIA', 'LA');


CREATE TABLE customers
( customer_id number(10) not null,
customer_name varchar2(50) not null,
city varchar2(50),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7001, 'Microsoft', 'San Francisco');

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7002, 'IBM', 'Toronto');

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7003, 'Red Hat', 'Newark');
SOLUTION FOR PRACTICE EXERCISE #2:
The following UPDATE statement would perform this update in Oracle.
UPDATE suppliers
SET city = (SELECT customers.city
FROM customers
WHERE customers.customer_name = suppliers.supplier_name)
WHERE EXISTS (SELECT customers.city
FROM customers
WHERE customers.customer_name = suppliers.supplier_name);
The suppliers table would now look like this:
SUPPLIER_ID SUPPLIER_NAME CITY
5001 Microsoft San Francisco
5002 IBM Toronto
5003 Red Hat Newark
5004 NVIDIA LA

ORACLE/PLSQL: DELETE STATEMENT
Learn how to use the Oracle DELETE statement with syntax, examples, and practice exercises.
DESCRIPTION
The Oracle DELETE statement is used to delete a single record or multiple records from a table in Oracle.
SYNTAX
The syntax for the Oracle DELETE statement is:
DELETE FROM table
WHERE conditions;
PARAMETERS OR ARGUMENTS
table is the table that you wish to delete records from.
conditions are conditions that must be met for the records to be deleted.
NOTE
You do not need to list fields in the Oracle DELETE statement since you are deleting the entire row from the table.
EXAMPLE - USING ONE CONDITION
Let's look at a simple Oracle DELETE query example, where we just have one condition in the DELETE statement.
For example:
DELETE FROM customers
WHERE last_name = 'Smith';
This Oracle DELETE example would delete all records from the customers table where the last_name is Smith.
You may wish to check for the number of rows that will be deleted. You can determine the number of rows that will be
deleted by running the following Oracle SELECT statement beforeperforming the delete.
SELECT count(*)
FROM customers
WHERE last_name = 'Smith';
EXAMPLE - USING TWO CONDITIONS
Let's look at an Oracle DELETE example, where we just have two conditions in the DELETE statement.
For example:
DELETE FROM customers
WHERE last_name = 'Anderson'
AND customer_id > 25;
This Oracle DELETE example would delete all records from the customers table where the last_name is 'Anderson' and
the customer_id is greater than 25.
You may wish to check for the number of rows that will be deleted. You can determine the number of rows that will be
deleted by running the following Oracle SELECT statement before performing the delete.
SELECT count(*)
FROM customers
WHERE last_name = 'Anderson'
AND customer_id > 25;
EXAMPLE - USING EXISTS CLAUSE
You can also perform more complicated deletes.
You may wish to delete records in one table based on values in another table. Since you can't list more than one table in
the Oracle FROM clause when you are performing a delete, you can use the Oracle EXISTS clause.
For example:
DELETE FROM suppliers
WHERE EXISTS
( SELECT customers.customer_name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id
AND customer_id > 25 );
This Oracle DELETE example would delete all records in the suppliers table where there is a record in
the customers table whose customer_id is greater than 25, and the customer_id matches the supplier_id.
If you wish to determine the number of rows that will be deleted, you can run the following Oracle SELECT
statement before performing the delete.
SELECT COUNT(*) FROM suppliers
WHERE EXISTS
( SELECT customers.customer_name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id
AND customer_id > 25 );
FREQUENTLY ASKED QUESTIONS
Question: How would I write an Oracle DELETE statement to delete all records in TableA whose data in field1 & field2
DO NOT match the data in fieldx & fieldz of TableB?
Answer: You could try something like this for your Oracle DELETE statement:
DELETE FROM TableA
WHERE NOT EXISTS
( SELECT *
FROM TableB
WHERE TableA.field1 = TableB.fieldx
AND TableA.field2 = TableB.fieldz );
PRACTICE EXERCISE #1:
Based on the contacts table, delete all records from the contacts table who reside in the City of 'Las Vegas' and
whose first_name is 'Jane'.
CREATE TABLE contacts
( contact_id number(10) not null,
last_name varchar2(50) not null,
first_name varchar2(50) not null,
address varchar2(50),
city varchar2(50),
state varchar2(2),
zip_code varchar2(10),
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
SOLUTION FOR PRACTICE EXERCISE #1:
The following Oracle DELETE statement would delete these records from the contacts table:
DELETE FROM contacts
WHERE city = 'Las Vegas'
AND first_name = 'Jane';
PRACTICE EXERCISE #2:
Based on the contacts table, delete all records from the contacts table whose contact_id is greater than or equal to 5000
and less than 6000.
CREATE TABLE contacts
( contact_id number(10) not null,
last_name varchar2(50) not null,
first_name varchar2(50) not null,
address varchar2(50),
city varchar2(50),
state varchar2(2),
zip_code varchar2(10),
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
SOLUTION FOR PRACTICE EXERCISE #2:
The following Oracle DELETE statement would delete these records from the contacts table:
DELETE FROM contacts
WHERE contact_id >= 5000
AND contact_id < 6000.
Or you could write the solution using the BETWEEN clause as follows:
DELETE FROM contacts
WHERE contact_id BETWEEN 5000 AND 5999;

ORACLE/PLSQL: IF-THEN-ELSE STATEMENT
Learn how to use the IF-THEN-ELSE statement in Oracle with syntax and examples.
DESCRIPTION
In Oracle, the IF-THEN-ELSE statement is used to execute code when a condition is TRUE, or execute different code if
the condition evaluates to FALSE.
SYNTAX
There are different syntaxes for the IF-THEN-ELSE statement.
SYNTAX (IF-THEN)
The syntax is for IF-THEN in Oracle/PLSQL is:
IF condition THEN
{...statements to execute when condition is TRUE...}
END IF;
You use the the IF-THEN syntax, when you want to execute statements only when condition is TRUE.
SYNTAX (IF-THEN-ELSE)
The syntax is for IF-THEN-ELSE in Oracle/PLSQL is:
IF condition THEN
{...statements to execute when condition is TRUE...}

ELSE
{...statements to execute when condition is FALSE...}

END IF;
You use the IF-THEN-ELSE syntax, when you want to execute one set of statements when condition is TRUE or a
different set of statements when condition is FALSE.
SYNTAX (IF-THEN-ELSIF)
The syntax for IF-THEN-ELSIF in Oracle/PLSQL is:
IF condition1 THEN
{...statements to execute when condition1 is TRUE...}

ELSIF condition2 THEN
{...statements to execute when condition2 is TRUE...}

END IF;
You use the IF-THEN-ELSEIF syntax, when you want to execute one set of statements when condition1 is TRUE or a
different set of statements when condition2 is TRUE.
SYNTAX (IF-THEN-ELSIF-ELSE)
The syntax for IF-THEN-ELSIF-ELSE in Oracle/PLSQL is:
IF condition1 THEN
{...statements to execute when condition1 is TRUE...}

ELSIF condition2 THEN
{...statements to execute when condition2 is TRUE...}

ELSE
{...statements to execute when both condition1 and condition2 are FALSE...}

END IF;
You use the IF-THEN-ELSEIF-ELSE syntax, when you want to execute one set of statements when condition1 is TRUE,
a different set of statements when condition2 is TRUE, or a different set of statements when all previous conditions
(ie: condition1 and condition2) are FALSE.
NOTE
Once a condition is found to be TRUE, the IF-THEN-ELSE statement will execute the corresponding code and not
evaluate the conditions any further.
If no condition is met, the ELSE portion of the IF-THEN-ELSE statement will be executed.
It is important to note that the ELSIF and ELSE portions are optional.
EXAMPLE
The following is example using the IF-THEN-ELSE statement in an Oracle function:
CREATE OR REPLACE Function IncomeLevel
( name_in IN varchar2 )
RETURN varchar2
IS
monthly_value number(6);
ILevel varchar2(20);

cursor c1 is
SELECT monthly_income
FROM employees
WHERE name = name_in;

BEGIN

open c1;
fetch c1 into monthly_value;
close c1;

IF monthly_value <= 4000 THEN
ILevel := 'Low Income';

ELSIF monthly_value > 4000 and monthly_value <= 7000 THEN
ILevel := 'Avg Income';

ELSIF monthly_value > 7000 and monthly_value <= 15000 THEN
ILevel := 'Moderate Income';

ELSE
ILevel := 'High Income';

END IF;

RETURN ILevel;

END;
In this IF-THEN-ELSE statement example, we've created a function called IncomeLevel. It has one parameter
called name_in and it returns a varchar2. The function will return the income level based on the employee's name.

You might also like