Oracle Database Table Management Guide
Oracle Database Table Management Guide
CONTENTS
I. Introduction
II. Creating Tables
III. Insert Table
IV. Delete Table
V. Alter Table
VI. Select Table
VII. Update Table
VIII. Aliases
IX. Where Clause
X. Operators
XI. Order by
XII. Group by
XIII. Group Functions
XIV. Having
XV. Primary Key
XVI. Foreign Key
XVII. Joins
XVIII. Veiws
XIX. Indexes
XX. Roles
I. Introduction
Oracle database is a relational database management system. It is known as Oracle database,
OracleDB or simply Oracle. It is produced and marketed by Oracle Corporation.
Oracle database is the first database designed for enterprise grid computing. The enterprise grid
computing provides the most flexible and cost effective way to manage information and
applications.
Enterprise Edition: It is the most robust and secure edition. It offers all features, including
superior performance and security.
Standard Edition: It provides the base functionality for users that do not require Enterprise
Edition’s robust package.
Express Edition (XE): It is the lightweight, free and limited Windows and Linux edition.
Oracle Corporation is the largest software company in the field of database business. Its
relational database was the first to support SQL which has since become the industry standard.
Oracle database is one of the most trusted and widely used relational database engines. The
biggest rival of Oracle database is Microsoft’s SQL Server.
History of Oracle
Oracle was originally developed by Lawrence Ellison (Larry Ellision) and his two friends and
former co-worker in 1977. Oracle DB runs on the most major platforms like Windows, UNIX,
Linux and Mac OS.
In Oracle, CREATE TABLE statement is used to create a new table in the database.
To create a table, you have to name that table and define its columns and datatype for each
column.
Syntax:
Here we are creating a table named customers. This table doesn’t have any primary key.
o city: This is the third column created as a varchar2 datatype. It can contain null values.
A primary key is a single field or combination of fields that contains a unique record. It must be
filled. None of the field of primary key can contain a null value. A table can have only one
primary key.
In Oracle, INSERT statement is used to add a single record or multiple records into the table.
Parameters:
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.
4) source_table:
5) conditions:
Consider here the already created suppliers table. Add a new row where the value of supplier_id
is 23 and supplier_name is Flipkart.
This method is used for more complicated cases of insertion. In this method insertion is done by
SELECT statement. This method is used to insert multiple elements.
In this method, we insert values to the “suppliers” table from “customers” table. Both tables are
already created with their respective columns.
XX)....... seconds
You can even check the number of rows that you want to insert by following statement:
1. SELECT count(*)
2. FROM customers
3. WHERE age > 20;
The Oracle INSERT ALL statement is used to insert multiple rows with a single INSERT
statement. You can insert the rows into one table or multiple tables by using only one SQL
command.
Syntax
1. INSERT ALL
2. INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
3. INTO table_name(column1, column2, column_n) VALUES (expr1, expr2, expr_n)
4. INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
5. SELECT * FROM dual;
Parameters
1) table_name: it specifies the table in which you want to insert your records.
2) column1, column2, column_n: this specifies the columns in the table to insert values.
3) expr1, expr2, expr_n: this specifies the values to assign to the columns in the table.
This example specifies how to insert multiple records in one table. Here we insert three rows into
the “suppliers” table.
1. INSERT ALL
2. INTO suppliers (supplier_id, supplier_name) VALUES (20, ‘Google’)
3. INTO suppliers (supplier_id, supplier_name) VALUES (21, ‘Microsoft’)
4. INTO suppliers (supplier_id, supplier_name) VALUES (22, ‘Apple’)
5. SELECT * FROM dual;
Output
3 row(s) inserted.
0.02 seconds
The INSERT ALL statement can also be used to insert multiple rows into more than one table by
one command only.
In the following example, we are going to insert records into the both “suppliers” and
“customers” tables.
1. INSERT ALL
2. INTO suppliers (supplier_id, supplier_name) VALUES (30, ‘Google’)
3. INTO suppliers (supplier_id, supplier_name) VALUES (31, ‘Microsoft’)
4. INTO customers (age, name, address) VALUES (29, ‘Luca Warsi’, ‘New York’)
5. SELECT * FROM dual;
Output
3 row(s) inserted.
0.03 seconds
Here, total 3 rows are inserted, 2 rows are inserted into the suppliers table and one row into the
customers table.
In Oracle, DELETE statement is used to remove or delete a single record or multiple records
from a table.
Syntax
Parameters
2) conditions: It specifies the conditions that must met for the records to be deleted.
This statement will delete all records from the customer table where name is “Sohan”.
This statement will delete all records from the customers table where the last_name is “Maurya”
and the customer_id is greater than 2.
In Oracle, TRUNCATE TABLE statement is used to remove all records from a table. It works
same as DELETE statement but without specifying a WHERE clause. It is generally used when
you don?t have to worry about rolling back
Once a table is truncated, it can?t be rolled back. The TRUNCATE TABLE statement does not
affect any of the table?s indexes, triggers or dependencies.
Parameters
1) schema_name: This parameter specifies the name of the schema that the table belongs to. It is
optional.
Consider a table named “customers” and execute the following query to truncate this
Output
Table truncated.
1.11 seconds
Now check the customers table, you will find that there is no data available in that table. It is
equally similar to DELETE TABLE statement in Oracle.
Both the statements will remove the data from the “customers” table but the main difference is
that you can roll back the DELETE statement whereas you can’t roll back the TRUNCATE
TABLE statement.
Oracle DROP TABLE statement is used to remove or delete a table from the Oracle database.
Syntax
schema_name: It specifies the name of the schema that owns the table.
Table_name: It specifies the name of the table which you want to remove from the Oracle
database.
PURGE: It is also optional. If specified, the table and its dependent objects are placed in the
recycle bin and can?t be recovered.
This statement will drop the table called customers and issue a PURGE so that the space
associated with the customers table is released and the customers table is not placed in recycle
bin. So, it is not possible to recover that table if required.
In Oracle, ALTER TABLE statement specifies how to add, modify, drop or delete columns in a
table. It is also used to rename a table.
Syntax:
Example:
Consider that already existing table customers. Now, add a new column customer_age into the
table customers.
Syntax:
Example
Syntax:
Example:
Syntax:
Example:
Syntax:
Example:
Syntax:
Example:
Syntax:
Example:
The Oracle SELECT statement is used to retrieve data from one or more than one tables, object
tables, views, object views etc.
Syntax
1. SELECT expressions
2. FROM tables
3. WHERE conditions;
Parameters
2) Tables: This parameter specifies the tables that you want to retrieve records from. There must
be at least one table within the FROM clause.
Let’s take an example to select all fields from an already created table named customers
1. SELECT *
2. FROM customers;
Output
Output
Update statement is used to update rows in existing tables which is in your own schema or if
you have update privilege on them.
For example to raise the salary by Rs.500 of employee number 104. You can give the
following statement.
In the above statement if we did not give the where condition then all employees salary will
be raised by Rs. 500. That’s why always specify proper WHERE condition if don’t want to
update all employees.
For example We want to change the name of employee no 102 from ‘Sami’ to ‘Mohd Sami’
and to raise the salary by 10%. Then the statement will be.
Now to compute total which is sum of Maths,Phy and Chem and average.
Suppose we added the city column in the employee table and now we want to set this column
with corresponding city column in department table which is join to employee table on
deptno.
Let’s look at an UPDATE example that shows how to update more than one column in a table.
TIP: When you update multiple columns in an UPDATE statement, you need to comma separate
the column/value pairs in the SET clause.
In this UPDATE example, we have a table called suppliers with the following data:
Now let’s demonstrate how to use the UPDATE statement to update more than one column value
at once. Enter the following UPDATE statement:
UPDATE suppliers
SET supplier_id = 150,
supplier_name = ‘Apple’,
city = ‘Cupertino’
WHERE supplier_name = ‘Google’;
There will be 1 record updated. Select the data from the suppliers table again:
This UPDATE example would update the supplier_id to 150, the supplier_name to ‘Apple’
and city to ‘Cupertino’ where thesupplier_name is ‘Google’.
Let’s look at an UPDATE example that shows how to update a table with data from another
table.
In this UPDATE example, we have a table called products with the following data:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
product_id current_category
1 10
2 10
3 10
4 10
5 10
8 10
Now let’s update the summary_data table with values from the products table. Enter the
following UPDATE statement:
UPDATE summary_data
SET current_category = (SELECT category_id
FROM products
WHERE products.product_id = summary_data.product_id)
WHERE EXISTS (SELECT category_id
FROM products
WHERE products.product_id = summary_data.product_id);
There will be 5 records update. Select the data from the summary_data table again:
product_id current_category
1 50
2 50
3 50
4 50
5 75
8 10
This example would update the current_category field in the summary_data table with
the category_id from the products table where the product_id values match. The first 5 records
in the summary_data table have been updated.
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
OR
Parameters or Arguments
column_name
Table_name
Alias_name
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.
If you want to follow along with this tutorial, get the DDL to create the tables and the DML to
populate the data. Then try the examples in your own database!
Generally, aliases are used to make the column headings in your result set easier to read. Most
commonly, you will alias a column when using an aggregate function such as MIN, MAX, AVG,
SUM or COUNT in your query.
In this example, we have a table called employees with the following data:
Let’s demonstrate how to alias a column. Enter the following SQL statement:
There will be 2 records selected. These are the results that you should see:
dept_id total
500 2
501 2
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 thealias_name in quotes.
Now, let’s rewrite our query to include a space in the column alias:
There will be 2 records selected. These are the results that you should see:
500 2
501 2
In this example, we’ve aliased the COUNT(*) field as “total employees” so this will become the
heading for the second column in our result set. Since there are spaces in this column alias, “total
employees” must be enclosed in quotes in the SQL statement.
When you alias 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.
In this example, we have a table called products with the following data:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
category_id category_name
25 Deli
50 Produce
75 Bakery
125 Technology
Now let’s join these 2 tables and alias each of the table names. Enter the following SQL
statement:
There will be 5 records selected. These are the results that you should see:
product_name category_name
Banana Produce
Orange Produce
Apple Produce
Bread Bakery
In this example, we’ve created an alias for the products table and an alias for
the categories table. Now within this SQL statement, we can refer to the products table as p and
the categories table as c.
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.
The SQL WHERE clause is used to filter the results and apply conditions in a SELECT,
INSERT, UPDATE, or DELETE statement.
Syntax
WHERE conditions;
Parameters or Arguments
conditions
If you want to follow along with this tutorial, get the DDL to create the tables and the DML to
populate the data. Then try the examples in your own database!
It is difficult to explain the syntax for the SQL WHERE clause, so let’s start with an example
that uses the WHERE clause to apply 1 condition.
In this example, we have a table called suppliers with the following data:
SELECT *
FROM suppliers
WHERE state = ‘California’;
There will be 4 records selected. These are the results that you should see:
In this 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 state is California. Because the * is used in the select, all fields from
the suppliers table would appear in the result set.
You can use the AND condition in the WHERE clause to specify more than 1 condition that
must be met for the record to be selected. Let’s explore how to do this.
In this example, we have a table called customers with the following data:
SELECT *
FROM customers
WHERE favorite_website = ‘[Link]’
AND customer_id > 6000;
There will be 1 record selected. These are the results that you should see:
This example uses the WHERE clause to define multiple conditions. In this case, this SQL
statement uses the AND conditionto return all customers whose favorite_website is
[Link] and whose customer_id is greater than 6000.
You can use the OR condition in the WHERE clause to test multiple conditions where the record
is returned if any one of the conditions are met.
In this example, we have a table called products with the following data:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
SELECT *
FROM products
WHERE product_name = ‘Pear’
OR product_name = ‘Apple’;
There will be 2 records selected. These are the results that you should see:
1 Pear 50
4 Apple 50
This 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
records from the products table where the product_name is either Pear or Apple.
You can also combine the AND condition with the OR condition to test more complex
conditions.
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
SELECT *
FROM products
WHERE (product_id > 3 AND category_id = 75)
OR (product_name = ‘Pear’);
There will be 2 records selected. These are the results that you should see:
1 Pear 50
5 Bread 75
This example would return all products whose product_id is greater than 3 and category_id is 75
as well as all products whose product_name is Pear.
The parentheses determine the order that the AND and OR conditions are evaluated. Just like
you learned in the order of operations in Math class!
Comparison operators are used in the WHERE clause to determine which records to select. Here
is a list of the comparison operators that you can use in SQL:
= Equal
!= Not Equal
If you want to follow along with this tutorial, get the DDL to create the tables and the DML to
populate the data. Then try the examples in your own database!
In this example, we have a table called suppliers with the following data:
SELECT *
FROM suppliers
WHERE supplier_name = ‘Microsoft’;
There will be 1 record selected. These are the results that you should see:
In this example, the SELECT statement above would return all rows from the suppliers table
where the supplier_name is equal to Microsoft.
In SQL, there are two ways to test for inequality in a query. You can use either
the <> or != operator. Both will return the same results.
Enter the following SQL statement to test for inequality using the <> operator:
SELECT *
FROM suppliers
WHERE supplier_name <> ‘Microsoft’;
SELECT *
FROM suppliers
WHERE supplier_name != ‘Microsoft’;
There will be 8 records selected. These are the results you should see with either one of the SQL
statements:
In the example, both SELECT statements would return all rows from the suppliers table where
the supplier_name is not equal to Microsoft.
You can use the > operator in SQL to test for an expression greater than.
In this example, we have a table called customers with the following data:
SELECT *
FROM customers
WHERE customer_id > 6000;
There will be 3 records selected. These are the results that you should see:
In this example, the SELECT statement would return all rows from the customers table where
the customer_id is greater than 6000. A customer_id equal to 6000 would not be included in the
result set.
In SQL, you can use the >= operator to test for an expression greater than or equal to.
SELECT *
FROM customers
WHERE customer_id >= 6000;
There will be 4 records selected. These are the results that you should see:
In this example, the SELECT statement would return all rows from the customers table where
the customer_id is greater than or equal to 6000. In this case, the supplier_id equal to 6000
would be included in the result set.
You can use the < operator in SQL to test for an expression less than.
In this example, we have a table called products with the following data:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
SELECT *
FROM products
WHERE product_id < 5;
There will be 4 records selected. These are the results that you should see:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
In this example, the SELECT statement would return all rows from the products table where
the product_id is less than 5. Aproduct_id equal to 5 would not be included in the result set.
In SQL, you can use the <= operator to test for an expression less than or equal to.
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
SELECT *
FROM products
WHERE product_id <= 5;
There will be 5 records selected. These are the results that you should see:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
In this example, the SELECT statement would return all rows from the products table where
the product_id is less than or equal to 5. In this case, the product_id equal to 5 would be included
in the result set.
IN Condition
The SQL IN condition (sometimes called the IN operator) allows you to easily test if an
expression matches any value in a list of values. It is used to help reduce the need for
multiple OR conditions in a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax
Parameters or Arguments
expression
These are the values to test against expression. If any of these values matches expression,
then the IN condition will evaluate to true.
If you want to follow along with this tutorial, get the DDL to create the tables and the DML to
populate the data. Then try the examples in your own database!
The IN condition can be used with any data type in SQL. Let’s look at how to use the IN
condition with character (string) values.
In this example, we have a table called suppliers with the following data:
SELECT *
FROM suppliers
WHERE supplier_name IN (‘Microsoft’, ‘Oracle’, ‘Flowers Foods’);
There will be 3 records selected. These are the results that you should see:
This example would return all rows from the suppliers table where the supplier_name is either
Microsoft, Oracle or Flowers Foods. Because the * is used in the select, all fields from
the suppliers table would appear in the result set.
SELECT *
FROM suppliers
WHERE supplier_name = ‘Microsoft’
OR supplier_name = ‘Oracle’
OR supplier_name = ‘Flowers Foods’;
As you can see, using the IN condition makes the statement easier to read and more efficient than
using multiple OR conditions.
Next, let’s look at how to use the IN condition with numeric values.
In this example, we have a table called customers with the following data:
SELECT *
FROM customers
WHERE customer_id IN (5000, 7000, 8000, 9000);
There will be 4 records selected. These are the results that you should see:
This example would return all records from the customers table where the customer_id is either
5000, 7000, 8000 or 9000.
SELECT *
FROM customers
WHERE customer_id = 5000
OR customer_id = 7000
OR customer_id = 8000
OR customer_id = 9000;
Finally, let’s look at how to use the IN condition with the NOT operator. The NOT operator is
used to negate a condition. When we use the NOT operator with the IN condition, we create a
NOT IN condition. This will test to see if an expression is not in a list.
In this example, we have a table called products with the following data:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
SELECT *
FROM products
WHERE product_name NOT IN (‘Pear’, ‘Banana’, ‘Bread’);
There will be 4 records selected. These are the results that you should see:
3 Orange 50
4 Apple 50
6 Sliced Ham 25
7 Kleenex NULL
This example would return all rows from the products table where the product_name is not Pear,
Banana or Bread. Sometimes, it is more efficient to list the values that you do not want, as
opposed to the values that you do want.
SELECT *
FROM products
WHERE product_name <> ‘Pear’
AND product_name <> ‘Banana’
AND product_name <> ‘Bread’;
As you can see, the equivalent statement is written using AND conditions instead of OR
conditions because the IN condition is negated.
The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition in
the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax
NOT condition
This is the condition to negate. The opposite of the condition be must be met for the
record to be included in the result set.
If you want to follow along with this tutorial, get the DDL to create the tables and the DML to
populate the data. Then try the examples in your own database!
Let’s start by looking at how to use NOT with the IN condition. When we use the NOT operator
with the IN condition, we create a NOT IN condition. This will test to see if an expression is not
in a list.
In this example, we have a table called products with the following data:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
SELECT *
FROM products
WHERE product_name NOT IN (‘Pear’, ‘Banana’, ‘Bread’);
There will be 4 records selected. These are the results that you should see:
3 Orange 50
4 Apple 50
6 Sliced Ham 25
7 Kleenex NULL
This example would return all rows from the products table where the product_name is not Pear,
Banana or Bread. Sometimes, it is more efficient to list the values that you do not want, as
opposed to the values that you do want.
SELECT *
FROM products
WHERE product_name <> ‘Pear’
AND product_name <> ‘Banana’
AND product_name <> ‘Bread’;
When you combine the NOT operator with the IS NULL condition, you create an IS NOT NULL
condition that allows you to test for a non-NULL value. This is the recommended comparison
operator to use in SQL when testing for non-NULL values. Let’s look at an example that shows
how to use the IS NOT NULL condition in a query.
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
SELECT *
FROM products
WHERE category_id IS NOT NULL;
There will be 6 records selected. These are the results that you should see:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
This example will return all records from the products table where the customer_id does not
contain a NULL value.
Next, let’s look at an example of how to use the NOT operator with the LIKE condition.
In this example, we have a table called suppliers with the following data:
Let’s look for all records in the suppliers table where the supplier_name does not contain the
letter ‘o’. Enter the following SQL statement:
SELECT *
FROM suppliers
WHERE supplier_name NOT LIKE ‘%o%’;
There will be 1 record selected. These are the results that you should see:
In this example, there is only one record in the suppliers table where the supplier_name does not
contain the letter ‘o’.
The NOT operator can also be combined with the BETWEEN condition to create a NOT
BETWEEN condition. Let’s explore an example that shows how to use the NOT BETWEEN
condition in a query.
In this example, we have a table called customers with the following data:
SELECT *
FROM customers
WHERE customer_id NOT BETWEEN 5000 AND 8000;
There will be 2 records selected. These are the results that you should see:
This would return all rows where the customer_id was NOT between 5000 and 8000, inclusive.
It would be equivalent to the following SELECT statement:
SELECT *
FROM customers
WHERE customer_id < 5000
OR customer_id > 8000;
Finally, the NOT condition can be combined with the EXISTS condition to create a NOT
EXISTS condition. Let’s look at an example that shows how to use the NOT EXISTS condition
in SQL.
In this example, we have a table called customers with the following data:
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
SELECT *
FROM customers
WHERE NOT EXISTS
(SELECT *
FROM orders
WHERE customers.customer_id = orders.customer_id);
There will be 2 records selected. These are the results that you should see:
This example would return all records from the customers table where there are no records in
the orders table for the givencustomer_id.
The SQL BETWEEN condition allows you to easily test if an expression is within a range of
values (inclusive). It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax
Parameters or Arguments
expression
A column or calculation.
Note
The SQL BETWEEN Condition will return the records where expression is within the
range of value1 and value2(inclusive).
If you want to follow along with this tutorial, get the DDL to create the tables and the DML to
populate the data. Then try the examples in your own database!
Let’s look at an example of how to use the BETWEEN condition to retrieve values within a
numeric range.
In this example, we have a table called suppliers with the following data:
SELECT *
FROM suppliers
WHERE supplier_id BETWEEN 300 AND 600;
There will be 4 records selected. These are the results that you should see:
This example would return all rows from the suppliers table where the supplier_id is between
300 and 600 (inclusive). It is equivalent to the following SELECT statement:
SELECT *
FROM suppliers
WHERE supplier_id >= 300
AND supplier_id <= 600;
Dates can be somewhat tricky in SQL and how you use the BETWEEN condition with dates
depends on the database you are running (ie: Oracle, SQL Server, MySQL, etc). We will show
you an example for each of the major database technologies. So let’s get started.
In this example, we have a table called orders with the following data:
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
Enter one of the following SQL statements, depending on the database you are running.
SELECT *
FROM orders
WHERE order_date BETWEEN ‘2016/04/19’ AND ‘2016/05/01’;
SELECT *
FROM orders
WHERE order_date BETWEEN TO_DATE (‘2016/04/19’, ‘yyyy/mm/dd’)
AND TO_DATE (‘2016/05/01’, ‘yyyy/mm/dd’);
SELECT *
FROM orders
WHERE order_date BETWEEN CAST(‘2016/04/19’ AS DATE) AND CAST(‘2016/05/01’ AS
DATE);
There will be 3 records selected. These are the results that you should see:
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
This example would return all records from the orders table where the order_date is between
Apr 19, 2016 and May 1, 2016 (inclusive).
The BETWEEN condition can be used with the NOT operator to create a NOT BETWEEN
condition. Let’s explore an example that shows how to use the NOT BETWEEN condition in a
query.
In this example, we have a table called customers with the following data:
SELECT *
FROM customers
WHERE customer_id NOT BETWEEN 5000 AND 8000;
There will be 2 records selected. These are the results that you should see:
This would return all rows where the customer_id was NOT between 5000 and 8000, inclusive.
It would be equivalent to the following SELECT statement:
SELECT *
FROM customers
WHERE customer_id < 5000
OR customer_id > 8000;
The IS NULL condition is used in SQL to test for a NULL value. It returns TRUE if a NULL
value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or
DELETE statement.
Syntax
expression IS NULL
Parameters or Arguments
expression
If you want to follow along with this tutorial, get the DDL to create the tables and the DML to
populate the data. Then try the examples in your own database!
When testing for a NULL value, IS NULL is the recommended comparison operator to use in
SQL. Let’s start by looking at an example that shows how to use the IS NULL condition in
a SELECT statement.
In this example, we have a table called customers with the following data:
SELECT *
FROM customers
WHERE favorite_website IS NULL;
There will be 1 record selected. These are the results that you should see:
This example will return all records from the customers table where
the favorite_website contains a NULL value.
Next, let’s look at an example of how to use the IS NULL condition in an UPDATE statement.
In this example, we have a table called products with the following data:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
UPDATE products
SET category_id = 100
WHERE category_id IS NULL;
There will be 1 record updated. Select the data from the products table again:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex 100
This example will update all category_id values in the products table to 100 where
the category_id contains a NULL value. As you can see, the category_id in the last row has been
updated to 100.
Next, let’s look at an example of how to use the IS NULL condition in a DELETE statement.
In this example, we have a table called orders with the following data:
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
There will be 1 record deleted. Select the data from the orders table again:
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
4 4000 2016/04/20
This example will delete all records from the orders table where the customer_id contains a
NULL value. As you can see, it deleted the record for order_id=5.
Syntax
The syntax for the IS NOT NULL condition in Oracle/PLSQL is:
Parameters or Arguments
expression
Note
SELECT *
FROM customers
WHERE customer_name IS NOT NULL;
This Oracle IS NOT NULL example will return all records from the customers table where
the customer_name does not contain a null value.
This Oracle IS NOT NULL example will insert records into the suppliers table where
the account_no does not contain a null value in the customers table.
UPDATE customers
SET status = ‘Active’
WHERE customer_name IS NOT NULL;
This Oracle IS NOT NULL example will update records in the customers table where
the customer_name does not contain a null value.
This Oracle IS NOT NULL example will delete all records from the customers table where
the status does not contain a null value.
Syntax
The syntax for the LIKE condition in Oracle/PLSQL is:
Parameters or Arguments
expression
Pattern
A character expression that contains pattern matching. The patterns that you can choose
from are:
Wildcard Explanation
% Allows you to match any string of any length (including zero length)
escape_character
Optional. It allows you to test for literal instances of a wildcard character such as % or _.
SELECT last_name
You can also using the % wildcard multiple times within the same string. For example,
SELECT last_name
FROM customers
WHERE last_name LIKE ‘%er%’;
SELECT supplier_name
FROM suppliers
WHERE supplier_name LIKE ‘Sm_th’;
This Oracle LIKE condition example would return all suppliers whose supplier_name is 5
characters long, where the first two characters is ‘Sm’ and the last two characters is ‘th’. For
example, it could return suppliers whose supplier_name is ‘Smith’, ‘Smyth’, ‘Smath’, ‘Smeth’,
etc.
Here is another example:
SELECT *
FROM suppliers
WHERE account_number LIKE ‘92314_’;
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:
923140, 923141, 923142, 923143, 923144, 923145, 923146, 923147, 923148, 923149
SELECT supplier_name
FROM suppliers
WHERE supplier_name NOT LIKE ‘W%’;
By placing the NOT Operator in front of the Oracle LIKE condition, you are able to retrieve all
suppliers whose supplier_name does not start with ‘W’.
SELECT *
FROM suppliers
WHERE supplier_name LIKE ‘Water!%’ ESCAPE ‘!’;
This Oracle LIKE condition example identifies the ! character as an escape character. This
statement will return all suppliers whose name is Water%.
Here is another more complicated example using escape characters in the Oracle LIKE
condition.
SELECT *
FROM suppliers
WHERE supplier_name LIKE ‘H%!%’ ESCAPE ‘!’;
This Oracle LIKE condition example returns all suppliers whose name starts with H and ends in
%. For example, it would return a value such as ‘Hello%’.
SELECT *
FROM suppliers
WHERE supplier_name LIKE ‘H%!_’ ESCAPE ‘!’;
This Oracle LIKE condition example returns all suppliers whose name starts with H and ends in
_. For example, it would return a value such as ‘Hello_’.
SELECT *
FROM employees
WHERE employee_name LIKE ‘%h’;
SELECT *
FROM employees
WHERE employee_name LIKE ‘%s%’;
SELECT *
FROM suppliers
WHERE supplier_id LIKE ‘500_’;
ORDER BY Clause
The SQL ORDER BY clause is used to sort the records in the result set for a SELECT statement.
Syntax
The syntax for the ORDER BY clause in SQL is:
SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
Parameters or Arguments
expressions
Tables
The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.
WHERE conditions
ASC
Optional. ASC sorts the result set in ascending order by expression. This is the default
behavior, if no modifier is provider.
DESC
If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will
be sorted by expression in ascending order. This is equivalent to ORDER
BY expression ASC.
SELECT *
FROM customers
ORDER BY last_name;
There will be 6 records selected. These are the results that you should see:
This example would return all records from the customers sorted by the last_name field in
ascending order and would be equivalent to the following SQL ORDER BY clause:
SELECT *
FROM customers
ORDER BY last_name ASC;
SELECT *
FROM suppliers
WHERE supplier_id > 400
ORDER BY supplier_id DESC;
There will be 5 records selected. These are the results that you should see:
This example would sort the result set by the supplier_id field in descending order.
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
There will be 6 records selected. These are the results that you should see:
product_id product_name
7 Kleenex
6 Sliced Ham
4 Apple
3 Orange
2 Banana
1 Pear
This example would sort the results by the product_id field in descending order, since
the product_id field is in position #1 in the result set and would be equivalent to the following
SQL ORDER BY clause:
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
SELECT *
FROM products
WHERE product_id <> 7
ORDER BY category_id DESC, product_name ASC;
There will be 6 records selected. These are the results that you should see:
5 Bread 75
4 Apple 50
2 Banana 50
3 Orange 50
1 Pear 50
6 Sliced Ham 25
This example would return the records sorted by the category_id field in descending order, with
a secondary sort by product_name in ascending order.
XII. Group by
Syntax
The syntax for the GROUP BY clause in SQL is:
Parameters or Arguments
expression1, expression2, … expression_n
Expressions that are not encapsulated within an aggregate function and must be included
in the GROUP BY Clause at the end of the SQL statement.
Aggregate_function
This is an aggregate function such as the SUM, COUNT, MIN, MAX, or AVG functions.
Aggregate_expression
This is the column or expression that the aggregate_function will be used on.
Tables
The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.
WHERE conditions
Optional. These are conditions that must be met for the records to be selected.
ORDER BY expression
ASC
Optional. ASC sorts the result set in ascending order by expression. This is the default
behavior, if no modifier is provider.
DESC
There will be 2 records selected. These are the results that you should see:
dept_id total_salaries
dept_id total_salaries
500 119500
501 113000
In this example, we’ve used the SUM function to add up all of the salaries for each dept_id and
we’ve aliased the results of the SUM function as total_salaries. Because the dept_id is not
encapsulated in the SUM function, it must be listed in the GROUP BY clause.
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL
There will be 3 records selected. These are the results that you should see:
category_id total_products
25 1
50 4
75 1
In this example, we’ve used the COUNT function to calculate the number of products for
each category_id and we’ve aliased the results of the COUNT function as total_products. We’ve
excluded any category_id values that are NULL by filtering them out in the WHERE clause.
Because the category_id is not encapsulated in the COUNT function, it must be listed in the
GROUP BY clause.
There will be 2 records selected. These are the results that you should see:
dept_id lowest_salary
dept_id lowest_salary
500 57500
501 42000
In this example, we’ve used the MIN function to return the lowest salary for each dept_id and
we’ve aliased the results of the MIN function as lowest_salary. Because the dept_id is not
encapsulated in the MIN function, it must be listed in the GROUP BY clause.
There will be 2 records selected. These are the results that you should see:
dept_id highest_salary
500 62000
501 71000
In this example, we’ve used the MAX function to return the highest salary for each dept_id and
we’ve aliased the results of the MAX function as highest_salary. The dept_id column must be
listed in the GROUP BY clause because it is not encapsulated in the MAX function.
Syntax
The syntax for the AVG function in SQL is:
SELECT AVG(aggregate_expression)
FROM tables
[WHERE conditions];
OR the syntax for the AVG function when grouping the results by one or more columns is:
Parameters or Arguments
expression1, expression2, … expression_n
Expressions that are not encapsulated within the AVG function and must be included in
the GROUP BY clause at the end of the SQL statement.
Aggregate_expression
Tables
The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.
WHERE conditions
Optional. These are conditions that must be met for the records to be selected.
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.
If there were two cost values of $25, only one of these values would be used in the AVG
function calculation.
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.
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.
Syntax
The syntax for the COUNT function in SQL is:
SELECT COUNT(aggregate_expression)
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]];
OR the syntax for the COUNT function when grouping the results by one or more columns is:
Expressions that are not encapsulated within the COUNT function and must be included
in the GROUP BY clause at the end of the SQL statement.
Aggregate_expression
Tables
The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.
WHERE conditions
Optional. These are conditions that must be met for the records to be selected.
ORDER BY expression
Optional. The expression used to sort the records in the result set. If more than one
expression is provided, the values should be comma separated.
ASC
Optional. ASC sorts the result set in ascending order by expression. This is the default
behavior, if no modifier is provider.
DESC
Enter the following SELECT statement that uses the COUNT function:
SELECT COUNT(customer_id)
FROM customers;
There will be 1 record selected. These are the results that you should see:
COUNT(customer_id)
In this example, the query will return 6 since there are 6 records in the customers table and
all customer_id values are NOT NULL (ie: customer_id is the primary key for the table).
But what happens when we encounter a NULL value with the COUNT function? Let’s enter this
next SELECT statement that counts the favorite_website column which can contain NULL
values:
SELECT COUNT(favorite_website)
FROM customers;
There will be 1 record selected. These are the results that you should see:
COUNT(favorite_website)
There will be 1 record selected. These are the results that you should see:
total
In this example, we will return the number of employees who have a salary above $50,000.
We’ve aliased the COUNT(*) as total to make our query results more readable. Now, total will
display as the column heading when the result set is returned.
There will be 2 records selected. These are the results that you should see:
dept_id total
500 2
501 1
In this example, the COUNT function will return the number of employees that make over
$50,000 for each dept_id. Because the dept_id column is not included in the COUNT function, it
must be listed in the GROUP BY clause.
There will be 1 record selected. These are the results that you should see:
total
In this example, the COUNT function will return the unique number of dept_id values that have
at least one employee that makes over $50,000.
Now, the 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.
Syntax
The syntax for the MAX function in SQL is:
SELECT MAX(aggregate_expression)
FROM tables
[WHERE conditions];
OR the syntax for the MAX function when grouping the results by one or more columns is:
Parameters or Arguments
expression1, expression2, … expression_n
Expressions that are not encapsulated within the MAX function and must be included in
the GROUP BY clause at the end of the SQL statement.
Aggregate_expression
This is the column or expression from which the maximum value will be returned.
Tables
The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.
WHERE conditions
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.
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.
Syntax
The syntax for the MIN function in SQL is:
SELECT MIN(aggregate_expression)
FROM tables
[WHERE conditions];
OR the syntax for the MIN function when grouping the results by one or more columns is:
Parameters or Arguments
expression1, expression2, … expression_n
Expressions that are not encapsulated within the MIN function and must be included in
the GROUP BY clause at the end of the SQL statement.
Aggregate_expression
This is the column or expression from which the minimum value will be returned.
Tables
The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.
WHERE conditions
Optional. These are conditions that must be met for the records to be selected.
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.
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.
Syntax
The syntax for the SUM function in SQL is:
SELECT SUM(aggregate_expression)
FROM tables
[WHERE conditions];
OR the syntax for the SUM function when grouping the results by one or more columns is:
Parameters or Arguments
expression1, expression2, … expression_n
Expressions that are not encapsulated within the SUM function and must be included in
the GROUP BY clause at the end of the SQL statement.
Aggregate_expression
Tables
WHERE conditions
Optional. These are conditions that must be met for the records to be selected.
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.
If there were two salaries of $30,000/year, only one of these values would be used in the SQL
SUM function.
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.
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.
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 HAVING clause in SQL is:
Parameters or Arguments
expression1, expression2, … expression_n
Expressions that are not encapsulated within an aggregate function and must be included
in the GROUP BY Clause near the end of the SQL statement.
Aggregate_function
This is an aggregate function such as the SUM, COUNT, MIN, MAX, or AVG functions.
Aggregate_expression
This is the column or expression that the aggregate_function will be used on.
Tables
The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.
WHERE conditions
This is a further condition applied only to the aggregated results to restrict the groups of
returned rows. Only those groups whose condition evaluates to TRUE will be included in
the result set.
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.
Syntax
The syntax to create a primary key using the CREATE TABLE statement in SQL is:
OR
table_name
Column1, column2
Constraint_name
Example
Let’s look at an example of how to create a primary key using the CREATE TABLE statement
in SQL. We will start with a very simple one where our primary key consists of just one column.
For example:
In this example, we’ve created a primary key on the suppliers table called suppliers_pk. It
consists of only one column – the supplier_id column.
We could have used the alternate syntax and created this same primary key as follows:
Both of these syntaxes are valid when creating a primary key with only one field.
If you create a primary key that is made up of 2 or more columns, you are limited to using only
the first syntax where the primary key is defined at the end of the CREATE TABLE statement.
For example:
This example creates a primary key called contacts_pk that is made up of a combination of
the last_name and first_name columns. So each combination of last_name and first_name must
be unique in the contacts table.
Syntax
The syntax to create a primary key using the ALTER TABLE statement in SQL is:
table_name
The name of the table to modify. This is the table that you wish to add a primary key to.
Constraint_name
Example
Let’s look at an example of how to create a primary key using the ALTER TABLE statement in
SQL. So say, we already have a suppliers table created in our database. We could add a primary
to the suppliers table with the following ALTER TABLE statement:
In this example, we’ve created a primary key on the existing suppliers table called suppliers_pk.
It consists of the supplier_id column.
We could also create a primary key with more than one field as in the example below:
This example would created a primary key called suppliers_pk that is made up of a combination
of the supplier_id and supplier_name columns.
Syntax
The syntax to drop a primary key in SQL is:
table_name
The name of the table to modify. This is the table whose primary key you wish to drop.
Example
Let’s look at an example of how to drop a primary key using the ALTER TABLE statement in
SQL.
In this example, we’ve dropped the primary key on the suppliers table. We do not need to
specify the name of the primary key as there can only be one primary key on a table.
Foreign Keys
Syntax
The syntax for creating a foreign key using a CREATE TABLE statement is:
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, … column_n)
REFERENCES parent_table (column1, column2, … column_n)
);
Example
In this example, we’ve created a primary key on the supplier table called supplier_pk. It consists
of only one field – the supplier_id field. Then we’ve created a foreign key called fk_supplier on
the products table that references the supplier table based on the supplier_id field.
We could also create a foreign key with more than one field as in the example below:
In this example, our foreign key called fk_foreign_comp references the supplier table based on
two fields – the supplier_id and supplier_name fields.
Syntax
The syntax for creating a foreign key in an ALTER TABLE statement is:
Example
In this example, we’ve created a foreign key called fk_supplier that references the supplier table
based on the supplier_id field.
We could also create a foreign key with more than one field as in the example below:
SQL: JOINS
SQL JOINS are used to retrieve data from multiple tables. A SQL JOIN is performed whenever
two or more tables are listed in a SQL statement.
There are 4 different types of SQL joins:
So let’s discuss SQL JOIN syntax, look at visual illustrations of SQL JOINS and explore some
examples.
Syntax
The syntax for the INNER JOIN in SQL is:
SELECT columns
FROM table1
INNER JOIN table2
ON [Link] = [Link];
Visual Illustration
In this visual diagram, the SQL INNER JOIN returns the shaded area:
The SQL INNER JOIN would return the records where table1 and table2 intersect.
Example
Let’s look at an example of how to use the INNER JOIN in a query.
In this example, we have a table called customers with the following data:
customer_id last_name first_name favorite_website
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
There will be 4 records selected. These are the results that you should see:
customer_id order_id order_date
4000 4 2016/04/20
5000 2 2016/04/18
7000 1 2016/04/18
8000 3 2016/04/19
This example would return all rows from the customers and orders tables where there is a
matching customer_id value in both the customers and orders tables.
The rows where customer_id is equal to 6000 and 9000 in the customers table would be omitted,
since they do not exist in both tables. The row where the order_id is 5 from the orders table
would be omitted, since the customer_id of NULL does not exist in the customers table.
Old Syntax
As a final note, it is worth mentioning that the INNER JOIN example above could be rewritten
using the older implicit syntax as follows (but we still recommend using the INNER JOIN
keyword syntax):
Syntax
The syntax for the LEFT OUTER JOIN in SQL is:
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON [Link] = [Link];
In some databases, the OUTER keyword is omitted and written simply as 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
Now let’s look at an example that shows how to use the LEFT OUTER JOIN in a SELECT
statement.
Using the same customers table as the previous example:
customer_id last_name first_name favorite_website
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
There will be 6 records selected. These are the results that you should see:
customer_id order_id order_date
4000 4 2016/04/20
5000 2 2016/04/18
7000 1 2016/04/18
8000 3 2016/04/19
This LEFT OUTER JOIN example would return all rows from the customers table and only
those rows from the orders table where the joined fields are equal.
If a customer_id value in the customers table does not exist in the orders table, all fields in
the orders table will display as NULL in the result set. As you can see, the rows
where customer_id is 6000 and 9000 would be included with a LEFT OUTER JOIN but
the order_id and order_date fields display NULL.
Syntax
The syntax for the RIGHT OUTER JOIN in SQL is:
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON [Link] = [Link];
In some databases, the OUTER keyword is omitted and written simply as 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
Now let’s look at an example that shows how to use the RIGHT OUTER JOIN in a SELECT
statement.
Using the same customers table as the previous example:
customer_id last_name first_name favorite_website
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
There will be 5 records selected. These are the results that you should see:
customer_id order_id order_date
NULL 5 2016/05/01
4000 4 2016/04/20
5000 2 2016/04/18
7000 1 2016/04/18
8000 3 2016/04/19
This RIGHT OUTER JOIN example would return all rows from the orders table and only those
rows from the customers table where the joined fields are equal.
If a customer_id value in the orders table does not exist in the customers table, all fields in
the customers table will display as NULL in the result set. As you can see, the row
where order_id is 5 would be included with a RIGHT OUTER JOIN but the customer_id field
displays NULL.
SELECT columns
FROM table1
FULL [OUTER] JOIN table2
ON [Link] = [Link];
In some databases, the OUTER keyword is omitted and written simply as 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
Let’s look at an example that shows how to use the FULL OUTER JOIN in a SELECT
statement.
Using the same customers table as the previous example:
customer_id last_name first_name favorite_website
1 7000 2016/04/18
2 5000 2016/04/18
3 8000 2016/04/19
4 4000 2016/04/20
5 NULL 2016/05/01
There will be 7 records selected. These are the results that you should see:
customer_id order_id order_date
NULL 5 2016/05/01
4000 4 2016/04/20
5000 2 2016/04/18
7000 1 2016/04/18
8000 3 2016/04/19
This FULL OUTER JOIN example would return all rows from the orders table and all rows
from the customers table. Whenever the joined condition is not met, a NULL value would be
extended to those fields in the result set. This means that if a customer_id value in
the customers table does not exist in the orders table, all fields in the orders table will display as
NULL in the result set. Also, if a customer_id value in the orders table does not exist in
the customers table, all fields in the customers table will display as NULL in the result set.
As you can see, the rows where the customer_id is 6000 and 9000 would be included but
the order_id and order_date fields for those records contains a NULL value. The row where
the order_id is 5 would be also included but the customer_id field for that record has a NULL
value.
SQL: VIEW
The SQL VIEW is, in essence, a virtual table that does not physically exist. Rather, it is created
by a SQL statement that joins one or more tables.
Syntax
The syntax for the CREATE VIEW statement in SQL is:
view_name
WHERE conditions
Optional. The conditions that must be met for the records to be included in the VIEW.
Example
Here is an example of how to use the SQL CREATE VIEW:
This SQL CREATE VIEW example would create a virtual table based on the result set of the
select statement. You can now query the SQL VIEW as follows:
SELECT *
FROM sup_orders;
Syntax
The syntax for the SQL CREATE OR REPLACE VIEW Statement is:
Example
Here is an example of how you would use the SQL CREATE OR REPLACE VIEW Statement:
This SQL CREATE OR REPLACE VIEW example would update the definition of the SQL
VIEW called sup_orders without dropping it. If the SQL VIEW did not yet exist, the SQL VIEW
would merely be created for the first time.
Syntax
The syntax for the SQL DROP VIEW Statement is:
view_name
This SQL DROP VIEW example would drop/delete the SQL VIEW called sup_orders.
SQL: Indexes
Create an Index
You can create an index in SQL using the CREATE INDEX statement.
Syntax
The syntax to create an index in SQL is:
UNIQUE
The UNIQUE modifier indicates that the combination of values in the indexed columns
must be unique.
Index_name
Table_name
Example
Let’s look at an example of how to create an index in SQL.
For example:
This would create an index called websites_idx that is made up of two columns –
site_name and server.
Unique Index
Similar to a primary key, a unique key allows you to choose one column or combination of
columns that must be unique for each record. Although you can only have one primary key on a
table, you can create as many unique indexes on a table as you need.
To create a unique index on a table, you need to specify the UNIQUE keyword in the CREATE
INDEX statement.
For example:
This example would create a unique index on the site_name field so that this field must always
contains a unique value with no duplicates. This is a great way to enforce integrity within your
database if you require unique values in columns that are not part of your primary key.
Drop an Index
You can drop an index in SQL using the DROP INDEX statement.
Syntax
The syntax to drop an index in SQL is:
For Oracle and PostgreSQL:
index_name
Table_name
Example
Let’s look at an example of how to drop an index called websites_idx from the websites table.
For Oracle:
Because each index name must be unique within the database, we do not have to specify
the websites table in the DROP INDEX statement in Oracle.
For MySQL and MariaDB:
As you can see, each database has unique differences in their syntax. Be sure you use the correct
DROP INDEX command.
XX. Roles
Roles
A role is a set or group of privileges that can be granted to users or another role. This is a great
way for database administrators to save time and effort.
Create Role
You may wish to create a role so that you can logically group the users' permissions. Please note
that to create a role, you must have CREATE ROLE system privileges.
Syntax
The syntax for creating a role in Oracle is:
role_name
The name of the new role that you are creating. This is how you will refer to the grouping
of privileges.
NOT IDENTIFIED
It means that the role is immediately enabled. No password is required to enable the role.
IDENTIFIED
It means that a user must be authorized by a specified method before the role is enabled.
BY password
USING package
It means that you are creating an application role - a role that is enabled only by
applications using an authorized package.
EXTERNALLY
It means that a user must be authorized by an external service to enable the role. An
external service can be an operating system or third-party service.
It means that a user must be authorized by the enterprise directory service to enable the
role.
Note
If both NOT IDENTIFIED and IDENTIFIED are omitted in the CREATE ROLE
statement, the role will be created as a NOT IDENTIFIED role.
Example
Let's look at an example of how to create a role in Oracle.
For example:
This second example creates the same role called test_role, but now it is password protected with
the password of test123.
Syntax
The syntax for granting table privileges to a role in Oracle is:
The privileges to assign to the role. It can be any of the following values:
Privilege Description
INDEX Ability to create an index on the table with the create index statement.
object
The name of the database object that you are granting privileges for. In the case of
granting privileges on a table, this would be the table name.
role_name
Example
Let's look at some examples of how to grant table privileges to a role in Oracle.
For example, if you wanted to grant SELECT, INSERT, UPDATE, and DELETE privileges on a
table called suppliers to a role named test_role, you would run the following GRANT statement:
You can also use the ALL keyword to indicate that you wish all permissions to be granted. For
example:
Syntax
The syntax for revoking table privileges from a role in Oracle is:
privileges
The privileges to revoke from the role. It can be any of the following values:
Privilege Description
INDEX Ability to create an index on the table with the create index statement.
object
The name of the database object that you are revoking privileges for. In the case of
revoking privileges on a table, this would be the table name.
The name of the role that will have these privileges revoked.
Example
Let's look at some examples of how to revoke table privileges from a role in Oracle.
For example, if you wanted to revoke DELETE privileges on a table called suppliers from a role
named test_role, you would run the following REVOKE statement:
If you wanted to revoke ALL privileges on the table called suppliers from a role
named test_role, you could use the ALL keyword. For example:
Syntax
The syntax for granting EXECUTE privileges on a function/procedure to a role in Oracle is:
EXECUTE
The ability to compile the function/procedure and the ability to execute the
function/procedure directly.
object
The name of the database object that you are granting privileges for. In the case of
granting EXECUTE privileges on a function or procedure, this would be the function
name or the procedure name.
role_name
The name of the role that will be granted the EXECUTE privileges.
Example
Syntax
The syntax for the revoking privileges on a function or procedure from a role in Oracle is:
EXECUTE
Revoking the ability to compile the function/procedure and the ability to execute the
function/procedure directly.
object
The name of the database object that you are revoking privileges for. In the case of
revoking EXECUTE privileges on a function or procedure, this would be the function
name or the procedure name.
role_name
The name of the role that will have the EXECUTE privileges revoked.
Example
Let's look at an example of how to grant EXECUTE privileges on a function or procedure to a
role in Oracle.
If you wanted to revoke EXECUTE privileges on a function called Find_Value from a role
named test_role, you would run the following REVOKE statement:
Syntax
The syntax to grant a role to a user in Oracle is:
role_name
user_name
Example
Let's look at an example of how to grant a role to a user in Oracle:
This example would grant the role called test_role to the user named smithj.
Syntax
The syntax for the SET ROLE statement in Oracle is:
SET ROLE
( role_name [ IDENTIFIED BY password ] | ALL [EXCEPT role1, role2, ... ] | NONE );
role_name
The password for the role to enable it. If the role does not have a password, this phrase
can be omitted.
ALL
It means that all roles should be enabled for this current session, except those listed
in EXCEPT.
NONE
Disables all roles for the current session (including all default roles).
Example
Let's look at an example of how to enable a role in Oracle.
For example:
This example would enable the role called test_role with a password of test123.
Syntax
The syntax for setting a role as a DEFAULT ROLE in Oracle is:
user_name
The name of the user whose role you are setting as DEFAULT.
role_name
ALL
NONE
Example
Let's look at an example of how to set a role as a DEFAULT ROLE in Oracle.
For example:
This example would set the role called test_role as a DEFAULT role for the user named smithj.
This example would set all roles assigned to smithj as DEFAULT, except for the role
called test_role.
Drop Role
Once a role has been created in Oracle, you might at some point need to drop the role.
Syntax
The syntax to drop a role in Oracle is:
role_name
This DROP statement would drop the role called test_role that we defined earlier.