You are on page 1of 47

Delete

DML Command
This command deletes only the
rows from the table based on the
condition given in the where
clause or
Deletes all the rows from the
table if no condition is specified.
But it does not free the space
containing the table
Delete removes content of a
database.

Drop
DDL Command
It removes the all the records or
rows or information along with
structure. It also removes all
information about the table from
data dictionary.

Truncate
DDL Command
This command is used to delete
all the rows or information of
records from the table and free
the space containing the table.

Drop removes the structure of a


database.

After performing a DELETE


operation you need to COMMIT
or ROLLBACK the transaction
to make the change permanent or
to undo it.
It can be Rollback

Oracle 10g provide the command


to recover it by using the
command (FLASHBACK)

It cant be Rollback

DDL(Data Defination Langauge)1.Create- To create table.


2.Alter- To alter/modify table.
3.Drop- To delete table.
*Create Syntax-

Create Table <Table name>


(col1 Datatype size, col2 Datatype size,..... clo Datatype size);

e.g- create table Employee(empid number (5), empname varchar2(10), address varchar2(30));

*How to create table form existing table-

CREATE TABLE NEW_TABLE_NAME AS


SELECT [ column1, column2...columnN ]
FROM EXISTING_TABLE_NAME
[ WHERE ]

OR

CREATE TABLE TABLE_NAME


AS (SELECT * FROM EXISTING_TABLE);

e.g-CREATE TABLE EMPLOYEE1

AS SELECT(empid, empname, address)


FROM EMPLOYEE;
*Question: How can I create a SQL table from another table without copying any values from the old
table?
Answer: To do this, the SQL CREATE TABLE syntax is:
CREATE TABLE new_table
AS (SELECT *
FROM old_table WHERE 1=2);
For example:
CREATE TABLE suppliers
AS (SELECT *FROM companies WHERE 1=2);
This would create a new table called suppliers that included all columns from the companies table, but no
data from the companies table.
2.ALTER- The SQL ALTER TABLE statement is used to add, modify, or drop/delete columns in a table.
The SQL ALTER TABLE statement is also used to rename a table.
*ADD COLUMN IN TABLE
Syntax:
ALTER TABLE table_name
ADD column_name column-definition;
For example: ALTER TABLE supplier
ADD supplier_name varchar2(50);
This SQL ALTER TABLE example will add a column called supplier_name to the supplier table.

**ADD MULTIPLE COLUMNS IN TABLEALTER TABLE table_name


ADD (column_1 column-definition,
column_2 column-definition, ...
column_n column_definition);
For example:
ALTER TABLE supplier

ADD (supplier_name varchar2(50),


city varchar2(45));
This SQL ALTER TABLE example will add two columns, supplier_name as a varchar2(50) field and city
as a varchar2(45) field to the supplier table.
**MODIFY COLUMN IN TABLE- To change data type.
SyntaxALTER TABLE table_name
MODIFY column_name column_type;
Example-ALTER TABLE supplier
MODIFY supplier_name varchar2(100) NOT NULL;
**MODIFY MULTIPLE COLUMNS IN TABLESyntaxALTER TABLE table_name
MODIFY (column_1 column_type,
column_2 column_type, ...
column_n column_type);
For example: ALTER TABLE supplier
MODIFY (supplier_name varchar2(100) NOT NULL,
city varchar2(75));

**DROP COLUMN IN TABLESyntax- ALTER TABLE table_name DROP COLUMN column_name;


For example: ALTER TABLE supplier
DROP COLUMN supplier_name;
**RENAME COLUMN IN TABLE- To rename a column in an existing table.
Syntax- ALTER TABLE table_name
RENAME COLUMN old_name TO new_name;
For example: ALTER TABLE supplier
RENAME COLUMN supplier_name TO sname;

**** To delete data parmanentaly- We use PURGE command.


Syntax- DROP TABLE <TABLE NAME> PURGE;
** RENAME TABLESyntax- ALTER TABLE table_name
RENAME TO new_table_name;
OR ALTER TABLE table_name
RENAME <old col. name> TO <new col. name>;
For example: ALTER TABLE supplier
RENAME TO vendor;
***PRACTICE EXERCISE #
1: Based on the departments table below, rename the departments table to depts.
2: Based on the employees table below, add a column called salary that is a number(6) datatype.
3: Based on the customers table below, add two columns - one column called contact_name that is a
varchar2(50) datatype and one column called last_contacted that is a date datatype.
4: Based on the employees table below, change the employee_name column to a varchar2(75) datatype.
5: Based on the customers table below, change the customer_name column to NOT allow null values and
change the statecolumn to a varchar2(2) datatype.
6: Based on the employees table below, drop the salary column.
7: Based on the departments table below, rename the department_name column to dept_name.
SQL: INSERT STATEMENT
This SQL tutorial explains how to use the SQL INSERT statement with syntax, examples, and practice
exercises. There are 2 syntaxes for the INSERT statement depending on whether you are inserting one
record or multiple records.
DESCRIPTION
The SQL INSERT statement is used to insert a one or more records into a table.
SYNTAX
The syntax for the SQL 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 SQL INSERT statement when inserting multiple records using a SELECT statement
is:
INSERT INTO table
(column1, column2, ... )
SELECT expression1, expression2, ...
FROM source_tables
[WHERE conditions];

