Top Banner
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
182
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Query

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

Page 2: Query

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

Page 3: Query

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;

Page 4: Query

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:

Page 5: Query

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)

);

Page 6: Query

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,

Page 7: Query

quantity number(5),

CONSTRAINT orders_pk PRIMARY KEY (order_id)

);

SOLUTION FOR PRACTICE EXERCISE #3:

The following SQL SELECT statement would select these records from the suppliers and orders table (using a SQL INNER JOIN):

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date

FROM suppliers

INNER JOIN orders

ON suppliers.supplier_id = orders.supplier_id

ORDER BY supplier_id DESC;

PRACTICE EXERCISE #4:

Based on the customers and old_customers table, select the customer_id and customer_name from the customers table that exist in the old_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)

);

Page 8: Query

CREATE TABLE old_customers

( old_customer_id number(10) not null,

old_customer_name varchar2(50) not null,

old_city varchar2(50),

status varchar2(20),

CONSTRAINT old_customers_pk PRIMARY KEY (old_customer_id)

);

SOLUTION FOR PRACTICE EXERCISE #4:

The following SQL SELECT statement would select the records from the customers table (using the SQL EXISTS clause):

SELECT customer_id, customer_name

FROM customers

WHERE EXISTS

( SELECT old_customers.old_customer_id

FROM old_customers

WHERE old_customers.old_customer_id = customers.customer_id )

ORDER BY customer_name ASC, customer_id DESC;

Or alternatively you could exclude the ASC keyword for customer_name in the ORDER BY clause. Both of these SELECT statements would generate the same results:

SELECT customer_id, customer_name

FROM customers

WHERE EXISTS

( SELECT old_customers.old_customer_id

Page 9: Query

FROM old_customers

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;

Page 10: Query

PARAMETERS OR ARGUMENTS

table is the table to insert the records into.

column1, column2 are the columns in the table to insert values.

expression1, expression2 are the values to assign to the columns in the table. So column1 would be assigned the value of expression1, column2 would be assigned the value of expression2, and so on.

source_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:

Page 11: Query

INSERT INTO suppliers

(supplier_id, supplier_name)

SELECT account_no, name

FROM customers

WHERE city = 'Newark';

By placing a SELECT statement within the INSERT statement, you can perform multiples inserts quickly.

With this type of insert, you may wish to check for the number of rows being inserted. You can determine the number of rows that will be inserted by running the following SQL SELECT statement before performing the insert.

SELECT count(*)

FROM customers

WHERE city = 'Newark';

FREQUENTLY ASKED QUESTIONS

Question: I am setting up a database with clients. I know that you use the SQL INSERT statement to insert information in the database, but how do I make sure that I do not enter the same client information again?

Answer: You can make sure that you do not insert duplicate information by using the SQL EXISTS condition.

For example, if you had a table named clients with a primary key of client_id, you could use the following SQL INSERT statement:

INSERT INTO clients

(client_id, client_name, client_type)

SELECT supplier_id, supplier_name, 'advertising'

FROM suppliers

Page 12: Query

WHERE NOT EXISTS (SELECT *

FROM clients

WHERE clients.client_id = suppliers.supplier_id);

This SQL INSERT statement inserts multiple records with a subselect.

If you wanted to insert a single record, you could use the following SQL INSERT statement:

INSERT INTO clients

(client_id, client_name, client_type)

SELECT 10345, 'IBM', 'advertising'

FROM dual

WHERE NOT EXISTS (SELECT *

FROM clients

WHERE clients.client_id = 10345);

The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.

PRACTICE EXERCISE #1:

Based on the employees table, insert an employee record whose employee_number is 1001, employee_name is Sally Johnson and salary is $32,000:

CREATE TABLE employees

( employee_number number(10) not null,

employee_name varchar2(50) not null,

salary number(6),

CONSTRAINT employees_pk PRIMARY KEY (employee_number)

);

Page 13: Query

SOLUTION FOR PRACTICE EXERCISE #1:

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

INSERT INTO employees (employee_number, employee_name, salary)

VALUES (1001, 'Sally Johnson', 32000);

PRACTICE EXERCISE #2:

Based on the suppliers table, insert a supplier record whose supplier_id is 5001 and supplier_name is Apple:

CREATE TABLE suppliers

( supplier_id number(10) not null,

supplier_name varchar2(50) not null,

city varchar2(50),

CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)

);

SOLUTION FOR PRACTICE EXERCISE #2:

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

INSERT INTO suppliers (supplier_id, supplier_name)

VALUES (5001, 'Apple');

PRACTICE EXERCISE #3:

Based on the customers and old_customers table, insert into the customers table all records from the old_customers table whose status is DELETED.

CREATE TABLE customers

( customer_id number(10) not null,

Page 14: Query

customer_name varchar2(50) not null,

city varchar2(50),

CONSTRAINT customers_pk PRIMARY KEY (customer_id)

);

CREATE TABLE old_customers

( old_customer_id number(10) not null,

old_customer_name varchar2(50) not null,

old_city varchar2(50),

status varchar2(20),

CONSTRAINT old_customers_pk PRIMARY KEY (old_customer_id)

);

SOLUTION FOR PRACTICE EXERCISE #3:

The following SQL INSERT statement would be the solution to insert into the customers table using a sub-select:

INSERT INTO customers

(customer_id, customer_name, city)

SELECT old_customer_id, old_customer_name, old_city

FROM old_customers

WHERE status = 'DELETED';

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.

Page 15: Query

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,

Page 16: Query

...

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';

Page 17: Query

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, contactsSET 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.

Page 18: Query

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),

Page 19: Query

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

Page 20: Query

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)

Page 21: Query

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:

Page 22: Query

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:

Page 23: Query

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.

Page 24: Query

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

Page 25: Query

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:

Page 26: Query

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

Page 27: Query

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:

Page 28: Query

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

Page 29: Query

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

Page 30: Query

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)

Page 31: Query

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:

Page 32: Query

SELECT expression1, expression2, ... expression_n

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;

Page 33: Query

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.

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.

Page 34: Query

Each SQL statement within the SQL INTERSECT must have the same number of fields in the result sets with similar data types.

SYNTAX

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

Page 35: Query

WHERE supplier_id > 2000

INTERSECT

SELECT company_id, company_name

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

Page 36: Query

FROM tables;

EXAMPLE - WITH SINGLE EXPRESSION

The following is a SQL MINUS operator example that has one field with the same data type:

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

Page 37: Query

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: 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;

Page 38: Query

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

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

Page 39: Query

10003 NVIDIA

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

Page 40: Query

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):

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:

Page 41: Query

The SQL LEFT OUTER JOIN would return the all records from table1 and only those records from table2 that intersect with table1.

EXAMPLE

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

Page 42: Query

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

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>

Page 43: Query

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

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:

Page 44: Query

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

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

Page 45: Query

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

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

Page 46: Query

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

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.

Page 47: Query

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:

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_i order_date

Page 48: Query

d

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:

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.

Page 49: Query

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:

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

Page 50: Query

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"

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 employeesGROUP 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

Page 51: Query

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_dateFROM suppliers sINNER JOIN order_detailsON 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_dateFROM suppliers sINNER JOIN order_details odON 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

Page 52: Query

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.

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:

Page 53: Query

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;

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

Page 54: Query

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';

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!

Page 55: Query

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

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.

Page 56: Query

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.

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.

Page 57: Query

EXAMPLE - SORTING IN DESCENDING ORDER

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

SELECT supplier_city

FROM suppliers

WHERE supplier_name = 'IBM'

ORDER BY supplier_city DESC;

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

EXAMPLE - SORTING BY RELATIVE POSITION

You can also use the SQL ORDER BY clause to sort by relative position in the result set, where the first field in the result set is 1. The next field is 2, and so on.

For example:

SELECT supplier_city

FROM suppliers

WHERE supplier_name = 'IBM'

ORDER BY 1 DESC;

