SQL Queries
SQL Queries
SQL Queries
Now, let's say you want to see the address of each employee. Use the SELECT
statement, like so:
To get all columns of a table without typing all column names, use:
Let's say that you want to list the ID and names of only those people who have sold
an antique. Obviously, you want a list where each seller is only listed once--you
don't want to know how many antiques a person sold, just the fact that this person
sold one. This means that you will need to tell SQL to eliminate duplicate sales
rows, and just list each person only once. To do this, use the DISTINCT keyword.
To throw in one more twist, we will also want the list alphabetized by LastName,
then by FirstName (on a LastName tie). Thus, we will use the ORDER BY clause:
In this section, we will talk about Aliases, In and the use of subqueries, and how
these can be used in a 3-table example. First, look at this query which prints the
last name of those owners who have placed an order and what the order is, only
listing those orders which can be filled (that is, there is a buyer who owns that
ordered item):
This gives:
Last Name Item Ordered
--------- ------------
Smith Table
Smith Desk
Akins Chair
Lawson Mirror
I will discuss five important aggregate functions: SUM, AVG, MAX, MIN, and COUNT.
They are called aggregate functions because they summarize the results of a
3
This query shows the total of all salaries in the table, and the average salary of all
of the entries in the table.
This query gives the smallest figure of the Benefits column, of the employees who
are Managers, which is 12500.
This query tells you how many employees have Staff status (3).
(5) Views
In SQL, you might (check your DBA) have access to create views for yourself. What
a view does is to allow you to assign the results of a query to a new, personal
table, that you can use in other queries, where this new table is given the view
name in your FROM clause. When you access a view, the query that is defined in
your view creation statement is performed (generally), and the results of that
query look just like another table in the query that you wrote invoking the view.
Now, write a query using this view as a table, where the table is just a listing of all
Items Desired from the Orders table:
This query shows all SellerID's from the Antiques table where the Item in that table
happens to appear in the Antview view, which is just all of the Items Desired in the
Orders table. The listing is generated by going through the Antique Items one-by-
one until there's a match with the Antview view. Views can be used to restrict
database access, as well as, in this case, simplify a complex query.
All tables within a database must be created at some point in time...let's see how
we would create the Orders table:
Let's add a column to the Antiques table to allow the entry of the price of a given
Item:
The data for this new column can be updated or inserted as shown later.
This inserts the data into the table, as a new row, column-by-column, in the pre-
defined order. Instead, let's change the order and leave Price blank:
INSERT INTO ANTIQUES (BUYERID, SELLERID, ITEM) VALUES (01, 21, 'Ottoman');
But if there is another row that contains 'Ottoman', that row will be deleted also.
Let's delete all rows (one, in this case) that contain the specific data we added
before:
Let's update a Price into a row that doesn't have a price listed yet:
This sets all Chair's Prices to 500.00. As shown above, more WHERE conditionals,
using AND, must be used to limit the updating to more specific rows. Also,
additional columns may be set by separating equal statements with commas.
Joins
A join is a query that combines rows from two or more tables, views, or
materialized views. Oracle performs a join whenever multiple tables
appear in the queries FROM clause. The query's select list can select any
columns from any of these tables. If any two of these tables have a column
name in common, you must qualify all references to these columns
throughout the query with table names to avoid ambiguity.
Join Conditions
Most join queries contain WHERE clause conditions that compare two
columns, each from a different table. Such a condition is called a join
condition. To execute a join, Oracle combines pairs of rows, each
containing one row from each table, for which the join condition evaluates
to TRUE. The columns in the join conditions need not also appear in the
select list.
Equijoins
select emp.empno,emp.ename,emp.sal,emp.deptno,dept.dname,dept.city
from emp,dept where emp.deptno=dept.deptno;
The above query can also be written like, using aliases, given below.
The above query can also be written like given below without using table
qualifiers.
select empno, ename, sal, dname, city from emp, dept where
emp.deptno=dept.deptno;
And if you want to see all the columns of both tables then the query can
be written like this.
Non equi joins is used to return result from two or more tables where exact
join is not possible.
For example we have emp table and salgrade table. The salgrade table
contains grade and their low salary and high salary. Suppose you want to
find the grade of employees based on their salaries then you can use NON
EQUI join.
Self Joins
A self join is a join of a table to itself. This table appears twice in the
FROM clause and is followed by table aliases that qualify column names in
the join condition. To perform a self join, Oracle combines and returns rows
of the table that satisfy the join condition.
For example the following query returns employee names and their
manager names for whom they are working.
7
Inner Join
Outer Joins
An outer join extends the result of a simple join. An outer join returns all
rows that satisfy the join condition and also returns some or all of those
rows from one table for which no rows from the other satisfy the join
condition.
To write a query that performs an outer join of tables A and B and returns
all rows from A (a left outer join), use the ANSI LEFT [OUTER] JOIN
syntax, or apply the outer join operator (+) to all columns of B in the join
condition. For all rows in A that have no matching rows in B, Oracle returns
null for any select list expressions containing columns of B.
To write a query that performs an outer join of tables A and B and returns
all rows from B (a right outer join), use the ANSI RIGHT [OUTER] syntax,
or apply the outer join operator (+) to all columns of A in the join
condition. For all rows in B that have no matching rows in A, Oracle returns
null for any select list expressions containing columns of A.
To write a query that performs an outer join and and returns all rows from
A and B, extended with nulls if they do not satisfy the join condition (a full
outer join), use the ANSI FULL [OUTER] JOIN syntax.
For example the following query returns all the employees and department
names and even those department names where no employee is working
for Left Outer Join.
SQL Operators
SQL Operators Overview
8
Arithmetic Operators
Character Operators
Character Operators
Operat
or Description Example
|| Concatenates SELECT 'The Name of the employee is: ' ||
character strings ENAME FROM EMP;
With Oracle Lite, you can concatenate character strings with the following
results:
Concatenating two character strings results in another character string.
SELECT CONCAT (CONCAT (ENAME, ' is a '),job) FROM EMP WHERE SAL >
2000;
This returns:
CONCAT(CONCAT(ENAME
-------------------------
KING is a PRESIDENT
BLAKE is a MANAGER
CLARK is a MANAGER
JONES is a MANAGER
FORD is a ANALYST
SCOTT is a ANALYST
6 rows selected.
Comparison Operators
10
Logical Operators
Operat
or Description Example
OR Returns TRUE if either component SELECT * FROM emp
condition is TRUE. Returns FALSE if WHERE job='CLERK' OR
both are FALSE. Otherwise, returns deptno=10
UNKNOWN.
Set Operators
Set operators combine the results of two queries into a single result.
Note: :
The syntax for INTERSECT ALL is supported, but it returns
the same results as INTERSECT.
13
Other Operators
Database Triggers
Till oracle 7.0 only 12 triggers could be associated with a given table, but
in higher versions of Oracle there is no such limitation. A database trigger
fires with the privileges of owner not that of user
A triggering event
A trigger constraint (Optional)
Trigger action
A triggering event can be an insert, update, or delete statement or an
instance shutdown or startup etc. The trigger fires automatically when any
of these events occur a trigger constraint specifies a Boolean expression
that must be true for the trigger to fire. This condition is specified using
the WHEN clause. The trigger action is a procedure that contains the code
to be executed when the trigger fires.
Types of Triggers
A Row trigger fires once for each row affected. It uses FOR EACH ROW
clause. They are useful if trigger action depends on number of rows
affected.
While defining the trigger we can specify whether to perform the trigger
action (i.e. execute trigger body) before or after the triggering statement.
BEFORE and AFTER triggers fired by DML statements can only be defined
on tables.
BEFORE triggers The trigger action here is run before the trigger
statement.
AFTER triggers The trigger action here is run after the trigger statement.
15
LOGON triggers fires after successful logon by the user and LOGOFF
trigger fires at the start of user logoff.
Points to ponder
PL/SQL subprograms
They allow you to write PL/SQL program that meet our need
They allow you to break the program into manageable modules.
They provide reusability and maintainability for the code.
18
Procedures
Example
BEGIN
PROC1; --- PROC1 is name of the procedure.
END;
/
TOO_MANY_ROWS When a select query returns more than one row and
the destination variable can take only single value.
EXCEPTION
User-defined Exceptions
Declaring Exception:
DECLARE
myexception EXCEPTION;
BEGIN
------
Raising Exception:
BEGIN
RAISE myexception;
-------
Handling Exception:
BEGIN
------
----
EXCEPTION
WHEN myexception THEN
Statements;
END;
25
Points To Ponder:
RAISE_APPLICATION_ERROR
To display your own error messages one can use the built-in
RAISE_APPLICATION_ERROR. They display the error message in the same
way as Oracle errors. You should use a negative number between 20000
to 20999 for the error_number and the error message should not exceed
512 characters.
The syntax to call raise_application_error is
RAISE_APPLICATION_ERROR (error_number, error_message, { TRUE
| FALSE });
26