Parameters or Arguments
table
The table in which to insert the records.
column1, column2
These are the columns in the table to insert values.
expression1, expression2
These 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_tables
Used when inserting records from another table. This is the source table when performing the
insert.
WHERE conditions
Optional. Used when inserting records from another table. These are the conditions that must be
met for the records to be inserted.
NOTE

When inserting records into a table using the SQL INSERT statement, you must provide a value
for every NOT NULL column.

You can omit a column from the SQL INSERT statement if the column allows NULL values.

Insert Muktiple value at onces:insert all

into emp (EmpID, name, Mob_Num, Email_ID, Location, Joining_Date, salary) values (1002,
'santosh', 1234567890, 'san@gmail.com', 'bangalore', '25-sep-2014', 12000)
into emp (EmpID, name, Mob_Num, Email_ID, Location, Joining_Date, salary) values (1003,
'abhay', 1324567890, 'abhay@gmail.com', 'pune', '10-feb-2015', 16000)
into emp (EmpID, name, Mob_Num, Email_ID, Location, Joining_Date, salary) values(1004,
'amit', 3214567890, 'abhay@hotmail.com', 'pune', '6-jan-2015', 180000)
into emp (EmpID, name, Mob_Num, Email_ID, Location, Joining_Date, salary) values (1005,
'dewashish', 5432167890, 'dewa@hotmail.com', 'bangolre', '18-march-2014', 17000)
select * from dual;
EXAMPLE - USING VALUES KEYWORD
Let's look at an example showing how to use the SQL INSERT statement. The simplest way use the
INSERT statement is to insert one record into a table using the VALUES keyword.
For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
VALUES
(24553, 'IBM');
This INSERT statement example would insert one record into the suppliers table. This new record would
have a supplier_idof 24553 and a supplier_name of IBM.
EXAMPLE - USING SELECT STATEMENT
You can also create more complicated SQL INSERT statements using SELECT statement.
For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city = 'Newark';
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 SQL SELECT
statement before performing the insert.
SELECT count(*)
FROM customers
WHERE city = 'Newark';

FREQUENTLY ASKED QUESTIONS


Question: I am setting up a database with clients. I know that you use the SQL 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 SQL EXISTS
condition.
For example, if you had a table named clients with a primary key of client_id, you could use the
following SQL 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 SQL INSERT statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following SQL 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.
PRACTICE EXERCISE #1:
Based on the employees table, insert an employee record whose employee_number is
1001, employee_name is Sally Johnson and salary is $32,000:
CREATE TABLE employees
( employee_number number(10) not null,
employee_name varchar2(50) not null,
salary number(6),
CONSTRAINT employees_pk PRIMARY KEY (employee_number)
);

Solution for Practice Exercise #1:


The following SQL INSERT statement would insert this record into the employees table:
INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1001, 'Sally Johnson', 32000);

PRACTICE EXERCISE #2:


Based on the suppliers table, insert a supplier record whose supplier_id is 5001 and supplier_name is
Apple:
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)
);

Solution for Practice Exercise #2:


The following SQL INSERT statement would insert this record into the suppliers table:

INSERT INTO suppliers (supplier_id, supplier_name)


VALUES (5001, 'Apple');

PRACTICE EXERCISE #3:


Based on the customers and old_customers table, insert into the customers table all records from
the old_customers table whose status is DELETED.
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)
);

CREATE TABLE old_customers


( old_customer_id number(10) not null,
old_customer_name varchar2(50) not null,
old_city varchar2(50),
status varchar2(20),
CONSTRAINT old_customers_pk PRIMARY KEY (old_customer_id)
);

Solution for Practice Exercise #3:


The following SQL INSERT statement would be the solution to insert into the customers table using a
sub-select:
INSERT INTO customers
(customer_id, customer_name, city)
SELECT old_customer_id, old_customer_name, old_city
FROM old_customers
WHERE status = 'DELETED';
= To insert values in column for existing table-

Syntax- Insert into <table name> (col1, col2, col3,.....) values(val1, val2, 'val3',......);
Note- To insert date- Use to_date(DD-MM-YYYY)
e.g- insert into employee
(employeeid, firstname, lastname, salary, joining, department)
values(1001, 'john', 'jam', 5000, to_date('1-jan-2013'), 'banking');

SQL: UPDATE STATEMENT


This SQL tutorial explains how to use the SQL UPDATE statement with syntax, examples, and practice
exercises. Notice that there are 3 ways to write a SQL UPDATE statement.
DESCRIPTION
The SQL UPDATE statement is used to update existing records in the tables.
SYNTAX
The syntax for the SQL UPDATE statement when updating one table is:
UPDATE table
SET column1 = expression1,
column2 = expression2,
...
[WHERE conditions];
OR
The syntax for the SQL UPDATE statement when updating one table with data from another table is:
UPDATE table1
SET column1 = (SELECT expression1
FROM table2
WHERE conditions)
[WHERE conditions];
OR
The syntax for the SQL UPDATE statement when updating multiple tables (not permitted in Oracle) is:

