1. SQL
SQL stands for "Structured Query Language". It is used by relational database technologies such as Oracle,
Microsoft Access, MySQL, and Sybase, among others. We've categorized SQL into the following topics:
SQL QUERY TYPES
SELECT Statement Retrieve records from a table
INSERT Statement Insert records into a table
UPDATE Statement Update records in a table
DELETE Statement Delete records from a table
UNION Operator Combine 2 result sets (removes duplicates)
UNION ALL Operator Combine 2 result sets (includes duplicates)
INTERSECT Operator Intersection of 2 result sets
MINUS Operator Result set of one minus the result set of another
SQL JOINS
JOIN TABLES Inner and Outer joins
SQL ALIASES
ALIASES Create a temporary name for a column or table
SQL CLAUSES
DISTINCT Clause Retrieve unique records
WHERE Clause Filter results
ORDER BY Clause Sort query results
GROUP BY Clause Group by one or more columns
HAVING Clause Restrict the groups of returned rows
SQL FUNCTIONS
COUNT Function Return the number of rows in a query
SUM Function Return the sum of an expression
2. MIN Function Return the min of an expression
MAX Function Return the max of an expression
AVG Function Return the average of an expression
SQL CONDITIONS
AND Condition 2 or more conditions to be met
OR Condition Any one of the conditions are met
AND & OR Combining AND and OR conditions
LIKE Condition Use wildcards in a WHERE clause
IN Condition Alternative to multiple OR conditions
NOT Condition Negate a condition
IS NULL Condition Test for NULL value
IS NOT NULL
Condition
Test for NOT NULL value
BETWEEN Condition Retrieve within a range (inclusive)
EXISTS Condition Condition is met if subquery returns at least one row
SQL TABLES AND VIEWS
CREATE TABLE Create a table
CREATE TABLE AS Create a table from another table's definition and data
ALTER TABLE Add, modify or delete columns in a table; rename a table
DROP TABLE Delete a table
GLOBAL TEMP
Tables
Tables that are distinct within SQL session
LOCAL TEMP Tables Tables that are distinct within modules and embedded SQL program
SQL VIEW Virtual tables (views of other tables)
SQL DATA TYPES
Data Types Data Types in SQL
3. SQL: SELECT STATEMENT
Learn 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 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 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;
4. 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 the supplier_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:
5. 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)
);
6. 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 orders tables. 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),
7. 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_customerstable (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 by customer_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
8. ( 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
9. WHERE old_customers.old_customer_id = customers.customer_id )
ORDER BY customer_name, customer_jd DESC;
SQL: INSERT STATEMENT
Learn 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
10. 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_tables 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 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.
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_id of 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
11. (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 *
12. 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:
13. 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,
14. 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';
SQL: UPDATE STATEMENT
Learn 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.
15. 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,
16. ...
WHERE table1.column = table2.column
AND 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
of expression2, and so on.
conditions are the conditions that must be met for the update to execute.
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';
17. 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 the supplier_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 thesuppliers table matches
the customer_name from the customers table, the contract_date from 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 the contact_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.
18. 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 whose supplier_name is "NVIDIA".
CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
city varchar2(50),
19. 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
20. 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 the city in the customers table when the supplier_name in
the suppliers table matches the customer_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)
21. 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:
22. 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
Learn 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:
23. 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 SQL 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.
24. 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
25. 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 before performing 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:
26. 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
27. 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 the old_customers table (matching thecustomer_id field from the customers table to
the old_customer_id field in the old_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:
28. DELETE FROM customers
WHERE EXISTS
( SELECT old_customers.old_customer_id
FROM old_customers
WHERE old_customers.old_customer_id = customers.customer_id );
SQL: UNION OPERATOR
Learn how to use the SQL UNION operator with syntax and examples.
DESCRIPTION
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.
SYNTAX
The syntax for the SQL UNION operator is:
SELECT expression1, expression2, ... expression_n
FROM tables
WHERE conditions
UNION
SELECT expression1, expression2, ... expression_n
FROM tables
WHERE conditions;
PARAMETERS OR ARGUMENTS
29. expression1, expression2, expression_n 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.
NOTE
There must be same number of expressions in both SELECT statements.
See also the UNION ALL operator.
EXAMPLE - RETURN SINGLE FIELD
The following is an example of the SQL UNION operator that returns one field from multiple
SELECT statements (and both fields have the same data type):
SELECT supplier_id
FROM suppliers
UNION
SELECT supplier_id
FROM orders;
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 SQL UNION operator removes duplicates. If
you do not wish to remove duplicates, try using the UNION ALL operator.
EXAMPLE - USING SQL ORDER BY CLAUSE
The SQL UNION operator can use the SQL ORDER BY clause to order the results of the query.
For example:
SELECT supplier_id, supplier_name
FROM suppliers
WHERE supplier_id > 2000
UNION
30. SELECT company_id, company_name
FROM companies
WHERE company_id > 1000
ORDER BY 2;
In this SQL UNION example, since the column names are different between the two SELECT
statements, it is more advantageous to reference the columns in the ORDER BY clause by their
position in the result set. In this example, we've sorted the results by supplier_name /
company_name in ascending order, as denoted by the "ORDER BY 2".
The supplier_name / company_name fields are in position #2 in the result set.
FREQUENTLY ASKED QUESTIONS
Question: I need to compare two dates and return the count of a field based on the date values.
For example, I have a date field in a table called last updated date. I have to check if
trunc(last_updated_date >= trunc(sysdate-13).
Answer: Since you are using the COUNT function which is an aggregate function, we'd
recommend using the Oracle UNION operator. For example, you could try the following:
SELECT a.code AS Code, a.name AS Name, COUNT(b.Ncode)
FROM cdmaster a, nmmaster b
WHERE a.code = b.code
AND a.status = 1
AND b.status = 1
AND b.Ncode <> 'a10'
AND TRUNC(last_updated_date) <= TRUNC(sysdate-13)
GROUP BY a.code, a.name
UNION
SELECT a.code AS Code, a.name AS Name, COUNT(b.Ncode)
31. FROM cdmaster a, nmmaster b
WHERE a.code = b.code
AND a.status = 1
AND b.status = 1
AND b.Ncode <> 'a10'
AND TRUNC(last_updated_date) > TRUNC(sysdate-13)
GROUP BY a.code, a.name;
The Oracle UNION allows you to perform a count based on one set of criteria.
TRUNC(last_updated_date) <= TRUNC(sysdate-13)
As well as perform a count based on another set of criteria.
TRUNC(last_updated_date) > TRUNC(sysdate-13)
SQL: UNION ALL OPERATOR
Learn how to use the SQL UNION ALL operator with syntax and examples.
DESCRIPTION
The SQL UNION ALL operator is used to combine the result sets of 2 or more SELECT
statements. It returns all rows from the query (even if the row exists in more than one of the
SELECT statements).
Each SELECT statement within the UNION ALL must have the same number of fields in the
result sets with similar data types.
SYNTAX
The syntax for the SQL UNION ALL operator is:
SELECT expression1, expression2, ... expression_n
32. FROM tables
WHERE conditions
UNION ALL
SELECT expression1, expression2, ... expression_n
FROM tables
WHERE conditions;
PARAMETERS OR ARGUMENTS
expression1, expression2, expression_n 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.
NOTE
There must be same number of expressions in both SELECT statements.
See also the UNION operator.
EXAMPLE - RETURN SINGLE FIELD
The following is an example of the SQL UNION ALL operator that returns one field from
multiple SELECT statements (and both fields have the same data type):
SELECT supplier_id
FROM suppliers
UNION ALL
SELECT supplier_id
FROM orders;
This SQL UNION ALL example would return a supplier_id multiple times in your result set if
the supplier_id appeared in both the suppliers and orders table. The SQL UNION ALL operator
does not remove duplicates. If you wish to remove duplicates, try using the UNION operator.
33. EXAMPLE - USING SQL ORDER BY
The UNION ALL operator can use the ORDER BY clause to order the results of the query.
For example:
SELECT supplier_id, supplier_name
FROM suppliers
WHERE supplier_id > 2000
UNION ALL
SELECT company_id, company_name
FROM companies
WHERE company_id > 1000
ORDER BY 2;
In this SQL UNION ALL example, since the column names are different between the
two SELECT statements, it is more advantageous to reference the columns in the ORDER BY
clause by their position in the result set. In this example, we've sorted the results by
supplier_name / company_name in ascending order, as denoted by the "ORDER BY 2".
The supplier_name / company_name fields are in position #2 in the result set.
SQL: INTERSECT OPERATOR
Learn how to use the SQL INTERSECT operator with syntax and examples.
DESCRIPTION
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. If a record exists in one query and not
in the other, it will be omitted from the INTERSECT results.
Each SQL statement within the SQL INTERSECT must have the same number of fields in the
result sets with similar data types.
SYNTAX
34. The syntax for the SQL INTERSECT operator is:
SELECT field1, field2, ... field_n
FROM tables
INTERSECT
SELECT field1, field2, ... field_n
FROM tables;
EXAMPLE - WITH SINGLE FIELD
The following is a SQL INTERSECT operator example that has one field with the same data
type:
SELECT supplier_id
FROM suppliers
INTERSECT
SELECT supplier_id
FROM orders;
In this SQL INTERSECT example, if a supplier_id appeared in both the suppliers and orders
table, it would appear in your result set.
EXAMPLE - USING ORDER BY
The following is an INTERSECT example that uses a ORDER BY clause:
SELECT supplier_id, supplier_name
FROM suppliers
WHERE supplier_id > 2000
INTERSECT
SELECT company_id, company_name
35. FROM companies
WHERE company_id > 1000
ORDER BY 2;
Since the column names are different between the two SELECT statements, it is more
advantageous to reference the columns in the ORDER BY clause by their position in the result
set. In this example, we've sorted the results by supplier_name / company_name in ascending
order, as denoted by the "ORDER BY 2".
The supplier_name / company_name fields are in position #2 in the result set.
SQL: MINUS OPERATOR
Learn how to use the SQL MINUS operator with syntax and examples.
DESCRIPTION
The SQL MINUS operator is used to return all rows in the first SELECT statement that are not
returned in the second SELECT statement.
Each SELECT statement within the MINUS query must have the same number of fields in the
result sets with similar data types.
SYNTAX
The syntax for the SQL MINUS operator is:
SELECT expression1, expression2, ... expression_n
FROM tables
MINUS
SELECT expression1, expression2, ... expression_n
FROM tables;
EXAMPLE - WITH SINGLE EXPRESSION
The following is a SQL MINUS operator example that has one field with the same data type:
36. SELECT supplier_id
FROM suppliers
MINUS
SELECT supplier_id
FROM orders;
This SQL MINUS example returns all supplier_id values that are in the suppliers table and not in
the orders table. What this means is that if a supplier_id value existed in the suppliers table and
also existed in the orders table, the supplier_id value would not appear in this result set.
EXAMPLE - USING ORDER BY CLAUSE
The following is a MINUS operator example that uses the ORDER BY clause:
SELECT supplier_id, supplier_name
FROM suppliers
WHERE supplier_id > 2000
MINUS
SELECT company_id, company_name
FROM companies
WHERE company_id > 1000
ORDER BY 2;
In this SQL MINUS operator example, since the column names are different between the two
SELECT statements, it is more advantageous to reference the columns in the ORDER BY clause
by their position in the result set. In this example, we've sorted the results by supplier_name /
company_name in ascending order, as denoted by the "ORDER BY 2".
The supplier_name / company_name fields are in position #2 in the result set.
37. SQL: JOINS
Learn how to use SQL joins with syntax, visual illustrations, and examples.
DESCRIPTION
SQL JOINS are used to retrieve data from multiple tables. A SQL JOIN is performed whenever
two or more tables are joined in a SQL statement.
There are 4 different types of SQL joins:
SQL INNER JOIN (or sometimes called simple join)
SQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
SQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
SQL FULL OUTER JOIN (or sometimes called FULL JOIN)
So let's discuss SQL JOIN syntax, look at visual illustrations of SQL JOINS, and explore SQL
JOIN examples.
SQL INNER JOIN (SIMPLE JOIN)
Chances are, you've already written a SQL statement that uses an SQL INNER JOIN. It is the
most common type of SQL join. SQL INNER JOINS return all rows from multiple tables where
the join condition is met.
SYNTAX
The syntax for the SQL INNER JOIN is:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
VISUAL ILLUSTRATION
In this visual diagram, the SQL INNER JOIN returns the shaded area:
38. The SQL INNER JOIN would return the records where table1 and table2 intersect.
EXAMPLE
Here is an example of a SQL INNER JOIN:
SELECT s.supplier_id, s.supplier_name, od.order_date
FROM suppliers AS s
INNER JOIN order_details AS od
ON s.supplier_id = od.supplier_id;
This SQL INNER JOIN example would return all rows from the suppliers and orders tables
where there is a matching supplier_id value in both the suppliers and orders tables.
Let's look at some data to explain how the INNER JOINS work:
We have a table called suppliers with two fields (supplier_id and supplier_ name). It contains the
following data:
supplier_id supplier_name
10000 IBM
10001 Hewlett Packard
10002 Microsoft
10003 NVIDIA
39. We have another table called orders with three fields (order_id, supplier_id, and order_date). It
contains the following data:
order_id supplier_id order_date
500125 10000 2003/05/12
500126 10001 2003/05/13
500127 10004 2003/05/14
If we run the SQL statement (that contains an INNER JOIN) below:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Our result set would look like this:
supplier_id name order_date
10000 IBM 2003/05/12
10001 Hewlett Packard 2003/05/13
The rows for Microsoft and NVIDIA from the supplier table would be omitted, since the
supplier_id's 10002 and 10003 do not exist in both tables. The row for 500127 (order_id) from
the orders table would be omitted, since the supplier_id 10004 does not exist in the suppliers
table.
OLD SYNTAX
As a final note, it is worth mentioning that the SQL INNER JOIN example above could be
rewritten using the older implicit syntax as follows (but we still recommend using the INNER
JOIN keyword syntax):
40. SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id;
SQL LEFT OUTER JOIN
Another type of join is called a LEFT OUTER JOIN. This type of join returns all rows from the
LEFT-hand table specified in the ON condition and only those rows from the other table where
the joined fields are equal (join condition is met).
SYNTAX
The syntax for the SQL LEFT OUTER JOIN is:
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
In some databases, the LEFT OUTER JOIN keywords are replaced with LEFT JOIN.
VISUAL ILLUSTRATION
In this visual diagram, the SQL LEFT OUTER JOIN returns the shaded area:
The SQL LEFT OUTER JOIN would return the all records from table1 and only those records
from table2 that intersect with table1.
EXAMPLE
41. Here is an example of a SQL LEFT OUTER JOIN:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
LEFT OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
This LEFT OUTER JOIN example would return all rows from the suppliers table and only those
rows from the orders table where the joined fields are equal.
If a supplier_id value in the suppliers table does not exist in the orders table, all fields in the
orders table will display as <null> in the result set.
Let's look at some data to explain how LEFT OUTER JOINS work:
We have a table called suppliers with two fields (supplier_id and name). It contains the
following data:
supplier_id supplier_name
10000 IBM
10001 Hewlett Packard
10002 Microsoft
10003 NVIDIA
We have a second table called orders with three fields (order_id, supplier_id, and order_date). It
contains the following data:
order_id supplier_id order_date
500125 10000 2003/05/12
500126 10001 2003/05/13
42. If we run the SQL statement (that contains a LEFT OUTER JOIN) below:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
LEFT OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Our result set would look like this:
supplier_id supplier_name order_date
10000 IBM 2003/05/12
10001 Hewlett Packard 2003/05/13
10002 Microsoft <null>
10003 NVIDIA <null>
The rows for Microsoft and NVIDIA would be included because a LEFT OUTER JOIN was
used. However, you will notice that the order_date field for those records contains a <null>
value.
OLD SYNTAX
As a final note, it is worth mentioning that the LEFT OUTER JOIN example above could be
rewritten using the older implicit syntax that utilizes the outer join operator (+) as follows (but
we still recommend using the LEFT OUTER JOIN keyword syntax):
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id(+);
SQL RIGHT OUTER JOIN
43. Another type of join is called a SQL RIGHT OUTER JOIN. This type of join returns all rows
from the RIGHT-hand table specified in the ON condition andonly those rows from the other
table where the joined fields are equal (join condition is met).
SYNTAX
The syntax for the SQL RIGHT OUTER JOIN is:
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
In some databases, the RIGHT OUTER JOIN keywords are replaced with RIGHT JOIN.
VISUAL ILLUSTRATION
In this visual diagram, the SQL RIGHT OUTER JOIN returns the shaded area:
The SQL RIGHT OUTER JOIN would return the all records from table2 and only those records
from table1 that intersect with table2.
EXAMPLE
Here is an example of a SQL RIGHT OUTER JOIN:
SELECT orders.order_id, orders.order_date, suppliers.supplier_name
FROM suppliers
RIGHT OUTER JOIN orders
44. ON suppliers.supplier_id = orders.supplier_id;
This RIGHT OUTER JOIN example would return all rows from the orders table and only those
rows from the suppliers table where the joined fields are equal.
If a supplier_id value in the orders table does not exist in the suppliers table, all fields in the
suppliers table will display as <null> in the result set.
Let's look at some data to explain how RIGHT OUTER JOINS work:
We have a table called suppliers with two fields (supplier_id and name). It contains the
following data:
supplier_id supplier_name
10000 Apple
10001 Google
We have a second table called orders with three fields (order_id, supplier_id, and order_date). It
contains the following data:
order_id supplier_id order_date
500125 10000 2013/08/12
500126 10001 2013/08/13
500127 10002 2013/08/14
If we run the SQL statement (that contains a RIGHT OUTER JOIN) below:
SELECT orders.order_id, orders.order_date, suppliers.supplier_name
FROM suppliers
RIGHT OUTER JOIN orders
45. ON suppliers.supplier_id = orders.supplier_id;
Our result set would look like this:
order_id order_date supplier_name
500125 2013/08/12 Apple
500126 2013/08/13 Google
500127 2013/08/14 <null>
The row for 500127 (order_id) would be included because a RIGHT OUTER JOIN was used.
However, you will notice that the supplier_name field for that record contains a <null> value.
OLD SYNTAX
As a final note, it is worth mentioning that the RIGHT OUTER JOIN example above could be
rewritten using the older implicit syntax that utilizes the outer join operator (+) as follows (but
we still recommend using the RIGHT OUTER JOIN keyword syntax):
SELECT orders.order_id, orders.order_date, suppliers.supplier_name
FROM suppliers, orders
WHERE suppliers.supplier_id(+) = orders.supplier_id;
SQL FULL OUTER JOIN
Another type of join is called a SQL FULL OUTER JOIN. This type of join returns all rows
from the LEFT-hand table and RIGHT-hand table with nulls in place where the join condition is
not met.
SYNTAX
The syntax for the SQL FULL OUTER JOIN is:
SELECT columns
FROM table1
46. FULL [OUTER] JOIN table2
ON table1.column = table2.column;
In some databases, the FULL OUTER JOIN keywords are replaced with FULL JOIN.
VISUAL ILLUSTRATION
In this visual diagram, the SQL FULL OUTER JOIN returns the shaded area:
The SQL FULL OUTER JOIN would return the all records from both table1 and table2.
EXAMPLE
Here is an example of a SQL FULL OUTER JOIN:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
FULL OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
This FULL OUTER JOIN example would return all rows from the suppliers table and all rows
from the orders table and whenever the join condition is not met, <nulls> would be extended to
those fields in the result set.
If a supplier_id value in the suppliers table does not exist in the orders table, all fields in the
orders table will display as <null> in the result set. If a supplier_id value in the orders table does
not exist in the suppliers table, all fields in the suppliers table will display as <null> in the result
set.
Let's look at some data to explain how FULL OUTER JOINS work:
47. We have a table called suppliers with two fields (supplier_id and name). It contains the
following data:
supplier_id supplier_name
10000 IBM
10001 Hewlett Packard
10002 Microsoft
10003 NVIDIA
We have a second table called orders with three fields (order_id, supplier_id, and order_date). It
contains the following data:
order_id supplier_id order_date
500125 10000 2013/08/12
500126 10001 2013/08/13
500127 10004 2013/08/14
If we run the SQL statement (that contains a FULL OUTER JOIN) below:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
FULL OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Our result set would look like this:
48. supplier_id supplier_name order_date
10000 IBM 2013/08/12
10001 Hewlett Packard 2013/08/13
10002 Microsoft <null>
10003 NVIDIA <null>
<null> <null> 2013/08/14
The rows for Microsoft and NVIDIA would be included because a FULL OUTER JOIN was
used. However, you will notice that the order_date field for those records contains a <null>
value.
The row for supplier_id 10004 would be also included because a FULL OUTER JOIN was used.
However, you will notice that the supplier_id and supplier_name field for those records contain a
<null> value.
OLD SYNTAX
As a final note, it is worth mentioning that the FULL OUTER JOIN example above could not
have been written in the old syntax without using a UNION query.
SQL: ALIASES
Learn how to use SQL ALIASES (temporary names for columns or tables) with syntax and
examples.
DESCRIPTION
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).
SYNTAX
The syntax to ALIAS A COLUMN in SQL is:
49. column_name AS alias_name
OR
The syntax to ALIAS A TABLE in SQL is:
table_name alias_name
PARAMETERS OR ARGUMENTS
column_name is the original name of the column that you wish to alias.
table_name is the original name of the table that you wish to alias.
alias_name is the temporary name to assign.
NOTE
If the alias_name contains spaces, you must enclose the alias_name in quotes.
It is acceptable to use spaces when you are aliasing a column name. However, it is not generally
good practice to use spaces when you are aliasing a table name.
The alias_name is only valid within the scope of the SQL statement.
EXAMPLE - ALIAS A COLUMN
Generally, aliases are used to make the column headings in your result set easier to read. For
example, when using the COUNT function, you might alias the result of the COUNT function.
For example:
SELECT department, COUNT(*) AS TOTAL
FROM employees
GROUP BY department;
In this example, we've aliased the COUNT(*) field as TOTAL. As a result, TOTAL will display
as the heading for the second column when the result set is returned. Because our alias_name did
not include any spaces, we are not required to enclose the alias_name in quotes.
However, it would have been perfectly acceptable to write this example using quotes as follows:
SELECT department, COUNT(*) AS "TOTAL"
50. FROM employees
GROUP BY department;
Next, let's look at an example where we are required to enclose the alias_name in quotes.
For example:
SELECT department, COUNT(*) AS "TOTAL EMPLOYEES"
FROM employees
GROUP BY department;
In this example, we've aliased the COUNT(*) field as "TOTAL EMPLOYEES". Since there are
spaces in this alias_name, "TOTAL EMPLOYEES" must be enclosed in quotes.
EXAMPLE - ALIAS A TABLE
When you create an alias on a table, it is either because you plan to list the same table name
more than once in the FROM clause (ie: self join), or you want to shorten the table name to make
the SQL statement shorter and easier to read.
Let's look at an example of how to alias a table name.
For example:
SELECT s.supplier_id, s.supplier_name, order_details.order_date
FROM suppliers s
INNER JOIN order_details
ON s.supplier_id = order_details.supplier_id
WHERE s.supplier_id > 5000;
In this example, we've created an alias for the suppliers table called s. Now within this SQL
statement, we can refer to the suppliers table as s.
When creating table aliases, it is not necessary to create aliases for all of the tables listed in the
FROM clause. You can choose to create aliases on any or all of the tables.
For example, we could modify our example above and create an alias for the order_details table
as well.
SELECT s.supplier_id, s.supplier_name, od.order_date
FROM suppliers s
51. INNER JOIN order_details od
ON s.supplier_id = od.supplier_id
WHERE s.supplier_id > 5000;
Now we have an alias for order_details table called od as well as the alias for the suppliers table
called s.
SQL: DISTINCT CLAUSE
Learn how to use the SQL DISTINCT clause with syntax and examples.
DESCRIPTION
The SQL DISTINCT clause is used to remove duplicates from the result set of a SELECT
statement.
SYNTAX
The syntax for the SQL DISTINCT clause is:
SELECT DISTINCT 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.
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.
52. EXAMPLE - WITH SINGLE FIELD
Let's look at the simplest SQL DISTINCT query example. We can use the SQL DISTINCT
clause to return a single field that removes the duplicates from the result set.
For example:
SELECT DISTINCT city
FROM suppliers;
This SQL DISTINCT example would return all unique city values from the suppliers table.
EXAMPLE - WITH MULTIPLE FIELDS
Let's look at how you might use the SQL DISTINCT clause to remove duplicates from more
than one field in your SQL SELECT statement.
For example:
SELECT DISTINCT city, state
FROM suppliers;
This SQL DISTINCT clause example would return each unique city and state combination. In
this case, the DISTINCT applies to each field listed after the DISTINCT keyword.
SQL: WHERE CLAUSE
Learn how to use the SQL WHERE clause with syntax and examples.
DESCRIPTION
The SQL WHERE clause is used to filter the results and apply conditions in a SELECT,
INSERT, UPDATE, or DELETE statement.
SYNTAX
The syntax for the SQL WHERE Clause is:
WHERE conditions;
53. PARAMETERS OR ARGUMENTS
conditions are conditions that must be met for records to be selected.
EXAMPLE - WITH SINGLE CONDITION
It is difficult to explain the syntax for the SQL WHERE clause, so let's look at some examples.
SELECT *
FROM suppliers
WHERE supplier_name = 'IBM';
In this SQL WHERE clause example, we've used the SQL WHERE clause to filter our results
from the suppliers table. The SQL statement above would return all rows from the suppliers table
where the supplier_name is IBM. Because the * is used in the select, all fields from the suppliers
table would appear in the result set.
EXAMPLE - USING AND CONDITION
SELECT *
FROM suppliers
WHERE supplier_city = 'Chicago'
AND supplier_id > 1000;
This SQL WHERE clause example uses the WHERE clause to define multiple conditions. In this
case, this SQL statement uses the AND Condition to return all suppliers that are located in
Chicago and whose supplier_id is greater than 1000.
EXAMPLE - USING OR CONDITION
SELECT supplier_id
FROM suppliers
WHERE supplier_name = 'IBM'
OR supplier_name = 'Apple';
54. This SQL WHERE clause example uses the WHERE clause to define multiple conditions, but
instead of using the AND Condition, it uses the OR Condition. In this case, this SQL statement
would return all supplier_id values where the supplier_name is IBM or Apple.
EXAMPLE - COMBINING AND & OR CONDITIONS
SELECT *
FROM suppliers
WHERE (city = 'New York' AND name = 'IBM')
OR (ranking >= 10);
This SQL WHERE clause example uses the WHERE clause to define multiple conditions, but it
combines the AND Condition and the OR Condition. This example would return all suppliers
that reside in New York whose name is IBM and all suppliers whose ranking is greater than or
equal to 10.
The brackets determine the order that the AND and OR conditions are evaluated. Just like you
learned in the order of operations in Math class!
EXAMPLE - JOINING TABLES
SELECT suppliers.suppler_name, orders.order_id
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
WHERE suppliers.supplier_city = 'Atlantic City';
This SQL WHERE clause example uses the SQL WHERE clause to join multiple tables
together in a single SQL statement. This SQL statement would return all supplier names and
order_ids where there is a matching record in the suppliers and orders tables based
on supplier_id, and where thesupplier_city is Atlantic City.
Learn more about SQL joins.
SQL: ORDER BY CLAUSE
55. Learn how to use the SQL ORDER BY clause with syntax and examples.
DESCRIPTION
The SQL ORDER BY clause is used to sort the records in the result set for a SELECT
statement.
SYNTAX
The syntax for the SQL ORDER BY clause is:
SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression [ ASC | DESC ];
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.
ASC is optional. It sorts the result set in ascending order by expression (default, if no modifier is
provider).
DESC is optional. It sorts the result set in descending order by expression.
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 (which 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.
56. 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.
57. 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.
SQL: GROUP BY CLAUSE
Learn how to use the SQL GROUP BY clause with syntax and examples.
58. DESCRIPTION
The SQL GROUP BY clause can be used in a SELECT statement to collect data across
multiple records and group the results by one or more columns.
SYNTAX
The syntax for the SQL GROUP BY clause is:
SELECT expression1, expression2, ... expression_n,
aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;
PARAMETERS OR ARGUMENTS
expression1, expression2, ... expression_n are expressions that are not encapsulated within an
aggregate function and must be included in the GROUP BY Clause.
aggregate_function can be a function such as SUM function, COUNT function, MIN function,
or MAX function.
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 - USING SUM FUNCTION
Let's look at a SQL GROUP BY query example that uses the SQL SUM function.
This GROUP BY example uses the SUM function to return the name of the department and the
total sales (for the department).
SELECT department, SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department;
59. Because you have listed one column (the department field) in your SQL SELECT statement that
is not encapsulated in the SUM function, you must use the GROUP BY Clause.
The department 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 SQL COUNT function.
This GROUP BY example uses the COUNT function to return the department and the number of
employees (in the department) that make over $25,000 / year.
SELECT department, COUNT(*) AS "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department;
EXAMPLE - USING MIN FUNCTION
Let's next look at how we could use the GROUP BY clause with the SQL 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 SQL 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
60. GROUP BY department;
SQL: HAVING CLAUSE
Learn how to use the SQL HAVING clause with syntax and examples.
DESCRIPTION
The SQL 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
The syntax for the SQL HAVING Clause is:
SELECT expression1, expression2, ... expression_n,
aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n
HAVING condition;
PARAMETERS OR ARGUMENTS
aggregate_function can be a function such as SQL SUM function, SQL COUNT
function, SQL MIN function, or SQL MAX function.
expression1, expression2, ... expression_n are expressions that are not encapsulated within an
aggregate function and must be included in the GROUP BY Clause.
condition is the condition that is used 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 a SQL HAVING clause example that uses the SQL SUM function.
61. You could also use the SQL SUM function to return the name of the department and the total
sales (in the associated department). The SQL HAVING clause will filter the results so that only
departments with sales greater than $1000 will be returned.
SELECT department, SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department
HAVING SUM(sales) > 1000;
EXAMPLE - USING COUNT FUNCTION
Let's look at how we could use the HAVING clause with the SQL COUNT function.
You could use the SQL COUNT function to return the name of the department and the number
of employees (in the associated department) that make over $25,000 / year. The SQL 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 > 25000
GROUP BY department
HAVING COUNT(*) > 10;
EXAMPLE - USING MIN FUNCTION
Let's next look at how we could use the HAVING clause with the SQL MIN function.
You could also use the SQL MIN function to return the name of each department and the
minimum salary in the department. The SQL HAVING clause will return only those departments
where the minimum salary is greater than $35,000.
SELECT department, MIN(salary) AS "Lowest salary"
FROM employees
62. GROUP BY department
HAVING MIN(salary) > 35000;
EXAMPLE - USING MAX FUNCTION
Finally, let's look at how we could use the HAVING clause with the SQL MAX function.
For example, you could also use the SQL MAX function to return the name of each department
and the maximum salary in the department. The SQL HAVING clause will return only those
departments whose maximum salary is less than $50,000.
SELECT department, MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department
HAVING MAX(salary) < 50000;
SQL: COUNT FUNCTION
Learn how to use the SQL COUNT function with syntax, examples, and practice exercises.
DESCRIPTION
The SQL COUNT function is used to count the number of rows returned in a SELECT
statement.
SYNTAX
The syntax for the SQL COUNT function is:
SELECT COUNT(expression)
FROM tables
WHERE conditions;
PARAMETERS OR ARGUMENTS
expression can be a numeric field or formula.
63. ONLY INCLUDES NOT NULL VALUES
Not everyone realizes this, but the SQL COUNT function will only include the records in the
count where the value ofexpression in COUNT(expression) is NOT NULL.
When expression contains a NULL value, it is not included in the COUNT calculations.
Let's look at a SQL COUNT function example that demonstrates how NULL values are
evaluated by the COUNT function.
For example, if you have the following table called suppliers:
supplier_id supplier_name state
1 IBM CA
2 Microsoft
3 NVIDIA
And if you ran the following SQL SELECT statement that uses the SQL COUNT function:
SELECT COUNT(supplier_id)
FROM suppliers;
This SQL COUNT example will return 3 since all supplier_id values in the query's result set are
NOT NULL.
However, if you ran the next SQL SELECT statement that uses the SQL COUNT function:
SELECT COUNT(state)
FROM suppliers;
This SQL COUNT example will only return 1, since only one state value in the query's result set
is NOT NULL. That would be the first row where the state = 'CA'. It is the only row that is
included in the COUNT function calculation.
EXAMPLE - WITH SINGLE EXPRESSION
64. The simplest way to use the SQL COUNT function would be to return a single field that returns
the COUNT of something.
For example, you might wish to know how many employees have a salary that is above $25,000
/ year.
SELECT COUNT(*) AS "Number of employees"
FROM employees
WHERE salary > 25000;
In this SQL COUNT function example, we've aliased the COUNT(*) expression as "Number of
employees". As a result, "Number of employees" will display as the field name when the result
set is returned.
EXAMPLE - USING SQL DISTINCT CLAUSE
You can use the SQL DISTINCT clause within the SQL COUNT function.
For example, the SQL statement below returns the number of unique departments where at least
one employee makes over $25,000 / year.
SELECT COUNT(DISTINCT department) AS "Unique departments"
FROM employees
WHERE salary > 25000;
Again, the COUNT(DISTINCT department) field is aliased as "Unique departments". This is the
field name that will display in the result set.
EXAMPLE - USING SQL GROUP BY CLAUSE
In some cases, you will be required to use the SQL GROUP BY clause with the SQL COUNT
function.
For example, you could use the SQL COUNT function to return the name of the department and
the number of employees (in the associated department) that make over $25,000 / year.
SELECT department, COUNT(*) AS "Number of employees"
FROM employees
65. WHERE salary > 25000
GROUP BY department;
Because you have listed one column in your SQL SELECT statement that is not encapsulated
in the SQL COUNT function, you must use the SQL GROUP BY clause. The department field
must, therefore, be listed in the GROUP BY section.
TIP: PERFORMANCE TUNING WITH SQL COUNT
Since the SQL COUNT function will return the same results regardless of what NOT NULL
field(s) you include as the SQL COUNT function parameters (ie: within the brackets), you can
change the syntax of the SQL COUNT function to COUNT(1) to get better performance as the
database engine will not have to fetch back the data fields.
For example, based on the example above, the following syntax would result in better
performance:
SELECT department, COUNT(1) AS "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department;
Now, the SQL COUNT function does not need to retrieve all fields from the employees table as
it had to when you used the COUNT(*) syntax. It will merely retrieve the numeric value of 1 for
each record that meets your criteria.
PRACTICE EXERCISE #1:
Based on the employees table populated with the following data, count the number of employees
whose salary is over $55,000 per year.
CREATE TABLE employees
( employee_number number(10) not null,
employee_name varchar2(50) not null,
salary number(6),
66. CONSTRAINT employees_pk PRIMARY KEY (employee_number)
);
INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1001, 'John Smith', 62000);
INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1002, 'Jane Anderson', 57500);
INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1003, 'Brad Everest', 71000);
INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1004, 'Jack Horvath', 42000);
SOLUTION FOR PRACTICE EXERCISE #1:
Although inefficient in terms of performance, the following SQL SELECT statement would
return the number of employees whose salary is over $55,000 per year.
SELECT COUNT(*) AS "Number of employees"
FROM employees
WHERE salary > 55000;
It would return the following result set:
Number of employees
67. 3
A more efficient implementation of the same solution would be the following SQL SELECT
statement:
SELECT COUNT(1) AS "Number of employees"
FROM employees
WHERE salary > 55000;
Now, the SQL COUNT function does not need to retrieve all of the fields from the table (ie:
employee_number, employee_name, and salary), but rather whenever the condition is met, it will
retrieve the numeric value of 1. Thus, increasing the performance of the SQL statement.
PRACTICE EXERCISE #2:
Based on the suppliers table populated with the following data, count the number of
distinct cities in the suppliers 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)
68. 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');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5005, 'NVIDIA', 'LA');
SOLUTION FOR PRACTICE EXERCISE #2:
The following SQL SELECT statement would return the number of distinct cities in
the suppliers table:
SELECT COUNT(DISTINCT city) AS "Distinct Cities"
FROM suppliers;
It would return the following result set:
Distinct Cities
4
PRACTICE EXERCISE #3:
Based on the customers table populated with the following data, count the number of
distinct cities for each customer_name in the customers table:
CREATE TABLE customers
69. ( 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', 'New York');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7002, 'IBM', 'Chicago');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7003, 'Red Hat', 'Detroit');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7004, 'Red Hat', 'New York');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7005, 'Red Hat', 'San Francisco');
INSERT INTO customers (customer_id, customer_name, city)
70. VALUES (7006, 'NVIDIA', 'New York');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7007, 'NVIDIA', 'LA');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7008, 'NVIDIA', 'LA');
SOLUTION FOR PRACTICE EXERCISE #3:
The following SQL SELECT statement would return the number of distinct cities for
each customer_name in the customers table:
SELECT customer_name, COUNT(DISTINCT city) AS "Distinct Cities"
FROM customers
GROUP BY customer_name;
It would return the following result set:
CUSTOMER_NAME Distinct Cities
IBM 1
Microsoft 1
NVIDIA 2
Red Hat 3
71. SQL: SUM FUNCTION
Learn how to use the SQL SUM function with syntax and examples.
DESCRIPTION
The SQL SUM function is used to return the sum of an expression in a SELECT statement.
SYNTAX
The syntax for the SQL SUM function is:
SELECT SUM(expression)
FROM tables
WHERE conditions;
PARAMETERS OR ARGUMENTS
expression can be a numeric field or formula.
EXAMPLE - WITH SINGLE EXPRESSION
For example, you might wish to know how the combined total salary of all employees whose
salary is above $25,000 / year.
SELECT SUM(salary) AS "Total Salary"
FROM employees
WHERE salary > 25000;
In this SQL SUM Function example, we've aliased the SUM(salary) expression as "Total
Salary". As a result, "Total Salary" will display as the field name when the result set is returned.
EXAMPLE - USING SQL DISTINCT
You can use the SQL DISTINCT clause within the SQL SUM function. For example, the SQL
SELECT statement below returns the combined total salary of unique salary values where the
salary is above $25,000 / year.
SELECT SUM(DISTINCT salary) AS "Total Salary"
72. FROM employees
WHERE salary > 25000;
If there were two salaries of $30,000/year, only one of these values would be used in the SQL
SUM function.
EXAMPLE - USING FORMULA
The expression contained within the SQL SUM function does not need to be a single field. You
could also use a formula. For example, you might want the net income for a business. Net
Income is calculated as total income less total expenses.
SELECT SUM(income - expenses) AS "Net Income"
FROM gl_transactions;
You might also want to perform a mathematical operation within the SQL SUM function. For
example, you might determine total commission as 10% of total sales.
SELECT SUM(sales * 0.10) AS "Commission"
FROM order_details;
EXAMPLE - USING SQL GROUP BY
In some cases, you will be required to use the SQL GROUP BY clause with the SQL SUM
function.
For example, you could also use the SQL SUM function to return the name of the department
and the total sales (in the associated department).
SELECT department, SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SQL SELECT statement that is not encapsulated
in the SQL SUM function, you must use the SQL GROUP BY clause. The department field
must, therefore, be listed in the SQL GROUP BY section.
73. SQL: MIN FUNCTION
Learn how to use the SQL MIN function with syntax and examples.
DESCRIPTION
The SQL MIN function is used to return the minimum value of an expression in a SELECT
statement.
SYNTAX
The syntax for the SQL MIN function is:
SELECT MIN(expression)
FROM tables
WHERE conditions;
PARAMETERS OR ARGUMENTS
expression can be a numeric field or formula.
EXAMPLE - WITH SINGLE EXPRESSION
The simplest way to use the SQL MIN function would be to return a single field that calculates
the MIN value.
For example, you might wish to know the minimum salary of all employees.
SELECT MIN(salary) AS "Lowest salary"
FROM employees;
In this SQL MIN function example, we've aliased the MIN(salary) field as "Lowest salary". As a
result, "Lowest salary" will display as the field name when the result set is returned.
EXAMPLE - USING SQL GROUP BY
In some cases, you will be required to use the SQL GROUP BY clause with the SQL MIN
function.
74. For example, you could also use the SQL 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;
Because you have listed one column in your SQL SELECT statement that is not encapsulated
in the SQL MIN function, you must use the SQL GROUP BY clause. The department field
must, therefore, be listed in the GROUP BY section.
SQL: MAX FUNCTION
Learn how to use the SQL MAX function with syntax and examples.
DESCRIPTION
The SQL MAX function is used to return the maximum value of an expression in a SELECT
statement.
SYNTAX
The syntax for the SQL MAX function is:
SELECT MAX(expression)
FROM tables
WHERE conditions;
PARAMETERS OR ARGUMENTS
expression can be a numeric field or formula.
EXAMPLE - WITH SINGLE EXPRESSION
The simplest way to use the SQL MAX function would be to return a single field that calculates
the MAX value.
For example, you might wish to know the maximum salary of all employees.
75. SELECT MAX(salary) AS "Highest salary"
FROM employees;
In this SQL MAX function example, we've aliased the MAX(salary) field as "Highest salary".
As a result, "Highest salary" will display as the field name when the result set is returned.
EXAMPLE - USING SQL GROUP BY CLAUSE
In some cases, you will be required to use the SQL GROUP BY clause with the SQL MAX
function.
For example, you could also use the SQL 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;
Because you have listed one column in your SQL SELECT statement that is not encapsulated
in the MAX function, you must use the SQL GROUP BY clause. The department field must,
therefore, be listed in the GROUP BY section.
FREQUENTLY ASKED QUESTIONS
Question: I'm trying to pull some info out of a table. To simplify, let's say the table
(report_history) has 4 columns: user_name, report_job_id, report_name, and report_run_date.
Each time a report is run in Oracle, a record is written to this table noting the above info. What I
am trying to do is pull from this table when the last time each distinct report was run and who ran
it last.
My initial query:
SELECT report_name, MAX(report_run_date)
FROM report_history
GROUP BY report_name
runs fine. However, it does not provide the name of the user who ran the report.
76. Adding user_name to both the select list and to the group by clause returns multiple lines for
each report; the results show the last time each person ran each report in question. (i.e. User1 ran
Report 1 on 01-JUL-03, User2 ran Report1 on 01-AUG-03). I don't want that....I just want to
know who ran a particular report the last time it was run.
Any suggestions?
Answer: This is where things get a bit complicated. The SQL SELECT statement below will
return the results that you want:
SELECT rh.user_name, rh.report_name, rh.report_run_date
FROM report_history rh,
(SELECT MAX(report_run_date) AS maxdate, report_name
FROM report_history
GROUP BY report_name) maxresults
WHERE rh.report_name = maxresults.report_name
AND rh.report_run_date= maxresults.maxdate;
Let's take a few moments to explain what we've done.
First, we've aliased the first instance of the report_history table as rh.
Second, we've included two components in our FROM clause. The first is the table called
report_history (aliased as rh). The second is a select statement:
(SELECT MAX(report_run_date) AS maxdate, report_name
FROM report_history
GROUP BY report_name) maxresults
We've aliased the max(report_run_date) as maxdate and we've aliased the entire result set
as maxresults.
Now, that we've created this select statement within our FROM clause, Oracle will let us join
these results against our original report_history table. So we've joined the report_name and
report_run_date fields between the tables called rh and maxresults. This allows us to retrieve the
report_name, max(report_run_date) as well as the user_name.
77. Question: I need help with a SQL query. I have a table in Oracle called orders which has the
following fields: order_no, customer, and amount.
I need a query that will return the customer who has ordered the highest total amount.
Answer: The following SQL should return the customer with the highest total amount in the
orders table.
SELECT query1.*
FROM (SELECT customer, SUM(orders.amount) AS total_amt
FROM orders
GROUP BY orders.customer) query1,
(SELECT MAX(query2.total_amt) AS highest_amt
FROM (SELECT customer, SUM(orders.amount) AS total_amt
FROM orders
GROUP BY orders.customer) query2) query3
WHERE query1.total_amt = query3.highest_amt;
This SQL SELECT statement will summarize the total orders for each customer and then return
the customer with the highest total orders. This syntax is optimized for Oracle and may not work
for other database technologies.
Question: I'm trying to retrieve some info from an Oracle database. I've got a table
named Scoring with two fields - Name and Score. What I want to get is the highest score from
the table and the name of the player.
Answer: The following SQL SELECT statement should work:
SELECT Name, Score
78. FROM Scoring
WHERE Score = (SELECT MAX(Score) FROM Scoring);
Question: I need help in a SQL query. I have a table in Oracle called cust_order which has the
following fields: OrderNo, Customer_id, Order_Date, and Amount.
I would like to find the customer_id, who has Highest order count.
I tried with following query.
SELECT MAX(COUNT(*))
FROM CUST_ORDER
GROUP BY CUSTOMER_ID;
This gives me the max Count, But, I can't get the CUSTOMER_ID. Can you help me please?
Answer: The following SQL SELECT statement should return the customer with the highest
order count in the cust_order table.
SELECT query1.*
FROM (SELECT Customer_id, Count(*) AS order_count
FROM cust_order
GROUP BY cust_order.Customer_id) query1,
(SELECT max(query2.order_count) AS highest_count
FROM (SELECT Customer_id, Count(*) AS order_count
FROM cust_order
GROUP BY cust_order.Customer_id) query2) query3
WHERE query1.order_count = query3.highest_count;
79. This SQL SELECT statement will summarize the total orders for each customer and then return
the customer with the highest order count. This syntax is optimized for Oracle and may not work
for other database technologies.
Question: I'm trying to get the employee with the maximum salary from department 30, but I
need to display the employee's full information. I've tried the following query, but it returns the
result from both department 30 and 80:
SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary)
FROM employees
WHERE department_id=30);
Answer: The SQL SELECT statement that you have written will first determine the maximum
salary for department 30, but then you select all employees that have this salary. In your case,
you must have 2 employees (one in department 30 and another in department 80) that have this
same salary. You need to make sure that you are refining your query results to only return
employees from department 30.
Try using this SQL SELECT statement:
SELECT *
FROM employees
WHERE department_id=30
AND salary = (SELECT MAX(salary)
FROM employees
WHERE department_id=30);
This will return the employee information for only the employee in department 30 that has the
highest salary.
80. SQL: AVG FUNCTION
Learn how to use the SQL AVG function with syntax and examples.
DESCRIPTION
The SQL AVG function is used to return the average of an expression in a SELECT statement.
SYNTAX
The syntax for the SQL AVG function is:
SELECT AVG(expression)
FROM tables
WHERE conditions;
PARAMETERS OR ARGUMENTS
expression can be a numeric field or formula.
EXAMPLE - WITH SINGLE EXPRESSION
For example, you might wish to know how the average cost of all products that are in the
Clothing category.
SELECT AVG(cost) AS "Average Cost"
FROM products
WHERE category = 'Clothing';
In this SQL AVG Function example, we've aliased the AVG(cost) expression as "Average
Cost". As a result, "Average Cost" will display as the field name when the result set is returned.
EXAMPLE - USING SQL DISTINCT
You can use the SQL DISTINCT clause within the AVG function. For example, the SELECT
statement below returns the combined average cost of unique cost values where the category is
Clothing.
SELECT AVG(DISTINCT cost) AS "Average Cost"
81. FROM products
WHERE category = 'Clothing';
If there were two cost values of $25, only one of these values would be used in the AVG
function calculation.
EXAMPLE - USING FORMULA
The expression contained within the AVG function does not need to be a single field. You could
also use a formula. For example, you might want the average profit for a product. Average profit
is calculated as sale_price less cost.
SELECT AVG(sale_price - cost) AS "Average Profit"
FROM products;
You might also want to perform a mathematical operation within the AVG function. For
example, you might determine the average commission as 10% of sale_price.
SELECT AVG(sale_price * 0.10) AS "Average Commission"
FROM products;
EXAMPLE - USING SQL GROUP BY
In some cases, you will be required to use the SQL GROUP BY clause with the AVG function.
For example, you could also use the AVG function to return the name of the department and the
average sales (in the associated department).
SELECT department, AVG(sales) AS "Average Sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the
AVG function, you must use the GROUP BY clause. The department field must, therefore, be
listed in the GROUP BY section.
SQL: AND CONDITION
82. Learn how to use the SQL AND condition with syntax and examples.
DESCRIPTION
The SQL AND Condition (also known as the AND Operator) is used to test for two or more
conditions in a SELECT, INSERT, UPDATE, or DELETE statement.
SYNTAX
The syntax for the SQL AND Condition is:
WHERE condition1
AND condition2
...
AND condition_n;
PARAMETERS OR ARGUMENTS
condition1, condition2, condition_n are all of the conditions that must be met for the records to
be selected.
NOTE
The SQL AND condition allows you to test 2 or more conditions.
The SQL AND condition requires that all of the conditions
(ie: condition1, condition2, condition_n) be must be met for the record to be included in the
result set.
EXAMPLE - WITH SELECT STATEMENT
The first SQL AND condition query involves a SELECT statement with 2 conditions.
For example:
SELECT *
FROM suppliers
WHERE city = 'New York'
83. AND ranking > 5;
This SQL AND example would return all suppliers that reside in New York and have a ranking
greater than 5. Because the * is used in the SQL SELECT statement, all fields from the suppliers
table would appear in the result set.
EXAMPLE - JOINING TABLES
Our next AND condition example demonstrates how the SQL AND condition can be used
to join multiple tables in a SQL statement.
For example:
SELECT orders.order_id, suppliers.supplier_name
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id
AND suppliers.supplier_name = 'IBM';
Though the above SQL works just fine, you would more traditionally write this SQL as follows
using a proper INNER JOIN.
For example:
SELECT orders.order_id, suppliers.supplier_name
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
WHERE suppliers.supplier_name = 'IBM';
This SQL AND condition example would return all rows where the supplier_name is IBM. And
the suppliers and orders tables are joined on supplier_id. You will notice that all of the fields are
prefixed with the table names (ie: orders.order_id). This is required to eliminate any ambiguity as
to which field is being referenced; as the same field name can exist in both the suppliers and
orders tables.
84. In this case, the result set would only display the order_id and supplier_name fields (as listed in
the first part of the select statement.).
EXAMPLE - WITH INSERT STATEMENT
This next AND condition example demonstrates how the SQL AND condition can be used in
the INSERT statement.
For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE customer_name = 'IBM'
AND employees <= 1000;
This SQL AND condition example would insert into the suppliers table, all account_no and
name records from the customers table whose customer_name is IBM and have less than or
equal to 1000 employees.
EXAMPLE - WITH UPDATE STATEMENT
This AND condition example shows how the AND condition can be used in the UPDATE
statement.
For example:
UPDATE suppliers
SET supplier_name = 'HP'
WHERE supplier_name = 'IBM'
AND offices = 8;
This SQL AND condition example would update all supplier_name values in the suppliers table
to HP where the supplier_name was IBM with 8 offices.
85. EXAMPLE - WITH DELETE STATEMENT
Finally, this last AND condition example demonstrates how the SQL AND condition can be used
in the DELETE statement.
For example:
DELETE FROM suppliers
WHERE supplier_name = 'IBM'
AND product = 'PC computers';
This SQL AND condition example would delete all suppliers from the suppliers table whose
supplier_name was IBM and product was PC computers.
Learn more about joining tables in SQL.
SQL: OR CONDITION
Learn how to use the SQL OR condition with syntax and examples.
DESCRIPTION
The SQL OR Condition is used to test multiple conditions, where the records are returned when
any one of the conditions are met. It can be used in a SELECT, INSERT, UPDATE, or DELETE
statement.
SYNTAX
The syntax for the SQL OR Condition is:
WHERE condition1
OR condition2
...
OR condition_n;
PARAMETERS OR ARGUMENTS
86. condition1, condition2, condition_n are any of the conditions that must be met for the records to
be selected.
NOTE
The SQL OR condition allows you to test 2 or more conditions.
The SQL OR condition requires that any of the conditions
(ie: condition1, condition2, condition_n) be must be met for the record to be included in the
result set.
EXAMPLE - WITH SELECT STATEMENT
The first SQL OR condition example that we'll take a look at involves a SQL SELECT
statement with 2 conditions:
SELECT *
FROM suppliers
WHERE city = 'New York'
OR available_products >= 250;
This SQL OR condition example would return all suppliers that reside in either New York or
have available_products greater than or equal to 250. Because the * is used in the SELECT
statement, all fields from the suppliers table would appear in the result set.
EXAMPLE - WITH SELECT STATEMENT (3 CONDITIONS)
The next SQL OR example takes a look at a SQL SELECT statement with 3 conditions. If any
of these conditions is met, the record will be included in the result set.
SELECT supplier_id
FROM suppliers
WHERE supplier_name = 'IBM'
OR city = 'New York'
OR offices > 5;
This SQL OR condition example would return all supplier_id values where the supplier's name is
either IBM, city is New York, or offices is greater than 5.
87. EXAMPLE - WITH INSERT STATEMENT
The SQL OR condition can be used in the SQL INSERT statement.
For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city = 'New York'
OR city = 'Newark';
This SQL OR condition example would insert into the suppliers table, all account_no and name
records from the customers table that reside in either New York or Newark.
EXAMPLE - WITH UPDATE STATEMENT
The SQL OR condition can be used in the SQL UPDATE statement.
For example:
UPDATE suppliers
SET supplier_name = 'HP'
WHERE supplier_name = 'IBM'
OR available_products > 36;
This SQL OR condition example would update all supplier_name values in the suppliers table to
HP where the supplier_name was IBM or its available_products was greater than 36.
EXAMPLE - WITH DELETE STATEMENT
The SQL OR condition can be used in the SQL DELETE statement.
For example:
88. DELETE FROM suppliers
WHERE supplier_name = 'IBM'
OR employees <= 100;
This SQL OR condition example would delete all suppliers from the suppliers table whose
supplier_name was IBM or its employees was less than or equal to 100.
SQL: AND & OR CONDITIONS
This SQL tutorial explains how to use the AND condition and the OR condition together in a
single query with syntax and examples.
DESCRIPTION
The SQL AND Condition and OR Condition can be combined to test for multiple conditions in
a SELECT, INSERT, UPDATE, or DELETE statement.
When combining these conditions, it is important to use brackets so that the database knows
what order to evaluate each condition. (Just like when you were learning the order of operations
in Math class!)
SYNTAX
The syntax for the SQL AND Condition is:
WHERE condition1
AND condition2
...
OR condition_n;
PARAMETERS OR ARGUMENTS
condition1, condition2, condition_n are the conditions that are evaluated to determine if the
records will be selected.
NOTE
The SQL AND & OR conditions allows you to test multiple conditions.
89. Don't forget the order of operation brackets!
EXAMPLE - WITH SELECT STATEMENT
Let's look at an example that combines the AND condition and OR condition in a SELECT
query.
For example:
SELECT *
FROM suppliers
WHERE (city = 'New York' AND name = 'IBM')
OR (ranking >= 10);
This SQL SELECT example would return all suppliers that reside in New York whose name is
IBM and all suppliers whose ranking is greater than or equal to 10. The brackets determine the
order that the AND and OR conditions are evaluated. Just like you learned in the order of
operations in Math class!
The next example takes a look at a more complex statement.
For example:
SELECT supplier_id
FROM suppliers
WHERE (name = 'IBM')
OR (name = 'Hewlett Packard' AND city = 'Atlantic City')
OR (name = 'Gateway' AND status = 'Active' AND city = 'Burma');
This SQL SELECT statement would return all supplier_id values where the supplier's name is
IBM or the name is Hewlett Packard and the city is Atlantic City or the name is Gateway, the
status is Active, and the city is Burma.
EXAMPLE - WITH INSERT STATEMENT
This next example demonstrates how the SQL AND condition and SQL OR condition can be
combined in the INSERT statement.
90. For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, customer_name
FROM customers
WHERE (customer_name = 'IBM' OR customer_name = 'Apple')
AND employees > 15;
This SQL AND and OR condition example would insert into the suppliers table, all account_no
and customer_name records from the customers table whose customer_name is either IBM or
Apple and where the employees is greater than 15.
EXAMPLE - WITH UPDATE STATEMENT
This example shows how the AND and OR conditions can be used in the UPDATE statement.
For example:
UPDATE suppliers
SET supplier_name = 'HP'
WHERE supplier_name = 'IBM'
AND state = 'California';
This SQL AND & OR condition example would update all supplier_name values in the suppliers
table to HP where the supplier_name was IBM and resides in the state of California.
EXAMPLE - WITH DELETE STATEMENT
Finally, this last AND & OR condition example demonstrates how the AND and OR condition
can be used in the DELETE statement.
For example:
DELETE FROM suppliers
91. WHERE city = 'New York'
AND (product = 'PC computers' OR supplier_name = 'Dell');
This SQL AND and OR condition example would delete all suppliers from the suppliers table
whose city was New York and either the product was PC computers or the supplier name was
Dell.
SQL: LIKE CONDITION
Learn how to use the SQL LIKE condition (to perform pattern matching) with syntax,
examples, and practice exercises.
DESCRIPTION
The SQL LIKE condition allows you to use wildcards to perform pattern matching. The LIKE
condition is used in theWHERE clause of a SELECT, INSERT, UPDATE, or DELETE
statement.
SYNTAX
The syntax for the SQL LIKE Condition is:
expression LIKE pattern [ ESCAPE 'escape_character' ]
PARAMETERS OR ARGUMENTS
expression is a character expression such as a column or field.
pattern is a character expression that contains pattern matching. The patterns that you can choose
from are:
% allows you to match any string of any length (including zero length)
_ allows you to match on a single character
escape_character is optional. It allows you to test for literal instances of a wildcard character
such as % or _.
EXAMPLE - USING % WILDCARD (PERCENT SIGN WILDCARD)
The first SQL LIKE example that we will look at involves using the % wildcard (percent sign
wildcard).
92. Let's explain how the % wildcard works in the SQL LIKE condition. We want to find all of the
suppliers whose name begins with 'Hew'.
SELECT supplier_name
FROM suppliers
WHERE supplier_name LIKE 'Hew%';
You can also using the % wildcard multiple times within the same string. For example,
SELECT supplier_name
FROM suppliers
WHERE supplier_name LIKE '%bob%';
In this SQL LIKE condition example, we are looking for all suppliers whose name contains the
characters 'bob'.
EXAMPLE - USING _ WILDCARD (UNDERSCORE WILDCARD)
Next, let's explain how the _ wildcard (underscore wildcard) works in the SQL LIKE condition.
Remember that _ wildcard is looking for only one character.
For example:
SELECT last_name
FROM customers
WHERE last_name LIKE 'Sm_th';
This SQL LIKE condition example would return all customers whose last_name is 5 characters
long, where the first two characters is 'Sm' and the last two characters is 'th'. For example, it
could return customers whose last_name is 'Smith', 'Smyth', 'Smath', 'Smeth', etc.
Here is another example:
SELECT *
FROM suppliers
93. WHERE account_number LIKE '12317_';
You might find that you are looking for an account number, but you only have 5 of the 6 digits.
The example above, would retrieve potentially 10 records back (where the missing value could
equal anything from 0 to 9). For example, it could return suppliers whose account numbers are:
123170, 123171, 123172, 123173, 123174, 123175, 123176, 123177, 123178, 123179
EXAMPLE - USING THE NOT OPERATOR
Next, let's look at how you would use the SQL NOT Operator with wildcards.
Let's use the % wilcard with the NOT Operator. You could also use the SQL LIKE condition to
find suppliers whose name does not start with 'T'.
For example:
SELECT supplier_name
FROM suppliers
WHERE supplier_name NOT LIKE 'T%';
By placing the NOT Operator in front of the SQL LIKE condition, you are able to retrieve all
suppliers whose supplier_name does not start with 'T'.
EXAMPLE - USING ESCAPE CHARACTERS
It is important to understand how to "Escape Characters" when pattern matching. These
examples deal specifically with escaping characters in Oracle.
Let's say you wanted to search for a % or a _ character in the SQL LIKE condition. You can do
this using an Escape character.
Please note that you can only define an escape character as a single character (length of 1).
For example:
SELECT *
FROM suppliers
WHERE supplier_name LIKE '!%' escape '!';