SQL Material
SQL Material
SQL Material
Data Type
integer
smallint
numeric
Syntax
integer
smallint
numeric(p,s)
Example #1
Let's take a look at how to select all fields from a table.
SELECT *
FROM supplier
WHERE city = 'Newark';
In our example, we've used * to signify that we wish to view all fields from the supplier table where the
supplier resides in Newark.
Example #2
You can also choose to select individual fields as opposed to all fields in the table.
For example:
SELECT name, city, state
FROM supplier
WHERE supplier_id > 1000;
This select statement would return all name, city, and state values from the supplier table where the
supplier_id value is greater than 1000.
Example #3
You can also use the select statement to retrieve fields from multiple tables.
SELECT orders.order_id, supplier.name
FROM supplier, orders
WHERE supplier.supplier_id = orders.supplier_id;
The result set would display the order_id and suppier name fields where the supplier_id value existed in
both the supplier and orders table.
Example #1
Let's take a look at a very simple example.
SELECT DISTINCT city
FROM supplier;
This SQL statement would return all unique cities from the supplier table.
Example #2
The DISTINCT clause can be used with more than one field.
For example:
SELECT DISTINCT city, state
FROM supplier;
This select statement would return each unique city and state combination. In this case, the distinct applies
to each field listed after the DISTINCT keyword.
Note:
The COUNT function will only count those records in which the field in the brackets is NOT NULL.
For example, if you have the following table called Suppliers:
Supplier_ID
1
2
3
Supplier_Name
IBM
Microsoft
NVidia
State
CA
While the result for the next query will only return 1, since there is only one row in the Suppliers table where
the State field is NOT NULL.
Select COUNT(State) From Suppliers;
Simple Example
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 example, we've aliased the count(*) field as "Number of employees". As a result, "Number of
employees" will display as the field name when the result set is returned.
Simple Example
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 example, we've aliased the sum(salary) field as "Total Salary". As a result, "Total Salary" will display
as the field name when the result set is returned.
If there were two salaries of $30,000/year, only one of these values would be used in the SUM function.
You might also want to perform a mathematical operation within a SUM function. For example, you might
determine total commission as 10% of total sales.
SELECT SUM(sales * 0.10) as "Commission"
FROM order_details;
Simple Example
For example, you might wish to know the minimum salary of all employees.
SELECT MIN(salary) as "Lowest salary"
FROM employees;
In this 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.
Simple Example
For example, you might wish to know the maximum salary of all employees.
SELECT MAX(salary) as "Highest salary"
FROM employees;
In this 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.
For example, you could also use 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;
Because you have listed one column in your SELECT statement that is not encapsulated in the MAX
function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP
BY section.
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, 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-JUL03, 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 statement below will return the results that
you want:
SELECT rh.user_name, rh.report_name, rh.report_run_date
FROM report_history rh,
(SELECT max(report_run_date) as maxdate, report_name
FROM report_history
GROUP BY report_name) maxresults
WHERE rh.report_name = maxresults.report_name
AND rh.report_run_date= maxresults.maxdate;
Let's take a few moments to explain what we've done.
First, we've aliased the first instance of the report_history table as rh.
Second, we've included two components in our FROM clause. The first is the table called report_history
(aliased as rh). The second is a select statement:
(SELECT max(report_run_date) as maxdate, report_name
FROM report_history
GROUP BY report_name) maxresults
We've aliased the max(report_run_date) as maxdate and we've aliased the entire result set as maxresults.
Now, that we've created this select statement within our FROM clause, Oracle will let us join these results
against our original report_history table. So we've joined the report_name and report_run_date fields
between the tables called rh and maxresults. This allows us to retrieve the report_name,
max(report_run_date) as well as the user_name.
Question: I need help in an SQL query. I have a table in Oracle called orders which has the following fields:
order_no, customer, and amount.
I need a query that will return the customer who has ordered the highest total amount.
Answer: The following SQL should return the customer with the highest total amount in the orders table.
select query1.* from
(SELECT customer, Sum(orders.amount) AS total_amt
FROM orders
GROUP BY orders.customer) query1,
(select max(query2.total_amt) as highest_amt
from (SELECT customer, Sum(orders.amount) AS total_amt
FROM orders
GROUP BY orders.customer) query2) query3
where query1.total_amt = query3.highest_amt;
This SQL 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 should work:
SELECT Name, Score
FROM Scoring
WHERE Score = (select Max(Score) from Scoring);
It is difficult to explain the basic syntax for the WHERE clause, so instead, we'll take a look at some
examples.
Example #1
SELECT *
FROM supplier
WHERE supplier_name = 'IBM';
In this first example, we've used the WHERE clause to filter our results from the supplier table. The SQL
statement above would return all rows from the supplier table where the supplier_name is IBM. Because the
* is used in the select, all fields from the supplier table would appear in the result set.
Example #2
SELECT supplier_id
FROM supplier
WHERE supplier_name = 'IBM'
or supplier_city = 'Newark';
We can define a WHERE clause with multiple conditions. This SQL statement would return all supplier_id
values where the supplier_name is IBM or the supplier_city is Newark.
Example #3
SELECT supplier.suppler_name, orders.order_id
FROM supplier, orders
WHERE supplier.supplier_id = orders.supplier_id
and supplier.supplier_city = 'Atlantic City';
We can also use the 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 supplier
and orders tables based on supplier_id, and where the supplier_city is Atlantic City.
The AND condition requires that each condition be must be met for the record to be included in the result
set. In this case, column1 has to equal 'value1' and column2 has to equal 'value2'.
Example #1
The first example that we'll take a look at involves a very simple example using the AND condition.
SELECT *
FROM supplier
WHERE city = 'New York'
and type = 'PC Manufacturer';
This would return all suppliers that reside in New York and are PC Manufacturers. Because the * is used in
the select, all fields from the supplier table would appear in the result set.
Example #2
Our next example demonstrates how the AND condition can be used to "join" multiple tables in an SQL
statement.
SELECT order.order_id, supplier.supplier_name
FROM supplier, order
WHERE supplier.supplier_id = order.supplier_id
and supplier.supplier_name = 'IBM';
This would return all rows where the supplier_name is IBM. And the supplier and order tables are joined on
supplier_id. You will notice that all of the fields are prefixed with the table names (ie: order.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 supplier and order 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 #1
The first example that we'll take a look at involves a very simple example using the OR condition.
SELECT *
FROM supplier
WHERE city = 'New York'
or city = 'Newark';
This would return all suppliers that reside in either New York or Newark. Because the * is used in the select,
all fields from the supplier table would appear in the result set.
Example #2
The next example takes a look at three conditions. If any of these conditions is met, the record will be
included in the result set.
For example:
SELECT supplier_id
FROM supplier
WHERE name = 'IBM'
or name = 'Hewlett Packard'
or name = 'Gateway';
This SQL statement would return all supplier_id values where the supplier's name is either IBM, Hewlett
Packard or Gateway.
Example #1
The first example that we'll take a look at an example that combines the AND and OR conditions.
SELECT *
FROM supplier
WHERE (city = 'New York' and name = 'IBM')
or (city = 'Newark');
This would return all suppliers that reside in either New York whose name is IBM, all supplies that reside in
Newark. The brackets determine what order the AND and OR conditions are evaluated in.
Example #2
The next example takes a look at a more complex statement.
For example:
SELECT supplier_id
FROM supplier
WHERE (name = 'IBM')
or (name = 'Hewlett Packard' and city = 'Atlantic City')
or (name = 'Gateway' and status = 'Active' and city = 'Burma');
This SQL 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 and the city is Burma.
You can also using the wildcard multiple times within the same string. For example,
SELECT * FROM supplier
WHERE supplier_name like '%bob%';
In this example, we are looking for all suppliers whose name contains the characters 'bob'.
You could also use the LIKE condition to find suppliers whose name does not start with 'T'. For example,
SELECT * FROM supplier
WHERE supplier_name not like 'T%';
By placing the not keyword in front of the LIKE condition, you are able to retrieve all suppliers whose name
does not start with 'T'.
This SQL statement identifies the ! character as an escape character. This statement will return all suppliers
whose name is %.
You can also use the Escape character with the _ character. For example,
SELECT * FROM supplier
WHERE supplier_name LIKE 'H%!_' escape '!';
This example returns all suppliers whose name starts with H and ends in _. For example, it would return a
value such as 'Hello_'.
Example #1
The following is an SQL statement that uses the IN function:
SELECT *
FROM supplier
WHERE supplier_name in ( 'IBM', 'Hewlett Packard', 'Microsoft');
This 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 supplier table would appear in the result set.
It is equivalent to the following statement:
SELECT *
FROM supplier
Example #2
You can also use the IN function with numeric values.
SELECT *
FROM orders
WHERE order_id in (10000, 10001, 10003, 10005);
This SQL statement would return all orders where the order_id is either 10000, 10001, 10003, or 10005.
It is equivalent to the following statement:
SELECT *
FROM orders
WHERE order_id = 10000
OR order_id = 10001
OR order_id = 10003
OR order_id = 10005;
This SQL statement will return the records where column1 is within the range of value1 and value2
(inclusive). The BETWEEN function can be used in any valid SQL statement - select, insert, update, or
delete.
Example #1 - Numbers
The following is an SQL statement that uses the BETWEEN function:
SELECT *
FROM suppliers
WHERE supplier_id between 5000 AND 5010;
This would return all rows where the supplier_id is between 5000 and 5010, inclusive. It is equivalent to the
following SQL statement:
SELECT *
FROM suppliers
WHERE supplier_id >= 5000
AND supplier_id <= 5010;
Example #2 - Dates
You can also use the BETWEEN function with dates.
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 statement 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 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 #1
Let's take a look at a simple example. The following is an SQL statement that uses the EXISTS condition:
SELECT *
FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);
This select statement will return all records from the suppliers table where there is at least one record in the
orders table with the same supplier_id.
( SELECT customer.name
FROM customers
WHERE customers.customer_id = supplier.supplier_id)
WHERE EXISTS
( SELECT customer.name
FROM customers
WHERE customers.customer_id = supplier.supplier_id);e following is an example of an update statement
that utilizes the EXISTS condition:
Example #1
SELECT supplier_city
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city;
This would return all records sorted by the supplier_city field in ascending order.
Example #2
SELECT supplier_city
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC;
This would return all records sorted by the supplier_city field in descending order.
Example #3
You can also 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.
SELECT supplier_city
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY 1 DESC;
This 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.
Example #4
SELECT supplier_city, supplier_state
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC, supplier_state ASC;
This would return all records sorted by the supplier_city field in descending order, with a secondary sort by
supplier_state in ascending order.
Example #1
The following is an example of a UNION query:
select supplier_id
from suppliers
UNION
select supplier_id
from orders;
In this example, if a supplier_id appeared in both the suppliers and orders table, it would appear once in
your result set. The UNION removes duplicates.
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 >=
trun(sysdate-13).
Answer: Since you are using the COUNT function which is an aggregate function, we'd recommend using a
UNION query. 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)
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 UNION query allows you to perform a COUNT based on one set of criteria.
Example #1
The following is an example of a UNION ALL query:
select supplier_id
from suppliers
UNION ALL
select supplier_id
from orders;
If a supplier_id appeared in both the suppliers and orders table, it would appear multiple times in your result
set. The UNION ALL does not remove duplicates.
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.
Example #1
The following is an example of an INTERSECT query:
select supplier_id
from suppliers
INTERSECT
select supplier_id
from orders;
In this example, if a supplier_id appeared in both the suppliers and orders table, it would appear in your
result set.
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.
Example #1
The following is an example of an MINUS query:
select supplier_id
from suppliers
MINUS
select supplier_id
from orders;
In this example, the SQL would return 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.
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.
( SELECT customer.name
FROM customers
WHERE customers.customer_id = supplier.supplier_id)
WHERE EXISTS
( SELECT customer.name
FROM customers
WHERE customers.customer_id = supplier.supplier_id);
Whenever a supplier_id matched a customer_id value, the supplier_name would be overwritten to the
customer name from the customers table.
Question: I am setting up a database with clients. I know that you use the "insert" statement to insert
information in the database, but how do I make sure that I do not enter the same client information again?
Answer: You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following
statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
This statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following 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.
SELECT count(*)
FROM supplier
WHERE supplier_name = 'IBM';
Question: How would I write an SQL 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:
DELETE FROM TableA
WHERE NOT EXISTS
( select *
from TableB
where TableA .field1 = TableB.fieldx
and TableA .field2 = TableB.fieldz );
SQL: Joins
A join is used to combine rows from multiple tables. A join is performed whenever two or more tables is
listed in the FROM clause of an SQL statement.
There are different kinds of joins. Let's take a look at a few examples.
supplier_name
10000
IBM
10001
Hewlett Packard
10002
Microsoft
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
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.
Outer Join
Another type of join is called an outer join. This type of join returns all rows from one table and only those
rows from a secondary table where the joined fields are equal (join condition is met).
For example,
select suppliers.supplier_id, suppliers.supplier_name, orders.order_date
from suppliers, orders
where suppliers.supplier_id = orders.supplier_id(+);
This SQL statement would return all rows from the suppliers table and only those rows from the orders table
where the joined fields are equal.
The (+) after the orders.supplier_id field indicates that, 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.
The above SQL statement could also be written as follows:
select suppliers.supplier_id, suppliers.supplier_name, orders.order_date
from suppliers, orders
where orders.supplier_id(+) = suppliers.supplier_id
supplier_name
10000
IBM
10001
Hewlett Packard
10002
Microsoft
10003
Nvidia
We have a second table called orders with three fields (order_id, supplier_id, and order_date).
It contains the following data:
order_id
supplier_id
order_date
500125
10000
2003/05/12
500126
10001
2003/05/13
supplier_name
order_date
10000
IBM
2003/05/12
10001
Hewlett Packard
2003/05/13
10002
Microsoft
<null>
10003
Nvidia
<null>
The rows for Microsoft and Nvidia would be included because an outer join was used. However, you will
notice that the order_date field for those records contains a <null> value.
For example:
CREATE TABLE supplier
( supplier_id
numeric(10)
supplier_name varchar2(50)
contact_name varchar2(50)
)
not null,
not null,
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.
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.
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.
Syntax #2
To add multiple columns to an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name
ADD ( column_1 column-definition,
column_2 column-definition,
...
column_n column_definition );
For example:
ALTER TABLE supplier
ADD ( supplier_name varchar2(50),
city
varchar2(45) );
This will add two columns (supplier_name and city) to the supplier table.
not null;
This will modify the column called supplier_name to be a data type of varchar2(100) and force the column to
not allow null values.
Syntax #2
To modify multiple columns in an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name
MODIFY ( column_1 column_type,
column_2 column_type,
...
column_n column_type );
For example:
ALTER TABLE supplier
MODIFY ( supplier_name
varchar2(100)
not null,
city
varchar2(75)
);
For example:
DROP TABLE supplier;
This would drop table called supplier.