UPDATE table1, table2, ...


SET column1 = expression1,
column2 = expression2,
...
WHERE table1.column = table2.column
AND conditions;

Parameters or Arguments
column1, column2
The columns that you wish to update.
expression1, expression2
These 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 of expression2, and so on.
WHERE conditions
Optional. The conditions that must be met for the update to execute. If no conditions are
provided, then all records in the table will be updated.
EXAMPLE - UPDATE SINGLE COLUMN
Let's look at an example showing how to use the SQL UPDATE statement to update a single column in a
table.
UPDATE suppliers
SET supplier_id = 50001
WHERE supplier_name = 'Apple';
This SQL UPDATE example would update the supplier_id to 50001 in the suppliers table where
the supplier_name is 'Apple'.
EXAMPLE - UPDATE MULTIPLE COLUMNS
Let's look at an UPDATE example that shows how to update more than one column in a table.
UPDATE suppliers
SET supplier_name = 'Apple',
product = 'iPhone'
WHERE supplier_name = 'RIM';

When you wish to update multiple columns, you can do this by separating the column/value pairs with
commas.
This SQL UPDATE statement example would update the supplier_name to "Apple" and product to
"iPhone" where thesupplier_name is "RIM".
EXAMPLE - UPDATE TABLE WITH DATA FROM ANOTHER TABLE
Let's look at an 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 customers table, the contract_datefrom the suppliers table would be copied to the c_details field in
the customers table.
EXAMPLE - UPDATE MULTIPLE TABLES
Let's look at an UPDATE example that shows how to update multiple tables in an UPDATE statement.
(Please note that this syntax is not valid in Oracle).
UPDATE suppliers, contacts
SET suppliers.status = 'Active',
contacts.note = 'Also Supplier'
WHERE suppliers.supplier_id = contacts.contact_id;
This UPDATE example would update columns in both the suppliers and contacts tables. When
the supplier_id matches thecontact_id, the status column in the suppliers table would be updated to
'Active' and the note column in the contacts table would be updated to 'Also Supplier'.
EXAMPLE - USING EXISTS CLAUSE
You can also perform more complicated updates using the UPDATE statement.
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 SQL UPDATE statement, you can use the SQL 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);
Or you could rewrite this UPDATE statement using the UPDATE syntax that allows multiple tables as
follows:
UPDATE suppliers, customers
SET suppliers.supplier_name = customers.customer_name
WHERE suppliers.supplier_id = customers.customer_id;
In this SQL 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 "Santa Clara" for all
records whosesupplier_name is "NVIDIA".
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 (5004, 'NVIDIA', 'New York');

Solution for Practice Exercise #1:


The following SQL UPDATE statement would perform this update in SQL.
UPDATE suppliers
SET city = 'Santa Clara'
WHERE supplier_name = 'NVIDIA';
The suppliers table would now look like this:
SUPPLIER_ID

SUPPLIER_NAME

CITY

5001

Microsoft

New York

5002

IBM

Chicago

5003

Red Hat

Detroit

5004

NVIDIA

Santa Clara

PRACTICE EXERCISE #2:


Based on the suppliers and customers table populated with the following data, update the city in
the suppliers table with thecity in the customers table when the supplier_name in the suppliers table
matches the customer_name in the customerstable.
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 SQL UPDATE statement would perform this update in SQL.
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

SQL: DELETE STATEMENT


This SQL tutorial explains how to use the SQL DELETE statement with syntax, examples, and practice
exercises.
DESCRIPTION
The SQL DELETE statement is a used to delete a one or more records from a table.
SYNTAX
The syntax for the SQL DELETE statement is:
DELETE FROM table

[WHERE conditions];

Parameters or Arguments
table
The table that you wish to delete records from.
WHERE conditions
Optional. The conditions that must be met for the records to be deleted. If no conditions are
provided, all records in the table will be deleted.
NOTE

You do not need to list fields in the DELETE statement since you are deleting the entire row from
the table.

EXAMPLE - WITH ONE CONDITION


Let's look at an example showing how to use the SQL DELETE statement.
For example:
DELETE FROM suppliers
WHERE supplier_name = 'IBM';
This SQL DELETE example would delete all records from the suppliers table where the supplier_name is
IBM.
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 SQL SELECT statement before performing the delete.
SELECT count(*)
FROM suppliers
WHERE supplier_name = 'IBM';

EXAMPLE - WITH TWO CONDITIONS


Let's look at a SQL DELETE example, where we just have two conditions in the SQL DELETE
statement.
For example:
DELETE FROM products

WHERE units >= 12


AND category = 'Clothing';
This SQL DELETE example would delete all records from the products table where the units is greater
than or equal to 12 and the category is Clothing.
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 SQL SELECT statement before performing the delete.
SELECT count(*)
FROM products
WHERE units >= 12
AND category = 'Clothing';