This SQL ORDER BY would return all records sorted by the supplier_city field in descending order, since the supplier_city field is in position #1 in the result set and would be equivalent to the following SQL ORDER BY clause:

SELECT supplier_city

FROM suppliers

WHERE supplier_name = 'IBM'

ORDER BY supplier_city DESC;

Page 58: Query

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.

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

Page 59: Query

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;

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

Page 60: Query

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

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)

Page 61: Query

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.

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.

Page 62: Query

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

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;

Page 63: Query

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.

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  

Page 64: Query

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

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.

Page 65: Query

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

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"

Page 66: Query

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),

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)

Page 67: Query

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

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:

Page 68: Query

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)

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');

Page 69: Query

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

( 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)

Page 70: Query

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)

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:

Page 71: Query

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

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

Page 72: Query

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"

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.

Page 73: Query

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.

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

Page 74: Query

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.

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.

Page 75: Query

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.

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;

Page 76: Query

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.

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

Page 77: Query

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.

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,

Page 78: Query

(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

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;

Page 79: Query

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;

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);

Page 80: Query

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.

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

Page 81: Query

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"

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.

Page 82: Query

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

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;

Page 83: Query

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'

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';

Page 84: Query

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.

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;

Page 85: Query

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.

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.

Page 86: Query

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

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;

Page 87: Query

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.

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.

Page 88: Query

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:

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.

Page 89: Query

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. 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

Page 90: Query

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.

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.

Page 91: Query

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

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

Page 92: Query

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).

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

Page 93: Query

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

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'.

Page 94: Query

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 '!';

This SQL LIKE condition example identifies the ! character as an escape character. This statement will return all suppliers whose name is %.

Here is another more complicated example using escape characters in the SQL LIKE condition.

SELECT *

FROM suppliers

WHERE supplier_name LIKE 'H%!%' escape '!';

This SQL LIKE condition example returns all suppliers whose name starts with H and ends in %. For example, it would return a value such as 'Hello%'.

Page 95: Query

You can also use the escape character with the _ character in the SQL LIKE condition.

For example:

SELECT *

FROM suppliers

WHERE supplier_name LIKE 'H%!_' escape '!';

This SQL LIKE condition example returns all suppliers whose name starts with H and ends in _. For example, it would return a value such as 'Hello_'.

FREQUENTLY ASKED QUESTIONS

Question: How do you incorporate the Oracle UPPER function with the SQL LIKE condition? I'm trying to query against a free text field for all records containing the word "test". The problem is that it can be entered in the following ways: TEST, Test, or test.

Answer: To answer this question, let's look at an example.

Let's say that we have a suppliers table with a field called supplier_name that contains the values TEST, Test, or test.

If we wanted to find all records containing the word "test", regardless of whether it was stored as TEST, Test, or test, we could run either of the following SQL SELECT statements:

SELECT *

FROM suppliers

WHERE UPPER(supplier_name) LIKE ('TEST%');

OR

SELECT *

FROM suppliers

WHERE UPPER(supplier_name) LIKE UPPER('test%')

Page 96: Query

These SQL SELECT statements use a combination of the Oracle UPPER function and the SQL LIKE condition to return all of the records where thesupplier_name field contains the word "test", regardless of whether it was stored as TEST, Test, or test.

PRACTICE EXERCISE #1:

Based on the employees table populated with the following data, find all records whose employee_name ends with the letter "h".

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)

);

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);

Page 97: Query

SOLUTION FOR PRACTICE EXERCISE #1:

The following SQL SELECT statement uses the SQL LIKE condition to return the records whose employee_name ends with the letter "h".

SELECT *

FROM employees

WHERE employee_name LIKE '%h';

It would return the following result set:

EMPLOYEE_NUMBER EMPLOYEE_NAME SALARY

1001 John Smith 62000

1004 Jack Horvath 42000

PRACTICE EXERCISE #2:

Based on the employees table populated with the following data, find all records whose employee_name contains the letter "s".

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)

);

INSERT INTO employees (employee_number, employee_name, salary)

VALUES (1001, 'John Smith', 62000);

Page 98: Query

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 #2:

The following SQL SELECT statement would use the SQL LIKE condition to return the records whose employee_name contains the letter "s".

SELECT *

FROM employees

WHERE employee_name LIKE '%s%';

It would return the following result set:

EMPLOYEE_NUMBER EMPLOYEE_NAME SALARY

1002 Jane Anderson 57500

1003 Brad Everest 71000

PRACTICE EXERCISE #3:

Based on the suppliers table populated with the following data, find all records whose supplier_id is 4 digits and starts with "500".

Page 99: Query

CREATE TABLE suppliers

