THE STRUCTURED QUERY LANGUAGE: SQL SELECT: Selects rows and columns from one or more tables. May embedded in other SQL commands. The Structured Query Language SQL is the ANSI standard language for manipulating relational databases. It is : n Easy to learn, understand and use by professional programmers and by non- technical experts too. n Assertive or non-procedural. n A complete language to manage the database; it is at the same time a Query language Data Definition Language Data Manipulation Language Data Control Language This document explains the Query Language ( SELECT command). It uses the following Oracle sample database. Table: EMP EMPNO ENAME JOB MGR# HIREDATE SAL COMM DEPTNO# 7369 SMITH CLERK 7902 17-DEC-80 800 20 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 7566 JONES MANAGER 7839 02-APR-81 2975 20 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7782 CLARK MANAGER 7839 09-JUN-81 2450 10 7788 SCOTT ANALYST 7566 09-DEC-82 3000 20 7839 KING PRESIDENT 17-NOV-81 5000 10 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 7876 ADAMS CLERK 7788 12-JAN-83 1100 20 7900 JAMES CLERK 7698 03-DEC-81 950 30 7902 FORD ANALYST 7566 03-DEC-81 3000 20 7934 MILLER CLERK 7782 23-JAN-82 1300 10 Table: DEPT DEPTNO DNAME LOC 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON Table : SALGRADE
29
Embed
INTRODUCTION TO 4GL and ORACLE … SELEC… · Web viewINTRODUCTION TO 4GL and ORACLE PRESENTATIONُ Subject: 4GL COURSE chapitre 1 Last modified by: Jamel-Feki Company: People
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
THE STRUCTURED QUERY LANGUAGE: SQL
SELECT: Selects rows and columns from one
or more tables. May embedded in other SQL
commands.
The Structured Query Language SQL is the ANSI standard language for manipulating relational databases. It is :
n Easy to learn, understand and use by professional programmers and by non-technical experts too.n Assertive or non-procedural.n A complete language to manage the database; it is at the same time a
� Query language� Data Definition Language� Data Manipulation Language� Data Control Language
This document explains the Query Language ( SELECT command). It uses the following Oracle sample database.
Table: EMP
EMPNO ENAME JOB MGR# HIREDATE SAL COMM DEPTNO#7369 SMITH CLERK 7902 17-DEC-80 800 207499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 307521 WARD SALESMAN 7698 22-FEB-81 1250 500 307566 JONES MANAGER 7839 02-APR-81 2975 207654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 307698 BLAKE MANAGER 7839 01-MAY-81 2850 307782 CLARK MANAGER 7839 09-JUN-81 2450 107788 SCOTT ANALYST 7566 09-DEC-82 3000 207839 KING PRESIDENT 17-NOV-81 5000 107844 TURNER SALESMAN 7698 08-SEP-81 1500 0 307876 ADAMS CLERK 7788 12-JAN-83 1100 207900 JAMES CLERK 7698 03-DEC-81 950 307902 FORD ANALYST 7566 03-DEC-81 3000 207934 MILLER CLERK 7782 23-JAN-82 1300 10
Table: DEPT
DEPTNO DNAME LOC10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON
select columns select rows join tables sort the result use built-in functions (row functions and aggregate functions) treat the NULL values connect records in a tree
A complete syntax is given in the last page of the current document.
The SELECT indicates the list of information we want to obtain in the result. This list is a combination of :
� When the WHERE clause is absent, the SFW becomes as the algebraic PROJECTION.
� Beware! The result of a SFW query may contain redundant tuples (records). To eliminate the redundancy we should use the UNIQUE (or its synonym DISTINCT) option.Look at the difference. The query
SELECT DEPTNO SELECT UNIQUE DEPTNOFROM EMP; FROM EMP;
whereasreturns 10 20 10 30 20 10 returns 10 20 30
The UNIQUE eliminates redundant rows in the result.
THE COMPARISON OPERATORS
The WHERE clause may use the following operators:
= equal!= different> greater than>= greater or equal< less than<= less or equal
BETWEEN ..AND.. within a scope[NOT] IN : [not] belong
LIKE resembles
IS NULL undefined value (empty field)
IS NOT NULL Not undefined (defined or known) value
{ =| != | > | < | >= | <= } ANY at least one ...
{ =| != | > | < | >= | <= } ALL all ...(each element)
EXAMPLES
DISPLAY THE NAME, SALARY and COMMISSION FOR EMPLOYEES HAVING A COMMISSION GREATER
THAN THE SALARY.
SELECT ENAME, SAL, COMMFROM EMPWHERECOMM > SAL;
GET THE NAME AND THE SALARY FOR EMPLOYEES HAVING A SALARY BETWEEN 1200 AND 1300
(limits included).
SELECT ENAME, SALFROM EMPWHERE SAL BETWEEN 1200 AND 1300 ;
The IN operator
It enables to compare one value with a set of values.
GET EMPLOYEE NUMBER, NAME AND SALARY FOR ALL 'CLERK' OR 'ANALYST'.
The trivial method - but not the best - is to compute the Cartesian product then to apply a selection on it (since the Cartesian product consists of all possible combinations of the two tables' rows).
Because the Cartesian product costs too much, SQL will process otherwise beginning by reducing the number of rows to be joined.
It is sometimes useful to join a given table to itself in the purpose to obtain on the same row some attributes coming from one row and others coming from another row of the same table.
EXAMPLES
GET THE NAME OF THE BOSS OF THE EMPLOYEE 'FORD'.
Since each row of the table EMP has a column MGR (manager number), and since this attribute is defined on the same domain with EMPNO, it will be possible to find for any employee the name of his/her manager. This needs to join the table EMP to itself.
ENAME------------JONESF This example involves a join of table EMP with itself; the join condition is that the manager number of the selected
employee (FORD) is equal to the employee number in another row.Table EMP appears twice in the FROM clause. To distinguish between the two appearances, we introduce arbitrary the
synonym BOSS and use it as a qualifier in the SELECT and WHERE clauses.
FIND ALL EMPLOYEES HAVING A SALARY MORE THAN JONES.
Note that persons without cars will not appear in the result (respectively cars without owners); this occurs because there is no corresponding rows for such records.
Result of the first SELECT Result of the second SELECT
EMPNO ENAME SAL COMM DEPTNO EMPNO ENAME SAL COMM DEPTNO7369 SMITH 800 20 7499 ALLEN 1600 300 307521 WARD 1250 500 30 7521 WARD 1250 500 307654 MARTIN 1250 1400 30 7654 MARTIN 1250 1400 307876 ADAMS 1100 20 7844 TURNER 1500 0 307900 JAMES 950 307934 MILLER 1300 10
ß ß union
of the two results
ßEMPNO ENAME SAL COMM DEPTNO
7369 SMITH 800 207521 WARD 1250 500 307654 MARTIN 1250 1400 307876 ADAMS 1100 207900 JAMES 950 307934 MILLER 1300 107499 ALLEN 1600 300 307844 TURNER 1500 0 30
Rule1: The two SELECTs must have the same number of columns. These columns must match in types.
Rule2: No redundant rows in the result (since the result is a set in mathematics meaning).
Think:
Write down the above query otherwise?
Look at this example:
SELECT ENAME NAME, 'SAL' TYPE, SAL AMOUNTFROM EMPWHERECOMM IS NOT NULLUNIONSELECT ENAME ,'COMM' , COMMFROM EMPWHERECOMM IS NOT NULL;
Note that the UNION is used to split on many rows data coming from the same record.
NAME TYPE AMOUNT------------ ------------ -------------ALLEN COMM 300ALLEN SAL 1600MARTIN COMM 1400MARTIN SAL 1250TURNER COMM 0TURNER SAL 1500WARD COMM 500
FROM EMPWHERE SAL < 1500INTERSECTSELECT EMPNO , ENAME ,SAL, COMM, DEPTNOFROM EMPWHERE COMM IS NOT NULL;
Result of the first SELECT Result of the second SELECT
EMPNO ENAME SAL COMM DEPTNO EMPNO ENAME SAL COMM DEPTNO7369 SMITH 800 20 7499 ALLEN 1600 300 307521 WARD 1250 500 30 7521 WARD 1250 500 307654 MARTIN 1250 1400 30 7654 MARTIN 1250 1400 307876 ADAMS 1100 20 7844 TURNER 1500 0 307900 JAMES 950 307934 MILLER 1300 10
ß ß
intersect of the two results
ß EMPNO ENAME SAL COMM DEPTNO7521 WARD 1250 500 307654 MARTIN 1250 1400 30
SELECT ENAME , JOB, SAL FROM EMP WHERE JOB ='MANAGER'INTERSECTSELECT ENAME , JOB, SAL FROM EMP WHERE SAL >= 2000;
Could you write this query without using the INTERSECT operator ?
NESTED QUERIES
Nested queries are queries within queries. This occurs when the WHERE clause of a given SFW block contains itself a sub query (SFW command ). The sub query ( or inner query/block) :
o May return only one column.o is able to return data from one row or several.o is typical coded as part of a predicate containing =, which is used when it returns a single value, or IN when it
returns several values.o often can be used as a substitute for a join when we want to extract columns from a single table.
o simple nested queries : the inner query is independent - from the outer query - in the sense that it is completely processed before using its result within the outer block.
o correlated (synchronized) queries: the inner query and the outer one have an inter-block reference so that the inner subselect must be processed more than once.
General form
SELECT ..........
FROM table-name
WHEREcol operator ( SELECT .....
FROM table-name
WHERE ...);
F Sub query empty Þ error.
SIMPLE NESTED QUERIES
EXAMPLE
DISPLAY NAME , SALARY , JOB FOR EMPLOYEES HAVING A SALARY > JONES ' SALARY.
SELECT ENAME , SAL , JOB ¬outer queryFROM EMPWHERESAL > ( SELECT SAL ¬inner query
Note that :o The sub query is independent with the outer query.o Oracle ( RDBMS) evaluates the whole sub query, then the outer query using the obtained result.
Think
Could you write the query otherwise (without nested blocks) ?
When the sub query may return more than one row, we must use the operators able to compare one value to a set of values:
IN{ = | != | > | >= | < | <= | } { ANY | ALL }
as expression < ANY sub queryor expression < ALL sub query
When < is used with ALL, it means the sub query will return several values, and the expression's value should be smaller than all of those values.If the statement is of the form expression <ANY sub query, the value of the expression should be less than at least one of the returned values. The other operators ( >, = , ... ) work in a similar manner.
EXAMPLE
DISPLAY NAME , SAL FOR EMPLOYEES EARNING MORE THAN ALL EMPLOYEES IN THE DEPT. 30.
SELECT ENAME, SALFROM EMPWHERE SAL > ALL ( SELECT SAL
DISPLAY NAME , JOB, SAL FOR EMPLOYEES HAVING THE SAME JOB AS 'JONES' OR EARNING MORE THAN 'FORD'.Result should be sorted on job and sal.
Think: Could you express the same query without using nested blocks?
CORRELATED SUB QUERIES
For all the sub queries we have examined thus far, ORACLE(RDBMS) evaluated the innermost (last) query first. The evaluation of the sub query returned a single value ( or a set of values). It then substituted this value into the outer level's predicate. Only then did oracle use those results to evaluate the next query.
There are times, however, when this isn't desirable - situations where the inner query depends on a value or values determined by an outer query. In this case, the outer query is repeatedly evaluated and a value determined. Then the inner query is evaluated based on the previously determined value. This type of query is called correlated sub query.
EXAMPLE
LIST OF EMPLOYEES ( ENAME) WORKING IN A DEPT. OTHER THAN THE DEPT. OF THEIR MANAGER.
F Necessary to use correlation name for the table.
CORRELATED Sub query processing
Think: Could you write this query differently? (without synchronized queries).
The EXISTS operatorThe EXISTS operator is useful to test for the existence of rows in a table that match some specified condition. Such a test is usually performed within a sub query and is connected to the outer query by using the syntax below:
EXISTS here represents the existential quantifier. The expression "EXISTS (SELECT ...)" evaluates to true if and only if the result of evaluating its "SELECT..." is not empty (at least one record returned by the sub query following EXISTS).
NOT EXISTS is the opposite, and then evaluates to true if the result of the sub query is empty.
EXISTS is not empty
NOT EXISTS is empty
EXAMPLE
DISPLAY EMPLOYEES WORKING IN DEPTs. HAVING AT LEAST ONE "ANALYST".
SELECT *FROM EMP EWHERE EXISTS ( SELECT *
FROM EMPWHERE JOB = 'ANALYST'AND E.DEPTNO = DEPTNO );
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO7369 SMITH CLERK 7902 17-DEC-80 800.00 207566 JONES MANAGER 7839 02-APR-81 2975.00 207788 SCOTT ANALYST 7566 09-DEC-82 3000.00 207876 ADAMS CLERK 7788 12-JAN-83 1100.00 207902 FORD ANALYST 7566 03-DEC-81 3000.00 20
For each employee E, the sub query finds a set of all ANALYSTs working in the same department as the employee E. Since the set is not empty then EXISTS evaluates to true and the employee E is displayed.
Think:Could you write the query without using the EXISTS operator ? Try to use IN.
DISPLAY DEPARTMENTs WITHOUT EMPLOYEES.
SELECT *FROM DEPTWHERE NOT EXISTS (SELECT*
FROM EMPWHERE DEPT.DEPTNO = DEPTNO
);Think:
This query could be formulated twice differently using :- MINUS- NOT IN.
Although "complete" as the relational algebra requires, the retrieval language described so far is still inadequate for many practical problems. For example, even a query as simple as "How many employees are there ?" cannot be expressed using the constructs given till now. SQL therefore provides a number of special built-in functions to enhance its basic retrieval power.
The functions currently supported are :
COUNT number of valuesSUM sum of the valuesAVG average of the valuesMAX largest value in a columnMIN smallest value in a column
Other functions may be encountered in different SQL implementations, some of them are :
NVL check on the null valueDECODE multiple choice testTO_CHAR Date to char conversionTO_DATE Char to date conversionEtc.,
THE NULL VALUE FUNCTION
Sometimes it is necessary to detect the null values in a column and work with an alternate (substitute) value. For example, the expression SAL + COMM may involve a problem if the commission column is null: naturally we cannot add an unknown value. To solve this problem, the NVL function should be applied on the COMM field to substitute the null by another value - let be zero - in the computation.
Syntax
NVL ( expression , val )
IF expression is null THEN the function returns the value val
ELSE (* expression is not null *)the function returns the value of expression;
This enables to substitute - in the expression- the value zero each time the employee's commission is null.F without using NVL, the expression takes an undefined value for employees without commissions.
GROUP FUNCTIONS
Summary information (such as average or total) may be obtained for groups of rows through the use of group functions (aggregate functions). Group functions are:
AVG( [DISTINCT | ALL ] n) : Average value of n, ignoring null values.COUNT( [DISTINCT | ALL ] expr|*) : Number of times the numeric expression expr evaluates to something other than
NULL. The asterisk(*) makes COUNT counts all selected rows.MAX( [DISTINCT | ALL ] expr) : Maximum value of expr.MIN( [DISTINCT | ALL ] expr) : Minimum value of expr.SUM( [DISTINCT | ALL ] , n) : Sum values of n, ignoring null values.
USING GROUP FUNCTIONS
A group function can be applied to a subset of the rows in a table by using the WHERE clause.
EXAMPLES
To calculate the average salary of all employees,SELECT AVG(SAL)FROM EMP;
To find the minimum salary earned by a clerk,SELECT MIN(SAL)FROM EMPWHERE JOB='CLERK';
To count the number of employees in department 20, SELECT COUNT(*)FROM EMPWHERE DEPTNO= 20;
To display only those jobs, where the maximum salary is greater than or equal to $3000, enter:
SELECT JOB , MAX(SAL)FROM EMPHAVING MAX (SAL) >= 3000GROUP BY JOB;
JOB-----------
MAX(SAL)-------------
ANALYST 3000PRESIDENT 5000
The WHERE clause may still be used to exclude rows from consideration. It processes the rows one by one, whereas the HAVING works on each group of rows.Note: The HAVING clause may preceed GROUP BY clause.