EXAMPLE - USING SQL 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 SQL FROM clause when you are performing a delete, you can use the SQL EXISTS
clause.
For example:
DELETE FROM suppliers
WHERE EXISTS
( SELECT customers.customer_name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id
AND customers.customer_name = 'IBM' );
This SQL DELETE example would delete all records in the suppliers table where there is a record in the
customers table whose name is IBM, and the customer_id is the same as the supplier_id.
If you wish to determine the number of rows that will be deleted, you can run the following SQL
SELECT statement beforeperforming the delete.
SELECT COUNT(*) FROM suppliers
WHERE EXISTS
( SELECT customers.customer_name

FROM customers
WHERE customers.customer_id = suppliers.supplier_id
AND customers.customer_name = 'IBM' );

FREQUENTLY ASKED QUESTIONS


Question: How would I write a SQL 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 SQL 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 employees table, delete all employee records whose salary is greater than $40,000:
CREATE TABLE employees
( employee_number number(10) not null,
employee_name varchar2(50) not null,
salary number(6),
CONSTRAINT employees_pk PRIMARY KEY (employee_number)
);

Solution for Practice Exercise #1:


The following SQL DELETE statement would delete these records from the employees table:
DELETE FROM employees
WHERE salary > 40000;

PRACTICE EXERCISE #2:


Based on the suppliers table, delete the supplier record whose supplier_id is 5001 and supplier_name is
Apple:
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)
);

Solution for Practice Exercise #2:


The following SQL DELETE statement would delete this record from the suppliers table:
DELETE FROM suppliers
WHERE supplier_id = 5001
AND supplier_name = 'Apple';

PRACTICE EXERCISE #3:


Based on the customers and old_customers table, delete from the customers table all records that exist in
theold_customers table (matching the customer_id field from the customers table to
the old_customer_id field in theold_customers table).
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)
);

CREATE TABLE old_customers


( old_customer_id number(10) not null,
old_customer_name varchar2(50) not null,

old_city varchar2(50),
status varchar2(20),
CONSTRAINT old_customers_pk PRIMARY KEY (old_customer_id)
);

Solution for Practice Exercise #3:


The following SQL DELETE statement would be the solution (using the SQL EXISTS clause) that would
delete the records from the customers table:
DELETE FROM customers
WHERE EXISTS
( SELECT old_customers.old_customer_id
FROM old_customers
WHERE old_customers.old_customer_id = customers.customer_id );

SQL: SELECT STATEMENT


This SQL tutorial explains how to use the SQL SELECT statement with syntax, examples, and practice
exercises.
DESCRIPTION
The SQL SELECT statement is used to retrieve records from one or more tables in your SQL database.
SYNTAX
The syntax for the SQL SELECT statement is:
SELECT expressions
FROM tables
[WHERE conditions];

Parameters or Arguments
expressions
The columns or calculations that you wish to retrieve.
tables

The tables that you wish to retrieve records from. There must be at least one table listed in the
FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected. If no conditions are
provided, then all records will be selected.
EXAMPLE - SELECT ALL FIELDS FROM ONE TABLE
Let's look at an example showing how to use the SQL SELECT statement to select all fields from a table.
SELECT *
FROM suppliers
WHERE city = 'Newark'
ORDER BY city DESC;
In this SQL SELECT statement example, we've used * to signify that we wish to view all fields from the
suppliers table where the supplier resides in Newark. The result set is sorted by city in descending order.
EXAMPLE - SELECT INDIVIDUAL FIELDS FROM ONE TABLE
You can also use the SQL SELECT statement to select individual fields from the table, as opposed to all
fields from the table.
For example:
SELECT supplier_name, city, state
FROM suppliers
WHERE supplier_id > 1000
ORDER BY name ASC, city DESC;
This SQL SELECT example would return only the supplier_name, city, and state fields from
the suppliers table where thesupplier_id value is greater than 1000. The results are sorted by
supplier_name in ascending order and then city in descending order.
EXAMPLE - SELECT FIELDS FROM MULTIPLE TABLES
You can also use the SQL SELECT statement to retrieve fields from multiple tables.
SELECT orders.order_id, suppliers.name
FROM suppliers
INNER JOIN orders

ON suppliers.supplier_id = orders.supplier_id
ORDER BY order_id;
This SQL SELECT example joins two tables together to gives us a result set that displays the order_id
and supplier name fields where the supplier_id value existed in both the suppliers and orders table. The
results are sorted by order_id in ascending order.
Learn more about SQL joins.
PRACTICE EXERCISE #1:
Based on the employees table below, select all fields from the employees table whose salary is less than or
equal to $52,500 (no sorting is required):
CREATE TABLE employees
( employee_number number(10) not null,
employee_name varchar2(50) not null,
salary number(6),
CONSTRAINT employees_pk PRIMARY KEY (employee_number)
);

Solution for Practice Exercise #1:


The following SQL SELECT statement would select these records from the employees table:
SELECT *
FROM employees
WHERE salary <= 52500;

PRACTICE EXERCISE #2:


Based on the suppliers table below, select the unique city values that reside in the state of Florida and
order the results in descending order by city:
CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
city varchar2(50),