( supplier_id varchar2(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 ('5008', 'Microsoft', 'New York');

INSERT INTO suppliers (supplier_id, supplier_name, city)

VALUES ('5009', 'IBM', 'Chicago');

INSERT INTO suppliers (supplier_id, supplier_name, city)

VALUES ('5010', 'Red Hat', 'Detroit');

INSERT INTO suppliers (supplier_id, supplier_name, city)

VALUES ('5011', 'NVIDIA', 'New York');

SOLUTION FOR PRACTICE EXERCISE #3:

The following SQL SELECT statement would use the SQL LIKE condition to return the records whose supplier_id is 4 digits and starts with "500".

SELECT *

Page 100: Query

FROM suppliers

WHERE supplier_id LIKE '500_';

It would return the following result set:

SUPPLIER_ID SUPPLIER_NAME CITY

5008 Microsoft New York

5009 IBM Chicago

SQL: IN CONDITION

Learn how to use the SQL IN condition with syntax and examples.

DESCRIPTION

The SQL IN condition is used to help reduce the need for multiple OR conditions in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL IN condition is:

expression IN (value1, value2, .... value_n);

PARAMETERS OR ARGUMENTS

expression is a value to test.

value1, value2..., or value_n are the values to test against expression.

NOTE

The SQL IN condition will return the records where expression is value1, value2..., or value_n. The SQL IN condition is also called the SQL IN operator.

EXAMPLE - WITH CHARACTER

Let's look at an IN condition example using character values.

Page 101: Query

The following is a SQL SELECT statement that uses the IN condition to compare character values:

SELECT *

FROM suppliers

WHERE supplier_name IN ('IBM', 'Hewlett Packard', 'Microsoft');

This SQL IN condition example would return all rows where the supplier_name is either IBM, Hewlett Packard, or Microsoft. Because the * is used in the select, all fields from the suppliers table would appear in the result set.

This IN condition example is equivalent to the following SQL statement:

SELECT *

FROM suppliers

WHERE supplier_name = 'IBM'

OR supplier_name = 'Hewlett Packard'

OR supplier_name = 'Microsoft';

As you can see, using the SQL IN condition makes the statement easier to read and more efficient.

EXAMPLE - WITH NUMERIC

Next, let's look at an IN condition example using numeric values.

For example:

SELECT *

FROM orders

WHERE order_id IN (10000, 10001, 10003, 10005);

This SQL IN condition example would return all orders where the order_id is either 10000, 10001, 10003, or 10005.

Page 102: Query

This IN condition example is equivalent to the following SQL statement:

SELECT *

FROM orders

WHERE order_id = 10000

OR order_id = 10001

OR order_id = 10003

OR order_id = 10005;

EXAMPLE - USING NOT OPERATOR

Finally, let's look at an IN condition example using the NOT operator.

For example:

SELECT *

FROM suppliers

WHERE supplier_name NOT IN ( 'IBM', 'Hewlett Packard', 'Microsoft');

This SQL IN condition example would return all rows where the supplier_name is neither IBM, Hewlett Packard, or Microsoft. Sometimes, it is more efficient to list the values that you do not want, as opposed to the values that you do want.

SQL: NOT CONDITION

Learn how to use the SQL NOT condition with syntax and examples.

DESCRIPTION

The SQL NOT Condition (also known as the SQL NOT Operator) is used to negate a condition in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL NOT Condition is:

Page 103: Query

NOT condition

PARAMETERS OR ARGUMENTS

condition is the condition to negate.

NOTE

The SQL NOT condition requires that the opposite of the condition be must be met for the record to be included in the result set.

EXAMPLE - COMBINE WITH IN CONDITION

The SQL NOT condition can be combined with the IN Condition.

For example:

SELECT *

FROM suppliers

WHERE supplier_name NOT IN ( 'IBM', 'Hewlett Packard', 'Microsoft' );

This SQL NOT example would return all rows where the supplier_name is neither IBM, Hewlett Packard, or Microsoft. Sometimes, it is more efficient to list the values that you do not want, as opposed to the values that you do want.

EXAMPLE - COMBINE WITH IS NULL CONDITION

The SQL NOT condition can also be combined with the IS NULL Condition.

For example,

SELECT *

FROM customers

WHERE customer_name IS NOT NULL;

This SQL NOT example would return all records from the customers table where the customer_name does not contain a NULL value.

EXAMPLE - COMBINE WITH LIKE CONDITION

Page 104: Query

The SQL NOT condition can also be combined with the LIKE Condition.

For example:

SELECT supplier_name

FROM suppliers

WHERE supplier_name NOT LIKE 'T%';

By placing the SQL 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 - COMBINE WITH BETWEEN CONDITION

The SQL NOT condition can also be combined with the BETWEEN Condition. Here is an example of how you would combine the NOT Operator with the BETWEEN Condition.

For example:

SELECT *

FROM suppliers

WHERE supplier_id NOT BETWEEN 5000 AND 5500;

This SQL NOT example would return all rows where the supplier_id was NOT between 5000 and 5500, inclusive. It would be equivalent to the following SQL SELECT statement:

SELECT *

FROM suppliers

WHERE supplier_id < 5000

OR supplier_id > 5500;

EXAMPLE - COMBINE WITH EXISTS CONDITION

The SQL NOT condition can also be combined with the EXISTS Condition.

For example,

Page 105: Query

SELECT *

FROM suppliers

WHERE NOT EXISTS (SELECT *

FROM orders

WHERE suppliers.supplier_id = orders.supplier_id);

This SQL NOT example would return all records from the suppliers table where there are no records in the orders table for the given supplier_id.

SQL: IS NULL CONDITION

Learn how to use the SQL IS NULL condition with syntax and examples.

DESCRIPTION

The SQL IS NULL condition is used to test for a NULL value in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL IS NULL condition is:

expression IS NULL

PARAMETERS OR ARGUMENTS

expression is the value to test.

NOTE

If expression is a NULL value, the condition evaluates to TRUE. If expression is not a NULL value, the condition evaluates to FALSE.

EXAMPLE - WITH SELECT STATEMENT

Let's look at an example of how to use IS NULL in a SELECT statement:

SELECT *

Page 106: Query

FROM suppliers

WHERE supplier_name IS NULL;

This SQL IS NULL example will return all records from the suppliers table where the supplier_name contains a NULL value.

EXAMPLE - WITH INSERT STATEMENT

Next, let's look at an example of how to use SQL IS NULL in an INSERT statement:

INSERT INTO suppliers

(supplier_id, supplier_name)

SELECT account_no, name

FROM customers

WHERE city IS NULL;

This SQL IS NULL example will insert records into the suppliers table where the city contains a NULL value.

EXAMPLE - WITH UPDATE STATEMENT

Next, let's look at an example of how to use SQL IS NULL in an UPDATE statement:

UPDATE suppliers

SET supplier_name = 'Apple'

WHERE supplier_name IS NULL;

This SQL IS NULL example will update records in the suppliers table where the supplier_name contains a NULL value.

EXAMPLE - WITH DELETE STATEMENT

Next, let's look at an example of how to use SQL IS NULL in a DELETE statement:

DELETE FROM suppliers

Page 107: Query

WHERE supplier_name IS NULL;

This SQL IS NULL example will delete all records from the suppliers table where the supplier_name contains a NULL value.

SQL: IS NOT NULL CONDITION

Learn how to use the SQL IS NOT NULL condition with syntax and examples.

DESCRIPTION

The SQL IS NOT NULL Condition is used to test for a NOT NULL value in SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL IS NOT NULL Condition is:

expression IS NOT NULL

PARAMETERS OR ARGUMENTS

expression is the value to test.

NOTE

If expression is NOT a NULL value, the condition evaluates to TRUE. If expression is a NULL value, the condition evaluates to FALSE.

EXAMPLE - WITH SELECT STATEMENT

Let's look at an example of how to use SQL IS NOT NULL in a SQL SELECT statement:

SELECT *

FROM customers

WHERE customer_name IS NOT NULL;

This SQL IS NOT NULL example will return all records from the customers table where the customer_name does not contain a NULL value.

Page 108: Query

EXAMPLE - WITH INSERT STATEMENT

Next, let's look at an example of how to use SQL IS NOT NULL in a SQL INSERT statement:

INSERT INTO suppliers

(supplier_id, supplier_name)

SELECT account_no, name

FROM customers

WHERE account_no IS NOT NULL;

This SQL 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.

EXAMPLE - WITH UPDATE STATEMENT

Next, let's look at an example of how to use SQL IS NOT NULL in a SQL UPDATE statement:

UPDATE suppliers

SET supplier_name = 'Apple'

WHERE supplier_name IS NOT NULL;

This SQL IS NOT NULL example will update records in the suppliers table where the supplier_name does not contain a NULL value.

EXAMPLE - WITH DELETE STATEMENT

Next, let's look at an example of how to use SQL IS NOT NULL in a SQL DELETE statement:

DELETE FROM customers

WHERE status IS NOT NULL;

This SQL IS NOT NULL example will delete all records from the customers table where the status does not contain a NULL value.

Page 109: Query

SQL: BETWEEN CONDITION

Learn how to use the SQL BETWEEN condition with syntax and examples.

DESCRIPTION

The SQL BETWEEN Condition is used to retrieve values within a range in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL BETWEEN Condition is:

expression BETWEEN value1 AND value2;

PARAMETERS OR ARGUMENTS

expression is a column or calculation.

value1 and value2 create an inclusive range that expression is compared to.

NOTE

The SQL BETWEEN Condition will return the records where expression is within the range of value1 and value2(inclusive).

EXAMPLE - WITH NUMERIC

Let's look at some BETWEEN condition examples using numeric values. The following numeric example uses the BETWEEN condition to retrieve values within a numeric range.

For example:

SELECT *

FROM suppliers

WHERE supplier_id BETWEEN 5000 AND 5010;

This SQL BETWEEN example would return all rows where the supplier_id is between 5000 and 5010 (inclusive). It is equivalent to the following SQL SELECT statement:

SELECT *

Page 110: Query

FROM suppliers

WHERE supplier_id >= 5000

AND supplier_id <= 5010;

EXAMPLE - WITH DATE

Next, let's look at how you would use the BETWEEN condition with Dates. The following date example uses the SQL BETWEEN condition to retrieve values within a date range.

For example:

SELECT *

FROM orders

WHERE order_date BETWEEN TO_DATE ('2003/01/01', 'yyyy/mm/dd')

AND TO_DATE ('2003/12/31', 'yyyy/mm/dd');

This SQL BETWEEN condition example would return all orders where the order_date is between Jan 1, 2003 and Dec 31, 2003 (inclusive). It would be equivalent to the following SQL SELECT statement:

SELECT *

FROM orders

WHERE order_date >= TO_DATE('2003/01/01', 'yyyy/mm/dd')

AND order_date <= TO_DATE('2003/12/31','yyyy/mm/dd');

EXAMPLE - USING NOT OPERATOR

The SQL BETWEEN condition can also be combined with the SQL NOT operator. Here is an example of how you would combine the BETWEEN condition with the NOT Operator.

For example:

SELECT *

Page 111: Query

FROM suppliers

WHERE supplier_id NOT BETWEEN 5000 AND 5500;

This SQL BETWEEN condition example would return all rows where the supplier_id was NOT between 5000 and 5500, inclusive. It would be equivalent to the following SQL SELECT statement:

SELECT *

FROM suppliers

WHERE supplier_id < 5000

OR supplier_id > 5500;

SQL: EXISTS CONDITION

Learn how to use the SQL EXISTS condition with syntax and examples.

DESCRIPTION

The SQL EXISTS condition is used in combination with a subquery and is considered to be met, if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL EXISTS condition is:

WHERE EXISTS ( subquery );

PARAMETERS OR ARGUMENTS

subquery is a SELECT statement.

NOTE

SQL Statements that use the SQL EXISTS Condition are very inefficient since the sub-query is RE-RUN for EVERY row in the outer query's table. There are more efficient ways to write most queries, that do not use the SQL EXISTS Condition.

Page 112: Query

EXAMPLE - WITH SELECT STATEMENT

Let's look at a simple example.

The following is a SQL SELECT statement that uses the SQL EXISTS condition:

SELECT *

FROM suppliers

WHERE EXISTS (SELECT *

FROM orders

WHERE suppliers.supplier_id = orders.supplier_id);

This SQL EXISTS condition example will return all records from the suppliers table where there is at least one record in the orders table with the same supplier_id.

EXAMPLE - WITH SELECT STATEMENT USING NOT EXISTS

The EXISTS condition can also be combined with the NOT operator.

For example,

SELECT *

FROM suppliers

WHERE NOT EXISTS (SELECT *

FROM orders

WHERE suppliers.supplier_id = orders.supplier_id);

This SQL EXISTS example will return all records from the suppliers table where there are no records in the orders table for the given supplier_id.

EXAMPLE - WITH INSERT STATEMENT

The following is an example of a SQL INSERT statement that uses the SQL EXISTS condition:

Page 113: Query

INSERT INTO contacts

(contact_id, contact_name)

SELECT supplier_id, supplier_name

FROM suppliers

WHERE EXISTS (SELECT *

FROM orders

WHERE suppliers.supplier_id = orders.supplier_id);

EXAMPLE - WITH UPDATE STATEMENT

The following is an example of a SQL UPDATE statement that uses the SQL EXISTS condition:

UPDATE suppliers

SET supplier_name = (SELECT customers.name

FROM customers

WHERE customers.customer_id = suppliers.supplier_id)

WHERE EXISTS (SELECT customers.name

FROM customers

WHERE customers.customer_id = suppliers.supplier_id);

EXAMPLE - WITH DELETE STATEMENT

The following is an example of a SQL DELETE statement that uses the SQL EXISTS condition:

DELETE FROM suppliers

WHERE EXISTS (SELECT *

FROM orders

Page 114: Query

WHERE suppliers.supplier_id = orders.supplier_id);

SQL: CREATE TABLE STATEMENT

Learn how to use the SQL CREATE TABLE statement with syntax, examples, and practice exercises.

DESCRIPTION

The SQL CREATE TABLE statement allows you to create and define a table.

SYNTAX

The syntax for the SQL CREATE TABLE statement is:

CREATE TABLE table_name

(

column1 datatype null/not null,

column2 datatype null/not null,

...

);

PARAMETERS OR ARGUMENTS

table_name is the name of the table that you wish to create.

column1, column2 are the columns that you wish to create in the table. Each column must have a datatype. The column should either be defined as "null" or "not null" and if this value is left blank, the database assumes "null" as the default.

EXAMPLE

Let's look at a SQL CREATE TABLE example.

CREATE TABLE suppliers

( supplier_id number(10) not null,

Page 115: Query

supplier_name varchar2(50) not null,

contact_name varchar2(50)

);

This SQL CREATE TABLE example creates a table called suppliers which has 3 columns.

The first column is called supplier_id which is created as a number datatype (maximum 10 digits in length) and can not contain null values.

The second column is called supplier_name which is a varchar2 datatype (50 maximum characters in length) and also can not contain null values.

The third column is called contact_name which is a varchar2 datatype but can contain null values.

Now the only problem with this SQL CREATE TABLE statement is that you have not defined a primary key for the table. We could modify this SQL CREATE TABLE statement and define the supplier_id as the primary key as follows:

CREATE TABLE suppliers

( supplier_id number(10) not null,

supplier_name varchar2(50) not null,

contact_name varchar2(50),

CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)

);

Learn about primary keys.

Learn about foreign keys.

PRACTICE EXERCISE #1:

Create a SQL table called customers that stores customer ID, name, and address information.

SOLUTION FOR PRACTICE EXERCISE #1:

The SQL CREATE TABLE statement for the customers table is:

Page 116: Query

CREATE TABLE customers

( customer_id number(10) not null,

customer_name varchar2(50) not null,

address varchar2(50),

city varchar2(50),

state varchar2(25),

zip_code varchar2(10)

);

PRACTICE EXERCISE #2:

Create a SQL table called customers that stores customer ID, name, and address information.

But this time, the customer ID should be the primary key for the table.

SOLUTION FOR PRACTICE EXERCISE #2:

The SQL CREATE TABLE statement for the customers table is:

CREATE TABLE customers

( customer_id number(10) not null,

customer_name varchar2(50) not null,

address varchar2(50),

city varchar2(50),

state varchar2(25),

zip_code varchar2(10),

CONSTRAINT customers_pk PRIMARY KEY (customer_id)

);

Page 117: Query

PRACTICE EXERCISE #3:

Based on the departments table below, create a SQL table called employees that stores employee number, employee name, department, and salary information. The primary key for the employees table should be the employee number. Create a foreign key on the employees table that references thedepartments table based on the department_id field.

CREATE TABLE departments

( department_id number(10) not null,

department_name varchar2(50) not null,

CONSTRAINT departments_pk PRIMARY KEY (department_id)

);

SOLUTION FOR PRACTICE EXERCISE #3:

The SQL CREATE TABLE statement for the employees table is:

CREATE TABLE employees

( employee_number number(10) not null,

employee_name varchar2(50) not null,

department_id number(10),

salary number(6),

CONSTRAINT employees_pk PRIMARY KEY (employee_number),

CONSTRAINT fk_departments

FOREIGN KEY (department_id)

REFERENCES departments(department_id)

);

SQL: CREATE TABLE AS STATEMENT

Page 118: Query

Learn how to use the SQL CREATE TABLE AS statement with syntax and examples.

DESCRIPTION

You can also use the SQL CREATE TABLE AS statement to create a table from an existing table by copying the existing table's columns.

It is important to note that when creating a table in this way, the new table will be populated with the records from the existing table (based on the  SELECT Statement ).

CREATE TABLE - BY COPYING ALL COLUMNS FROM ANOTHER TABLE

SYNTAX

The syntax for the SQL CREATE TABLE AS statement copying all of the columns is:

CREATE TABLE new_table

AS (SELECT * FROM old_table);

EXAMPLE

Let's look at an example that shows how to create a table by copying all columns from another table.

For Example:

CREATE TABLE suppliers

AS (SELECT *

FROM companies

WHERE id > 1000);

This would create a new table called suppliers that included all columns from the companies table.

If there were records in the companies table, then the new suppliers table would also contain the records selected by the SELECT statement.

Page 119: Query

CREATE TABLE - BY COPYING SELECTED COLUMNS FROM ANOTHER TABLE

SYNTAX

The syntax for the CREATE TABLE AS statement copying the selected columns is:

CREATE TABLE new_table

AS (SELECT column_1, column2, ... column_n

FROM old_table);

EXAMPLE

Let's look at an example that shows how to create a table by copying selected columns from another table.

For Example:

CREATE TABLE suppliers

AS (SELECT id, address, city, state, zip

FROM companies

WHERE id > 1000);

This would create a new table called suppliers, but the new table would only include the specified columns from the companies table.

Again, if there were records in the companies table, then the new suppliers table would also contain the records selected by the SELECT statement.

CREATE TABLE - BY COPYING SELECTED COLUMNS FROM MULTIPLE TABLES

SYNTAX

The syntax for the CREATE TABLE AS statement copying columns from multiple tables is:

CREATE TABLE new_table

Page 120: Query

AS (SELECT column_1, column2, ... column_n

FROM old_table_1, old_table_2, ... old_table_n);

EXAMPLE

Let's look at an example that shows how to create a table by copying selected columns from multiple tables.

For Example:

CREATE TABLE suppliers

AS (SELECT companies.id, companies.address, categories.cat_type

FROM companies, categories

WHERE companies.id = categories.id

AND companies.id > 1000);

This would create a new table called suppliers based on columns from both the companies and categories tables.

FREQUENTLY ASKED QUESTIONS

Question: How can I create a SQL table from another table without copying any values from the old table?

Answer: To do this, the SQL CREATE TABLE syntax is:

CREATE TABLE new_table

AS (SELECT *

FROM old_table WHERE 1=2);

For example:

CREATE TABLE suppliers

AS (SELECT *

Page 121: Query

FROM companies WHERE 1=2);

This would create a new table called suppliers that included all columns from the companies table, but no data from the companies table.

Acknowledgements: We'd like to thank Daniel W. for providing this solution!

SQL: ALTER TABLE STATEMENT

Learn how to use the SQL ALTER TABLE statement to add a column, modify a column, drop a column, rename a column or rename a table (with lots of clear, concise examples). We've also added some practice exercises that you can try for yourself.

DESCRIPTION

The SQL ALTER TABLE statement is used to add, modify, or drop/delete columns in a table. The SQL ALTER TABLE statement is also used to rename a table.

ADD COLUMN IN TABLE

SYNTAX

To add a column in a table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name

ADD column_name column-definition;

EXAMPLE

Let's look at a SQL ALTER TABLE example that adds a column.

For example:

ALTER TABLE supplier

ADD supplier_name varchar2(50);

This SQL ALTER TABLE example will add a column called supplier_name to the supplier table.

ADD MULTIPLE COLUMNS IN TABLE

Page 122: Query

SYNTAX

To add multiple columns to an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name

ADD (column_1 column-definition,

column_2 column-definition,

...

column_n column_definition);

EXAMPLE

Let's look at SQL ALTER TABLE example that adds more than one column.

For example:

ALTER TABLE supplier

ADD (supplier_name varchar2(50),

city varchar2(45));

This SQL ALTER TABLE example will add two columns, supplier_name as a varchar2(50) field and city as a varchar2(45) field to the supplier table.

MODIFY COLUMN IN TABLE

SYNTAX

To modify a column in an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name

MODIFY column_name column_type;

EXAMPLE

Let's look at SQL ALTER TABLE example that modifies a column.

Page 123: Query

For example:

ALTER TABLE supplier

MODIFY supplier_name varchar2(100) not null;

This SQL ALTER TABLE example will modify the column called supplier_name to be a data type of varchar2(100) and force the column to not allow null values.

MODIFY MULTIPLE COLUMNS IN TABLE

SYNTAX

To modify multiple columns in an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name

MODIFY (column_1 column_type,

column_2 column_type,

...

column_n column_type);

EXAMPLE

Let's look at SQL ALTER TABLE example that modifies more than one column.

For example:

ALTER TABLE supplier

MODIFY (supplier_name varchar2(100) not null,

city varchar2(75));

This SQL ALTER TABLE example will modify both the supplier_name and city columns.

DROP COLUMN IN TABLE

SYNTAX

Page 124: Query

To drop a column in an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name

DROP COLUMN column_name;

EXAMPLE

Let's look at SQL ALTER TABLE example that drops (ie: deletes) a column from a table.

For example:

ALTER TABLE supplier

DROP COLUMN supplier_name;

This SQL ALTER TABLE example will drop the column called supplier_name from the table called supplier.

RENAME COLUMN IN TABLE

SYNTAX

To rename a column in an existing table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name

RENAME COLUMN old_name to new_name;

EXAMPLE

Let's look at SQL ALTER TABLE example that renames a column in a table.

For example:

ALTER TABLE supplier

RENAME COLUMN supplier_name to sname;

This SQL ALTER TABLE example will rename the column called supplier_name to sname.

RENAME TABLE

Page 125: Query

SYNTAX

To rename a table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name

RENAME TO new_table_name;

EXAMPLE

Let's look at SQL ALTER TABLE example that renames a table.

For example:

ALTER TABLE suppliers

RENAME TO vendors;

This SQL ALTER TABLE example will rename the suppliers table to vendors.

PRACTICE EXERCISE #1:

Based on the departments table below, rename the departments table to depts.

CREATE TABLE departments

( department_id number(10) not null,

department_name varchar2(50) not null,

CONSTRAINT departments_pk PRIMARY KEY (department_id)

);

SOLUTION FOR PRACTICE EXERCISE #1:

The following SQL ALTER TABLE statement would rename the departments table to depts:

ALTER TABLE departments

RENAME TO depts;

Page 126: Query

PRACTICE EXERCISE #2:

Based on the employees table below, add a column called salary that is a number(6) datatype.

CREATE TABLE employees

( employee_number number(10) not null,

employee_name varchar2(50) not null,

department_id number(10),

CONSTRAINT employees_pk PRIMARY KEY (employee_number)

);

SOLUTION FOR PRACTICE EXERCISE #2:

The following SQL ALTER TABLE statement would add a salary column to the employees table:

ALTER TABLE employees

ADD salary number(6);

PRACTICE EXERCISE #3:

Based on the customers table below, add two columns - one column called contact_name that is a varchar2(50) datatype and one column calledlast_contacted that is a date datatype.

CREATE TABLE customers

( customer_id number(10) not null,

customer_name varchar2(50) not null,

address varchar2(50),

city varchar2(50),

state varchar2(25),

zip_code varchar2(10),

Page 127: Query

CONSTRAINT customers_pk PRIMARY KEY (customer_id)

);

SOLUTION FOR PRACTICE EXERCISE #3:

The following SQL ALTER TABLE statement would add the contact_name and last_contacted columns to the customers table:

ALTER TABLE customers

ADD (contact_name varchar2(50),

last_contacted date);

PRACTICE EXERCISE #4:

Based on the employees table below, change the employee_name column to a varchar2(75) datatype.

CREATE TABLE employees

( employee_number number(10) not null,

employee_name >varchar2(50) not null,

department_id number(10),

CONSTRAINT employees_pk PRIMARY KEY (employee_number)

);

SOLUTION FOR PRACTICE EXERCISE #4:

The following SQL ALTER TABLE statement would change the datatype for the employee_name column to varchar2(75):

ALTER TABLE employees

MODIFY employee_name varchar2(75);

PRACTICE EXERCISE #5:

Page 128: Query

Based on the customers table below, change the customer_name column to NOT allow null values and change the state column to a varchar2(2) datatype.

CREATE TABLE customers

( customer_id number(10) not null,

customer_name varchar2(50),

address varchar2(50),

city varchar2(50),

state varchar2(25),

zip_code varchar2(10),

CONSTRAINT customers_pk PRIMARY KEY (customer_id)

);

SOLUTION FOR PRACTICE EXERCISE #5:

The following SQL ALTER TABLE statement would modify the customer_name and state columns accordingly in the customers table:

ALTER TABLE customers

MODIFY (customer_name varchar2(50) not null,

state varchar2(2));

PRACTICE EXERCISE #6:

Based on the employees table below, drop the salary column.

CREATE TABLE employees

( employee_number number(10) not null,

employee_name varchar2(50) not null,

department_id number(10),

Page 129: Query

salary number(6),

CONSTRAINT employees_pk PRIMARY KEY (employee_number)

);

SOLUTION FOR PRACTICE EXERCISE #6:

The following SQL ALTER TABLE statement would drop the salary column from the employees table:

ALTER TABLE employees

DROP COLUMN salary;

PRACTICE EXERCISE #7:

Based on the departments table below, rename the department_name column to dept_name.

CREATE TABLE departments

( department_id number(10) not null,

department_name varchar2(50) not null,

CONSTRAINT departments_pk PRIMARY KEY (department_id)

);

SOLUTION FOR PRACTICE EXERCISE #7:

The following SQL ALTER TABLE statement would rename the department_name column to dept_name in the departments table:

ALTER TABLE departments

RENAME COLUMN department_name to dept_name;

SQL: DROP TABLE STATEMENT

Learn how to use the SQL DROP TABLE statement with syntax and examples.

Page 130: Query

DESCRIPTION

The SQL DROP TABLE statement allows you to remove or delete a table from the SQL database.

SYNTAX

The syntax for the SQL DROP TABLE statement is:

DROP TABLE table_name;

PARAMETERS OR ARGUMENTS

table_name is the name of the table to remove from the database.

EXAMPLE

Let's look at an example that shows how to drop a table using the SQL DROP TABLE statement.

For example:

DROP TABLE supplier;

This DROP TABLE statement example would drop the table called supplier.

SQL: GLOBAL TEMPORARY TABLES

Learn how to create SQL GLOBAL TEMORARY tables with syntax and examples.

DESCRIPTION

SQL GLOBAL TEMPORARY TABLES are tables that are created distinct within SQL sessions.

SYNTAX

The syntax for SQL CREATE GLOBAL TEMPORARY TABLE is:

CREATE GLOBAL TEMPORARY TABLE table_name

( column1 datatype null/not null,

Page 131: Query

column2 datatype null/not null,

...

);

PARAMETERS OR ARGUMENTS

table_name is the name of the global temporary table that you wish to create.

column1, column2 are the columns that you wish to create in the global temporary table. Each column must have a datatype. The column should either be defined as "null" or "not null" and if this value is left blank, the database assumes "null" as the default.

EXAMPLE

Let's look at a SQL CREATE GLOBAL TEMPORARY TABLE example:

CREATE GLOBAL TEMPORARY TABLE suppliers_temp

( supplier_id numeric(10) not null,

supplier_name varchar2(50) not null,

contact_name varchar2(50)

);

This example would create a GLOBAL TEMPORARY TABLE called suppliers_temp.

SQL: LOCAL TEMPORARY TABLES

Learn how to create SQL LOCAL TEMPORARY tables with syntax and examples.

DESCRIPTION

SQL LOCAL TEMPORARY TABLES are distinct within modules and embedded SQL programs within SQL sessions.

SYNTAX

The syntax for SQL DECLARE LOCAL TEMPORARY TABLE is:

Page 132: Query

DECLARE LOCAL TEMPORARY TABLE table_name

( column1 datatype null/not null,

column2 datatype null/not null,

...

);

PARAMETERS OR ARGUMENTS

table_name is the name of the local temporary table that you wish to create.

column1, column2 are the columns that you wish to create in the local temporary table. Each column must have a datatype. The column should either be defined as "null" or "not null" and if this value is left blank, the database assumes "null" as the default.

EXAMPLE

Let's look at a SQL DECLARE LOCAL TEMPORARY TABLE example:

DECLARE LOCAL TEMPORARY TABLE suppliers_temp

( supplier_id number(10) not null,

supplier_name varchar2(50) not null,

contact_name varchar2(50)

);

This example would create a LOCAL TEMPORARY TABLE called suppliers_temp.

SQL: VIEWS

Learn how to create, update, and drop SQL VIEWS with syntax and examples.

DESCRIPTION

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.

Page 133: Query

CREATE SQL VIEW

SYNTAX

The syntax for the SQL CREATE VIEW Statement is:

CREATE VIEW view_name AS

SELECT columns

FROM tables

WHERE conditions;

view_name is the name of the SQL VIEW that you wish to create.

EXAMPLE

Here is an example of how to use the SQL CREATE VIEW:

CREATE VIEW sup_orders AS

SELECT suppliers.supplier_id, orders.quantity, orders.price

FROM suppliers

INNER JOIN orders

ON suppliers.supplier_id = orders.supplier_id

WHERE suppliers.supplier_name = 'IBM';

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;

UPDATE SQL VIEW

You can modify the definition of a SQL VIEW without dropping it by using the SQL CREATE OR REPLACE VIEW Statement.

Page 134: Query

SYNTAX

The syntax for the SQL CREATE OR REPLACE VIEW Statement is:

CREATE OR REPLACE VIEW view_name AS

SELECT columns

FROM table

WHERE conditions;

EXAMPLE

Here is an example of how you would use the SQL CREATE OR REPLACE VIEW Statement:

CREATE or REPLACE VIEW sup_orders AS

SELECT suppliers.supplier_id, orders.quantity, orders.price

FROM suppliers

INNER JOIN orders

ON suppliers.supplier_id = orders.supplier_id

WHERE suppliers.supplier_name = 'Microsoft';

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.

DROP SQL VIEW

Once a SQL VIEW has been created, you can drop it with the SQL DROP VIEW Statement.

SYNTAX

The syntax for the SQL DROP VIEW Statement is:

DROP VIEW view_name;

view_name is the name of the view that you wish to drop.

Page 135: Query

EXAMPLE

Here is an example of how to use the SQL DROP VIEW Statement:

DROP VIEW sup_orders;

This SQL DROP VIEW example would drop/delete the SQL VIEW called sup_orders.

FREQUENTLY ASKED QUESTIONS

Question: Can you update the data in a SQL VIEW?

Answer: A VIEW in SQL is created by joining one or more tables. When you update record(s) in a view, it updates the records in the underlying tables that make up the SQL View.

So, yes, you can update the data in a SQL VIEW providing you have the proper privileges to the underlying SQL tables.

Question: Does the SQL View exist if the table is dropped from the database?

Answer: Yes, in Oracle, the SQL VIEW continues to exist even after one of the tables (that the SQL VIEW is based on) is dropped from the database. However, if you try to query the SQL VIEW after the table has been dropped, you will receive a message indicating that the SQL VIEW has errors.

If you recreate the table (the table that you had dropped), the SQL VIEW will again be fine.

SQL: CREATE TABLE AS STATEMENT

Learn how to use the SQL CREATE TABLE AS statement with syntax and examples.

DESCRIPTION

You can also use the SQL CREATE TABLE AS statement to create a table from an existing table by copying the existing table's columns.

It is important to note that when creating a table in this way, the new table will be populated with the records from the existing table (based on theSELECT Statement).

CREATE TABLE - BY COPYING ALL COLUMNS FROM ANOTHER TABLE

Page 136: Query

SYNTAX

The syntax for the SQL CREATE TABLE AS statement copying all of the columns is:

CREATE TABLE new_table

AS (SELECT * FROM old_table);

EXAMPLE

Let's look at an example that shows how to create a table by copying all columns from another table.

For Example:

CREATE TABLE suppliers

AS (SELECT *

FROM companies

WHERE id > 1000);

This would create a new table called suppliers that included all columns from the companies table.

If there were records in the companies table, then the new suppliers table would also contain the records selected by the SELECT statement.

CREATE TABLE - BY COPYING SELECTED COLUMNS FROM ANOTHER TABLE

SYNTAX

The syntax for the CREATE TABLE AS statement copying the selected columns is:

CREATE TABLE new_table

AS (SELECT column_1, column2, ... column_n

FROM old_table);

EXAMPLE

Page 137: Query

Let's look at an example that shows how to create a table by copying selected columns from another table.

For Example:

CREATE TABLE suppliers

AS (SELECT id, address, city, state, zip

FROM companies

WHERE id > 1000);

This would create a new table called suppliers, but the new table would only include the specified columns from the companies table.

Again, if there were records in the companies table, then the new suppliers table would also contain the records selected by the SELECT statement.

CREATE TABLE - BY COPYING SELECTED COLUMNS FROM MULTIPLE TABLES

SYNTAX

The syntax for the CREATE TABLE AS statement copying columns from multiple tables is:

CREATE TABLE new_table

AS (SELECT column_1, column2, ... column_n

FROM old_table_1, old_table_2, ... old_table_n);

EXAMPLE

Let's look at an example that shows how to create a table by copying selected columns from multiple tables.

For Example:

CREATE TABLE suppliers

AS (SELECT companies.id, companies.address, categories.cat_type

Page 138: Query

FROM companies, categories

WHERE companies.id = categories.id

AND companies.id > 1000);

This would create a new table called suppliers based on columns from both the companies and categories tables.

FREQUENTLY ASKED QUESTIONS

Question: How can I create a SQL table from another table without copying any values from the old table?

Answer: To do this, the SQL CREATE TABLE syntax is:

CREATE TABLE new_table

AS (SELECT *

FROM old_table WHERE 1=2);

For example:

CREATE TABLE suppliers

AS (SELECT *

FROM companies WHERE 1=2);

This would create a new table called suppliers that included all columns from the companies table, but no data from the companies table.

SQL: VIEWS

Learn how to create, update, and drop SQL VIEWS with syntax and examples.

DESCRIPTION

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.

Page 139: Query

CREATE SQL VIEW

SYNTAX

The syntax for the SQL CREATE VIEW Statement is:

CREATE VIEW view_name AS

SELECT columns

FROM tables

WHERE conditions;

view_name is the name of the SQL VIEW that you wish to create.

EXAMPLE

Here is an example of how to use the SQL CREATE VIEW:

CREATE VIEW sup_orders AS

SELECT suppliers.supplier_id, orders.quantity, orders.price

FROM suppliers

INNER JOIN orders

ON suppliers.supplier_id = orders.supplier_id

WHERE suppliers.supplier_name = 'IBM';

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;

UPDATE SQL VIEW

You can modify the definition of a SQL VIEW without dropping it by using the SQL CREATE OR REPLACE VIEW Statement.

Page 140: Query

SYNTAX

The syntax for the SQL CREATE OR REPLACE VIEW Statement is:

CREATE OR REPLACE VIEW view_name AS

SELECT columns

FROM table

WHERE conditions;

EXAMPLE

Here is an example of how you would use the SQL CREATE OR REPLACE VIEW Statement:

CREATE or REPLACE VIEW sup_orders AS

SELECT suppliers.supplier_id, orders.quantity, orders.price

FROM suppliers

INNER JOIN orders

ON suppliers.supplier_id = orders.supplier_id

WHERE suppliers.supplier_name = 'Microsoft';

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.

DROP SQL VIEW

Once a SQL VIEW has been created, you can drop it with the SQL DROP VIEW Statement.

SYNTAX

The syntax for the SQL DROP VIEW Statement is:

DROP VIEW view_name;

view_name is the name of the view that you wish to drop.

Page 141: Query

EXAMPLE

Here is an example of how to use the SQL DROP VIEW Statement:

DROP VIEW sup_orders;

This SQL DROP VIEW example would drop/delete the SQL VIEW called sup_orders.

FREQUENTLY ASKED QUESTIONS

Question: Can you update the data in a SQL VIEW?

Answer: A VIEW in SQL is created by joining one or more tables. When you update record(s) in a view, it updates the records in the underlying tables that make up the SQL View.

So, yes, you can update the data in a SQL VIEW providing you have the proper privileges to the underlying SQL tables.

Question: Does the SQL View exist if the table is dropped from the database?

Answer: Yes, in Oracle, the SQL VIEW continues to exist even after one of the tables (that the SQL VIEW is based on) is dropped from the database. However, if you try to query the SQL VIEW after the table has been dropped, you will receive a message indicating that the SQL VIEW has errors.

If you recreate the table (the table that you had dropped), the SQL VIEW will again be fine.

SQL: DATA TYPES

The following is a list of general SQL data types that may not be supported by all relational databases.

Data Type Syntax Explanation (if applicable)

integer integer  

smallint smallint  

numeric numeric(p,s) Where p is a precision value; s is a scale value. For example, numeric(6,2) is a number that has 4 digits before the decimal and 2 digits after the decimal.

Page 142: Query

decimal decimal(p,s) Where p is a precision value; s is a scale value.

real real Single-precision floating point number

double precision double precision Double-precision floating point number

float float(p) Where p is a precision value.

character char(x) Where x is the number of characters to store. This data type is space padded to fill the number of characters specified.

character varying varchar2(x) Where x is the number of characters to store. This data type does NOT space pad.

bit bit(x) Where x is the number of bits to store.

bit varying bit varying(x) Where x is the number of bits to store. The length can vary up to x.

date date Stores year, month, and day values.

time time Stores the hour, minute, and second values.

timestamp timestamp Stores year, month, day, hour, minute, and second values.

time with time zone

time with time zone

Exactly the same as time, but also stores an offset from UTC of the time specified.

timestamp with time zone

timestamp with time zone

Exactly the same as timestamp, but also stores an offset from UTC of the time specified.

year-month interval

  Contains a year value, a month value, or both.

day-time interval   Contains a day value, an hour value, a minute value, and/or a second value.

SQL SERVER (TRANSACT-SQL)

SQL Server is a relational database technology released by Microsoft.

Page 143: Query

Transact-SQL is used in SQL Server databases. Transact-SQL is closely integrated into the SQL language, yet it adds programming constructs that are not native to SQL.

We've categorized SQL Server and Transact-SQL into the following topics:

SQL SERVER (TRANSACT-SQL) FUNCTIONS

Functions - Alphabetical

SQL Server (Transact-SQL) Functions listed alphabetically

Functions - Category SQL Server (Transact-SQL) Functions listed by category

SQL SERVER PROGRAMMING

Comments within SQL How to create comments within your SQL statement

SQL SERVER QUERY TYPES

SELECT Statement Retrieve records from a table

SELECT TOP Statement

Retrieve records from a table and limit results

INSERT Statement Insert records into a table

UPDATE Statement Update records in a table

DELETE Statement Delete records from a table

DELETE TOP Statement

Delete records and limit number of deletions

SQL SERVER JOINS

JOIN TABLES Inner and Outer joins

SQL SERVER ALIASES

ALIASES Create a temporary name for a column or table

SQL SERVER CLAUSES

DISTINCT Clause Retrieve unique records

WHERE Clause Filter results

Page 144: Query

ORDER BY Clause Sort query results

GROUP BY Clause Group by one or more columns

SQL SERVER SQL FUNCTIONS

COUNT Function Return the number of rows in a query

SUM Function Return the sum of an expression

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 SERVER CONDITIONS

AND Condition 2 or more conditions to be met

OR Condition Any one of the conditions are met

AND and OR Combine 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 a NULL value

IS NOT NULL Condition

Test for a NOT NULL value

BETWEEN Condition Retrieve within a range (inclusive)

EXISTS Condition Condition is met if subquery returns at least one row

SQL SERVER (TRANSACT-SQL): FUNCTIONS - ALPHABETICAL

Below is a list of the most commonly used functions in SQL Server (Transact-SQL), sorted alphabetically.

ALPHABETICAL LISTING OF SQL SERVER FUNCTIONSABSASCII

DATEPARTDAY

RANDREPLACE

Page 145: Query

AVGCASTCEILINGCHARCHARINDEXCOALESCECONCATConcat with +CONVERTCOUNTCURRENT_TIMESTAMPCURRENT_USERDATALENGTHDATEADDDATEDIFFDATENAME

FLOORGETDATEGETUTCDATEISDATEISNULLISNUMERICLEFTLENLOWERLTRIMMAXMINMONTHNCHARNULLIFPATINDEX

RIGHTROUNDRTRIMSESSIONPROPERTYSESSION_USERSIGNSPACESTRSTUFFSUBSTRINGSUMSYSTEM_USERUPPERUSER_NAMEYEAR

SQL SERVER (TRANSACT-SQL): FUNCTIONS - CATEGORY

Below is a list of the most commonly used functions in SQL Server (Transact-SQL), sorted by Category.

STRING FUNCTIONSASCIICHARCHARINDEXCONCATConcat with +DATALENGTHLEFT

LENLOWERLTRIMNCHARPATINDEXREPLACERIGHT

RTRIMSPACESTRSTUFFSUBSTRINGUPPER

CONVERSION FUNCTIONSCAST CONVERT  

ADVANCED FUNCTIONSCOALESCECURRENT_USERISDATEISNULL

ISNUMERICNULLIFSESSIONPROPERTYSESSION_USER

SYSTEM_USERUSER_NAME

NUMERIC / MATHEMATICAL FUNCTIONS

Page 146: Query

ABSAVGCEILINGCOUNT

DATALENGTHFLOORMAXMIN

RANDROUNDSIGNSUM

DATE / TIME FUNCTIONSCURRENT_TIMESTAMPDATEADDDATEDIFFDATENAME

DATEPARTDAYGETDATEGETUTCDATE

MONTHYEAR

SQL SERVER (TRANSACT-SQL): COMMENTS WITHIN SQL

Learn how to use comments within your SQL statements in SQL Server (Transact-SQL) with syntax and examples.

DESCRIPTION

Did you know that you can place comments within your SQL statements in SQL Server (Transact-SQL)? These comments can appear on a single line or span across multiple lines. Let's look at how to do this.

SYNTAX

There are two syntaxes that you can use to create a comment within your SQL statement in SQL Server (Transact-SQL).

SYNTAX USING -- SYMBOL

The syntax for creating a SQL comment using the -- symbol in SQL Server (Transact-SQL) is:

-- comment goes here

In SQL Server, a comment started with -- symbol must be at the end of a line in your SQL statement with a line break after it. This method of commenting can only span a single line within your SQL and must be at the end of the line.

SYNTAX USING /* AND */ SYMBOLS

Page 147: Query

The syntax for creating a SQL comment using /* and */ symbols in SQL Server (Transact-SQL) is:

/* comment goes here */

In SQL Server, a comment that starts with /* symbol and ends with */ and can be anywhere in your SQL statement. This method of commenting can span several lines within your SQL.

EXAMPLE - COMMENT ON A SINGLE LINE

You can create a SQL comment on a single line in your SQL statement in SQL Server (Transact-SQL).

Let's look at a SQL comment example that shows a SQL comment on its own line:

SELECT employee_id, last_name

/* Author: TechOnTheNet.com */

FROM employees;

Here is a SQL comment that appears in the middle of the line:

SELECT /* Author: TechOnTheNet.com */ employee_id, last_name

FROM employees;

Here is a SQL comment that appears at the end of the line:

SELECT employee_id, last_name /* Author: TechOnTheNet.com */

FROM employees;

or

SELECT employee_id, last_name -- Author: TechOnTheNet.com

FROM employees;

EXAMPLE - COMMENT ON MULTIPLE LINES

Page 148: Query

In SQL Server (Transact-SQL), you can create a SQL comment that spans multiple lines in your SQL statement. For example:

SELECT employee_id, last_name

/*

* Author: TechOnTheNet.com

* Purpose: To show a comment that spans multiple lines in your SQL statement.

*/

FROM employees;

This SQL comment spans across multiple lines in SQL Server - in this example, it spans across 4 lines.

In SQL Server, you can also create a SQL comment that spans multiple lines using this syntax:

SELECT employee_id, last_name /* Author: TechOnTheNet.com

Purpose: To show a comment that spans multiple lines in your SQL statement. */

FROM employees;

SQL Server (Transact-SQL) will assume that everything after the /* symbol is a comment until it reaches the */ symbol, even if it spans multiple lines within the SQL statement. So in this example, the SQL comment will span across 2 lines.

SQL SERVER (TRANSACT-SQL): ALIASES

Learn how to use ALIASES in SQL Server (Transact-SQL) with syntax and examples.

DESCRIPTION

SQL Server (Transact-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.

Page 149: Query

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 Server (Transact-SQL) is:

column_name [ AS ] alias_name

OR

The syntax to ALIAS A TABLE in SQL Server (Transact-SQL) is:

table_name [ AS ] 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.

AS is optional. Most programmers will specify the AS keyword when aliasing a column name, but not when aliasing a table name. Whether you specify the AS keyword or not has no impact on the alias in MySQL. It is a personal choice in MySQL, unlike other databases. (Our examples will use AS when aliasing a column name but omit AS when aliasing a table name.)

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 concatenating fields together, you might alias the result.

For example:

SELECT employee_id, first_name + last_name AS NAME

Page 150: Query

FROM employees

WHERE first_name = 'Sarah';

In this example, we've aliased the second column (ie: first_name and last_name concatenated) as NAME. As a result, NAME 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 employee_id, first_name + last_name AS "NAME"

FROM employees

WHERE first_name = 'Sarah';

Next, let's look at an example where we are required to enclose the alias_name in quotes.

For example:

SELECT employee_id, first_name + last_name AS "EMPLOYEE NAME"

FROM employees

WHERE first_name = 'Sarah';

In this example, we've aliased the second column (ie: first_name and last_name concatenated) as "EMPLOYEE NAME". Since there are spaces in thisalias_name, "EMPLOYEE NAME" 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 p.product_name, inventory.quantityFROM products p

Page 151: Query

INNER JOIN inventoryON p.product_id = inventory.product_id

ORDER BY p.product_name ASC, inventory.quantity DESC;

In this example, we've created an alias for the products table called p. Now within this SQL statement, we can refer to the products table as p.

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 inventory table as well.

SELECT p.product_name, inv.quantityFROM products pINNER JOIN inventory invON p.product_id = inv.product_id

ORDER BY p.product_name ASC, inv.quantity DESC;

Now we have an alias for inventory table called inv as well as the alias for the products table called p.

Page 152: Query

Oracle: How to Create an Auto Increment Field Using SequenceIn Oracle, you can create an auto increment field using ‘sequence’ database object that can be assigned as primary keys. Using Oracle ‘sequence’ object, you can generate new values for a column. An Oracle sequence is an object like a table or a stored procedure. Examples with walkthrough explanations are provided.

Create a sequence.

Syntax:

Create sequence sequence_name start with value

increment by value

minvalue value

maxvalue value;

Let’s walk through an example.

First, let’s create an emp table with primary key constraint on emp_id column.

SQL> create table emp ( emp_id number(10),

fname varchar2(25),

lname varchar2(25),

constraint pk_emp_id PRIMARY KEY(emp_id)

);

Now let’s create a sequence.

SQL> Create sequence emp_sequence start with 1

increment by 1

minvalue 1

maxvalue 10000;

Now we have created a sequence object named emp_sequence with starting value as

1 and incrementing by 1 from 1 (minvalue) to 10000 (maxvalue).

Now let’s insert the values into emp table.

SQL> insert into emp (emp_id,fname,lname)

values(emp_sequence.nextval,'Darvin','Johnson'); SQL> insert into emp

Page 153: Query

(emp_id,fname,lname) values(emp_sequence.nextval,'Mig','Andrews');

SQL> insert into emp (emp_id,fname,lname)

values(emp_sequence.nextval,'Alex','Martin');

SQL> insert into emp (emp_id,fname,lname)

values(emp_sequence.nextval,'Jon','paul');

SQL> insert into emp (emp_id,fname,lname)

values(emp_sequence.nextval,'Yatin','Bones');

In emp_sequence.nextval where emp_sequence is the name of sequence we

created above andnextval is a function that is used to assign the next number

from emp_sequence to emp_id column inemp table.

Now let’s see the emp table.

SQL> select * from emp;

EMP_ID FNAME LNAME

---------- ------------------------- -------------------------

1 Darvin Johnson

2 Mig Andrews

3 Alex Martin

4 Jon paul

5 Yatin Bones

Now you can see using ‘sequence’ the emp_id column has auto incremented values

from 1 to 5.