state varchar2(25),
CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)
);

Solution for Practice Exercise #2:


The following SQL SELECT statement would select these records from the suppliers table:
SELECT DISTINCT city
FROM suppliers
WHERE state = 'Florida'
ORDER BY city DESC;

PRACTICE EXERCISE #3:


Based on the suppliers table and the orders table below, select the supplier_id and supplier_name from
the suppliers table and select the order_date from the orders table where there is a
matching supplier_id value in both the suppliers and orderstables. Order the results by supplier_id in
descending order.
CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
city varchar2(50),
state varchar2(25),
CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE orders


( order_id number(10) not null,
supplier_id number(10) not null,
order_date date not null,
quantity number(5),
CONSTRAINT orders_pk PRIMARY KEY (order_id)

);

Solution for Practice Exercise #3:


The following SQL SELECT statement would select these records from the suppliers and orders table
(using a SQL INNER JOIN):
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
ORDER BY supplier_id DESC;

PRACTICE EXERCISE #4:


Based on the customers and old_customers table, select the customer_id and customer_name from
the customers table that exist in the old_customers table (matching the customer_id field from
the customers table to the old_customer_id field in the old_customers table). Order the results in
ascending order by customer_name and then descending order bycustomer_id.
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)
);

CREATE TABLE old_customers


( old_customer_id number(10) not null,
old_customer_name varchar2(50) not null,
old_city varchar2(50),
status varchar2(20),
CONSTRAINT old_customers_pk PRIMARY KEY (old_customer_id)
);

Solution for Practice Exercise #4:


The following SQL SELECT statement would select the records from the customers table (using the SQL
EXISTS clause):
SELECT customer_id, customer_name
FROM customers
WHERE EXISTS
( SELECT old_customers.old_customer_id
FROM old_customers
WHERE old_customers.old_customer_id = customers.customer_id )
ORDER BY customer_name ASC, customer_id DESC;
Or alternatively you could exclude the ASC keyword for customer_name in the ORDER BY clause. Both
of these SELECT statements would generate the same results:
SELECT customer_id, customer_name
FROM customers
WHERE EXISTS
( SELECT old_customers.old_customer_id
FROM old_customers WHERE old_customers.old_customer_id = customers.customer_id ) ORDER
BY customer_name, customer_jd DESC;

ALIASES- SQL ALIASES can be used to create a temporary name for columns or
tables.

COLUMN ALIASES are used to make column headings in your result set easier
to read.

TABLE ALIASES are used to shorten your SQL to make it easier to read or
when you are performing a self join (ie: listing the same table more than once in
the FROM clause).

The syntax to ALIAS A COLUMN in SQL is:- column_name AS alias_name


The syntax to ALIAS A TABLE in SQL is:- table_name alias_name

SET OPERATOR1. UNION


2. UNION ALL
3. INTERSECT
4. MINUS
Union- The SQL UNION operator is used to combine the result sets of 2 or more
SELECT statements. It removes duplicate rows between the various SELECT
statements.
Each SELECT statement within the UNION must have the same number of fields in the
result sets with similar data types.

WHAT IS THE DIFFERENCE BETWEEN UNION AND UNION ALL?

UNION removes duplicate rows.

UNION ALL does not remove duplicate rows.

SYNTAX
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
UNION
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];

NOTE

There must be same number of expressions in both SELECT statements.

The corresponding expressions must have the same data type in the SELECT
statements. For example: expression1must be the same data type in both the first and
second SELECT statement.

For example:

SELECT supplier_id

FROM suppliers

UNION

SELECT supplier_id

FROM orders

ORDER BY supplier_id;

In this SQL UNION operator example, if a supplier_id appeared in both


the suppliers and orders table, it would appear once in your result set. The
UNION operator removes duplicates. If you do not wish to remove duplicates, try
using the UNION ALL operator.

If you had the suppliers table populated with the following records:

supplier_id

supplier_name

1000

Microsoft

2000

Oracle

3000

Apple

4000

Samsung

And the orders table populated with the following records:

order_id

order_date

supplier_id

2015-08-01

2000

2015-08-01

6000

2015-08-02

7000

2015-08-03

8000

And you executed the following UNION ALL statement:

SELECT supplier_id

FROM suppliers

UNION

SELECT supplier_id

FROM orders

ORDER BY supplier_id;

You would get the following results:

supplier_id
1000
2000
3000
4000

6000
7000
8000

UNION ALL OPERATOR- The SQL UNION ALL operator is used to

combine the result sets of 2 or more SELECT statements. It does not remove duplicate
rows between the various SELECT statements (all rows are returned).
Each SELECT statement within the UNION ALL must have the same number of fields in
the result sets with similar data types.

SYNTAXSELECT expression1, expression2, ... expression_n


FROM tables
[WHERE conditions]
UNION ALL
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];

E.GSELECT supplier_id
FROM suppliers
UNION ALL
SELECT supplier_id
FROM orders

ORDER BY supplier_id;

You would get the following results:


supplier_id
1000
2000
2000
3000
4000
6000
7000
8000

INTERSECT OPERATOR-

The SQL INTERSECT operator is used to

return the results of 2 or more SELECT statements. However, it only returns the rows
selected by all queries or data sets. If a record exists in one query and not in the other, it
will be omitted from the INTERSECT results.

Explanation: The INTERSECT query will return the records in the blue shaded area.
These are the records that exist in both Dataset1 and Dataset2.
Each SQL statement within the SQL INTERSECT must have the same number of fields
in the result sets with similar data types.

SYNTAX
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
INTERSECT
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];
Example- Slect name from cricket_team
Intersect
Slect name from football_team;

MINUS OPERATORThe SQL MINUS operator is used to return all rows in the first SELECT statement that
are not returned by the second SELECT statement. Each SELECT statement will define
a dataset. The MINUS operator will retrieve all records from the first dataset and then
remove from the results all records from the second dataset.
Minus Query

Explanation: The MINUS query will return the records in the blue shaded area. These
are the records that exist in Dataset1 and not in Dataset2.
Each SELECT statement within the MINUS query must have the same number of fields
in the result sets with similar data types.
TIP: The MINUS operator is not supported in all SQL databases. It can used in
databases such as Oracle.
For databases such as SQL Server, PostgreSQL, and SQLite, use the EXCEPT
operator to perform this type of query.

SYNTAX
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
MINUS
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];

Difference B/W Minus & IntersectMinus- Eliminate the common rows or record from the result set.
Intersect- Returns common rows or records from the result set.

WHERE CLAUSEThe Oracle WHERE clause is used to filter the results from
a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX
WHERE conditions;

EXAMPLE - WITH SINGLE CONDITION


It is difficult to explain the syntax for the Oracle WHERE clause, so let's look at some
examples.
SELECT *
FROM customers
WHERE last_name = 'Anderson';

In this Oracle WHERE clause example, we've used the WHERE clause to filter our
results from the customers table. The SELECT statement above would return all rows
from the customers table where the last_name is Anderson. Because the * is used in the
SELECT, all fields from the customers table would appear in the result set.

GROUP BY CLAUSE
The Oracle GROUP BY clause is used in a SELECT statement to collect data across
multiple records and group the results by one or more columns.

SYNTAX
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM tables
[WHERE conditions]

GROUP BY expression1, expression2, ... expression_n;

EXAMPLE - USING SUM FUNCTION


Let's look at an Oracle GROUP BY query example that uses the SUM function.
This Oracle GROUP BY example uses the SUM function to return the name of the
product and the total sales (for the product).
SELECT product, SUM(sale) AS "Total sales"
FROM order_details
GROUP BY product;

Because you have listed one column (the product field) in your SELECT statement that
is not encapsulated in the SUM function, you must use the GROUP BY clause.
The product field must, therefore, be listed in the GROUP BY clause.

EXAMPLE - USING COUNT FUNCTION


Let's look at how we could use the GROUP BY clause with the COUNT function.
This GROUP BY example uses the COUNT function to return the category and the
number of suppliers (in that category) that have over 45 available_products.
SELECT category, COUNT(*) AS "Number of suppliers"
FROM suppliers
WHERE available_products > 45
GROUP BY category;

EXAMPLE - USING MIN FUNCTION


Let's next look at how we could use the GROUP BY clause with the MIN function.
This GROUP BY example uses the MIN function to return the name of each department
and the minimum salary in the department.

SELECT department, MIN(salary) AS "Lowest salary"


FROM employees
GROUP BY department;

EXAMPLE - USING MAX FUNCTION


Finally, let's look at how we could use the GROUP BY clause with the MAX function.
This GROUP BY example uses the MAX function to return the name of each
department and the maximum salary in the department.
SELECT department, MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;

HAVING CLAUSE
The Oracle HAVING clause is used in combination with the GROUP BY clause to
restrict the groups of returned rows to only those whose the condition is TRUE.

SYNTAX
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING having_condition;
Parameters or Arguments
expression1, expression2, ... expression_n

The expressions that are not encapsulated within an aggregate function and must be
included in the GROUP BY clause.
aggregate_function
It can be a function such as SUM, COUNT, MIN, MAX, or AVG functions.
aggregate_expression
This is the column or expression that the aggregate_function will be used against.
tables
The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.
WHERE conditions
Optional. These are the conditions for the records to be selected.
having_condition
This is a further condition applied only to the aggregated results to restrict the groups of
returned rows. Only those groups whose condition evaluates to TRUE will be included in
the result set.

EXAMPLE - USING SUM FUNCTION


Let's look at an Oracle HAVING clause example that uses the SUM function.
You could also use the SUM function to return the name of the department and the total
sales (in the associated department). The Oracle HAVING clause will filter the results so
that only departments with sales greater than $25,000 will be returned.
SELECT department, SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department
HAVING SUM(sales) > 25000;

EXAMPLE - USING COUNT FUNCTION

Let's look at how we could use the HAVING clause with the COUNT function.
You could use the COUNT function to return the name of the department and the
number of employees (in the associated department) that make under $49,500 / year.
The Oracle HAVING clause will filter the results so that only departments with more than
10 employees will be returned.
SELECT department, COUNT(*) AS "Number of employees"
FROM employees
WHERE salary < 49500
GROUP BY department
HAVING COUNT(*) > 10;

EXAMPLE - USING MIN FUNCTION


Let's next look at how we could use the HAVING clause with the MIN function.
You could also use the MIN function to return the name of each department and the
minimum salary in the department. The Oracle HAVING clause will return only those
departments where the minimum salary is less than $42,000.
SELECT department, MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department
HAVING MIN(salary) < 42000;

EXAMPLE - USING MAX FUNCTION


Finally, let's look at how we could use the HAVING clause with the MAX function.

For example, you could also use the MAX function to return the name of each
department and the maximum salary in the department. The Oracle HAVING clause will
return only those departments whose maximum salary is greater than $45,000.
SELECT department, MAX(salary) AS "Highest salary"

FROM employees
GROUP BY department
HAVING MAX(salary) > 45000;

DISTINCT CLAUSE
The Oracle DISTINCT clause is used to remove duplicates from the result set. The
DISTINCT clause can only be used withSELECT statements.

SYNTAX
SELECT DISTINCT expressions
FROM tables
[WHERE conditions];

NOTE

When only one expression is provided in the DISTINCT clause, the query will return the
unique values for that expression.

When more than one expression is provided in the DISTINCT clause, the query will
retrieve unique combinations for the expressions listed.

In Oracle, the DISTINCT clause doesn't ignore NULL values. So when using the
DISTINCT clause in your SQL statement, your result set will include NULL as a distinct
value.

EXAMPLE - WITH SINGLE EXPRESSION


Let's look at the simplest Oracle DISTINCT clause example. We can use the Oracle
DISTINCT clause to return a single field that removes the duplicates from the result set.
For example:
SELECT DISTINCT state

FROM customers
WHERE last_name = 'Smith';

This Oracle DISTINCT example would return all unique state values from
the customers table where the customer'slast_name is 'Smith'.

EXAMPLE - WITH MULTIPLE EXPRESSIONS


Let's look at how you might use the Oracle DISTINCT clause to remove duplicates from
more than one field in your SELECT statement.
For example:
SELECT DISTINCT city, state
FROM customers
WHERE total_orders > 10
ORDER BY city;

This Oracle DISTINCT clause example would return each


unique city and state combination from the customers table where the total_orders is
greater than 10. The results are sorted in ascending order by city.
In this case, the DISTINCT applies to each field listed after the DISTINCT keyword, and
therefore returns distinct combinations

ORDER BY CLAUSE
The SQL ORDER BY clause is used to sort the records in the result set for a SELECT
statement.

SYNTAX
SELECT expressions
FROM tables
[WHERE conditions]

ORDER BY expression [ ASC | DESC ];

NOTE

If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will be
sorted by expression in ascending order. This is equivalent to ORDER
BY expression ASC.

EXAMPLE - SORTING WITHOUT USING ASC/DESC ATTRIBUTE


The SQL ORDER BY clause can be used without specifying the ASC or DESC value.
When this attribute is omitted from the SQL ORDER BY clause, the sort order is
defaulted to ASC or ascending order.
For example:
SELECT supplier_city
FROM suppliers
WHERE supplier_name = 'IBM'
ORDER BY supplier_city;

This SQL ORDER BY example would return all records sorted by the supplier_city field
in ascending order and would be equivalent to the following SQL ORDER BY clause:
SELECT supplier_city
FROM suppliers
WHERE supplier_name = 'IBM'
ORDER BY supplier_city ASC;

Most programmers omit the ASC attribute if sorting in ascending order.

EXAMPLE - SORTING IN DESCENDING ORDER


When sorting your result set in descending order, you use the DESC attribute in your
ORDER BY clause as follows:

SELECT supplier_city
FROM suppliers
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC;

This SQL ORDER BY example would return all records sorted by the supplier_city field
in descending order.

EXAMPLE - SORTING BY RELATIVE POSITION


You can also use the SQL ORDER BY clause to sort by relative position in the result
set, where the first field in the result set is 1. The next field is 2, and so on.
For example:
SELECT supplier_city
FROM suppliers
WHERE supplier_name = 'IBM'
ORDER BY 1 DESC;

This SQL ORDER BY would return all records sorted by the supplier_city field in
descending order, since the supplier_city field is in position #1 in the result set and
would be equivalent to the following SQL ORDER BY clause:
SELECT supplier_city
FROM suppliers
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC;

EXAMPLE - USING BOTH ASC AND DESC ATTRIBUTES


When sorting your result set using the SQL ORDER BY clause, you can use the ASC
and DESC attributes in a single SQL SELECT statement.

For example:
SELECT supplier_city, supplier_state
FROM suppliers
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC, supplier_state ASC;

This SQL ORDER BY would return all records sorted by the supplier_city field in
descending order, with a secondary sort by supplier_state in ascending order.

RANK FUNCTION
The Oracle/PLSQL RANK function returns the rank of a value in a group of values. It is
very similar to the DENSE_RANK function. However, the rank function can cause nonconsecutive rankings if the tested values are the same. Whereas, theDENSE_RANK
function will always result in consecutive rankings.
The RANK function can be used two ways - as an Aggregate function or as an Analytic
function.

RANK FUNCTION SYNTAX #1 - USED AS AN AGGREGATE


FUNCTION
As an Aggregate function, the RANK function returns the rank of a row within a group
of rows.
The syntax for the RANK function when used as an Aggregate function is:
RANK( expr1 [, expr2, ... expr_n ] ) WITHIN GROUP ( ORDER BY expr1 [,
expr_2, ... expr_n ] )
Parameters or Arguments
expr1
First expression which identifies a unique row in the group.

expr2, ... expr_n


Optional. Additional expressions which identifies a unique row in the group.

NOTE

There must be the same number of expressions in the first expression list as there is in
the ORDER BY clause.

The expression lists match by position so the data types must be compatible between
the expressions in the first expression list as in the ORDER BY clause.

APPLIES TO
The RANK function can be used in the following versions of Oracle/PLSQL:

Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i

EXAMPLE (AS AN AGGREGATE FUNCTION)


Let's look at some Oracle RANK function examples and explore how to use the RANK
function in Oracle/PLSQL.
For example:
select RANK(1000, 500) WITHIN GROUP (ORDER BY salary, bonus)
from employees;

The SQL statement above would return the rank of an employee with a salary of $1,000
and a bonus of $500 from within the employees table.

RANK FUNCTION SYNTAX #2 - USED AS AN ANALYTIC


FUNCTION
As an Analytic function, the RANK function returns the rank of each row of a query with
respective to the other rows.
The syntax for the RANK function when used as an Analytic function is:

rank() OVER ( [ query_partition_clause] ORDER BY clause )

APPLIES TO
The RANK function can be used in the following versions of Oracle/PLSQL:

Oracle 11g, Oracle 10g, Oracle 9i, Oracle 8i

EXAMPLE (AS AN ANALYTIC FUNCTION)


select employee_name, salary,
RANK() OVER (PARTITION BY department ORDER BY salary)
from employees
where department = 'Marketing';

The SQL statement above would return all employees who work in the Marketing
department and then calculate a rank for each unique salary in the Marketing
department. If two employees had the same salary, the RANK function would return the
same rank for both employees. However, this will cause a gap in the ranks (ie: nonconsecutive ranks). This is quite different from the DENSE_RANK function which
generates consecutive rankings.

DENSE_RANK FUNCTION
The Oracle/PLSQL DENSE_RANK function returns the rank of a row in a group of rows.
It is very similar to the RANK function. However, the RANK function can cause nonconsecutive rankings if the tested values are the same. Whereas, the DENSE_RANK
function will always result in consecutive rankings.
The DENSE_RANK function can be used two ways - as an Aggregate function or as an
Analytic function.

DENSE_RANK FUNCTION SYNTAX #1 - USED AS AN


AGGREGATE FUNCTION

As an Aggregate function, the DENSE_RANK function returns the dense rank of a row
within a group of rows.
The syntax for the DENSE_RANK function when used as an Aggregate function is:
DENSE_RANK( expression1, ... expression_n ) WITHIN GROUP ( ORDER BY
expression1, ... expression_n )
Parameters or Arguments
expression1 .. expression_n
One or more expressions which identify a unique row in the group.

NOTE

There must be the same number of expressions in the first expression list as there is in
the ORDER BY clause.

The expression lists match by position so the data types must be compatible between
the expressions in the first expression list as in the ORDER BY clause.

APPLIES TO
The DENSE_RANK function can be used in the following versions of Oracle/PLSQL:

Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i

EXAMPLE (AS AN AGGREGATE FUNCTION)


Let's look at some Oracle DENSE_RANK function examples and explore how to use the
DENSE_RANK function in Oracle/PLSQL.
For example:
select DENSE_RANK(1000, 500) WITHIN GROUP (ORDER BY salary, bonus)
from employees;

The SQL statement above would return the dense rank of an employee with a salary of
$1,000 and a bonus of $500 from within the employees table.

DENSE_RANK FUNCTION SYNTAX #2 - USED AS AN ANALYTIC


FUNCTION
As an Analytic function, the DENSE_RANK function returns the rank of each row of a
query with respective to the other rows.
The syntax for the DENSE_RANK function when used as an Analytic function is:
DENSE_RANK() OVER ( [ query_partition_clause] ORDER BY clause )

APPLIES TO
The DENSE_RANK function can be used in the following versions of Oracle/PLSQL:

Oracle 11g, Oracle 10g, Oracle 9i, Oracle 8i

EXAMPLE (AS AN ANALYTIC FUNCTION)


Let's look at some Oracle DENSE_RANK function examples and explore how to use the
DENSE_RANK function in Oracle/PLSQL.
For example:
select employee_name, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary)
from employees
where department = 'Marketing';

The SQL statement above would return all employees who work in the Marketing
department and then calculate a rank for each unique salary in the Marketing
department. If two employees had the same salary, the DENSE_RANK function would
return the same rank for both employees.

You might also like