SQL 2006 By  Cathie Usher
SQL
Introduction to SQL SQL stands for Structured Query Language In simple terms it is a universal language that permits the c...
<ul><li>SQL consists of two sub languages:   </li></ul><ul><ul><ul><li>DML (Data manipulation language)   </li></ul></ul><...
Structured Query Language (SQL) <ul><li>D ata  D efinition  L anguage (DDL) involves </li></ul><ul><ul><li>Data types (Cha...
Vocabulary The following terminologies are used in this area of SQL
DML, DDL and Transaction Control <ul><li>Data Manipulation Language </li></ul><ul><ul><li>Query or manipulate the data in ...
Common Data Types <ul><li>Before we can create tables we need to know about data types . Here is a summary of the data typ...
Values allowed by data types <ul><li>SMALLINT  whole no -32,766 to 32,767 </li></ul><ul><li>INTEGER  whole no -2,147,483,6...
<ul><li>These  commands  relate in particular to the creation of tables. </li></ul><ul><li>DDL implement  Integrity Constr...
Creating a Table  (1)   <ul><li>The CREATE TABLE statement sets up a table in which rows of data can be stored. </li></ul>...
Creating a Table  (1) sql>  CREATE TABLE DEPARTMENT (DEPT_CODE CHAR(1) NOT NULL, DNAME VARCHAR(25)  NOT NULL, MAIL_NO CHAR...
Creating the Table  (2) sql>  CREATE TABLE EMPLOYEE (EMP_ID CHAR(3) NOT NULL, ENAME VARCHAR(25) NOT NULL, DEPT CHAR(1) NOT...
SQL <ul><li>A simple sql statement that retrieves data from a table has the following key structure. Keywords are in capit...
Result Set <ul><li>The result of a Select Statement is often referred to as the Result Set. (That's we will call it anyway...
SELECT item list FROM table-name <ul><li>SELECT < item-list [ [AS]  <alias>]  >… </li></ul><ul><li>The item list is usuall...
Select Distinct <ul><li>SELECT [ALL / DISTINCT] <item-list >… </li></ul><ul><li>ALL is the default. All possible records  ...
Order By <ul><li>The Order By clause specifies the sequence of records in the result-set. </li></ul><ul><ul><li>The order ...
Order By <ul><li>SELECT … FROM … </li></ul><ul><li>[ ORDER BY <column-name / column-no> [ASC / DESC] [,…] ] </li></ul><ul>...
WHERE clause <ul><li>SELECT … FROM … </li></ul><ul><li>[ WHERE <search-condition> ] </li></ul><ul><li>[ ORDER BY … </li></...
Data Types <ul><li>When specifying a value stored in a  character  field you must use quotes around the value you search f...
Data Types <ul><li>When specifying a value stored in a  numeric  field you should  not  use quotes around the value you se...
Summary <ul><li>SELECT - FROM - WHERE Syntax </li></ul><ul><li>SELECT </li></ul><ul><ul><li>*  shows all rows </li></ul></...
Activity <ul><li>Complete Tut 1. </li></ul>
Multiple criteria in the Where   Clause <ul><li>Use AND / OR when your query needs to meet multiple criteria. </li></ul><u...
And Operator <ul><li>The  AND  operator is used in the where clause. </li></ul><ul><li>It evaluates and merges two conditi...
OR Operator <ul><li>The  OR  operator is used in the where clause. </li></ul><ul><li>It evaluates and merges two condition...
Multiple operators <ul><li>Where multiple operators exist, evaluate one operator at a time then the next, then the next… <...
ANDs and ORs <ul><li>When  both  AND and OR operators are used in the where clause,  </li></ul><ul><li>the  AND operators ...
Parentheses   <ul><li>Operators within parentheses are always evaluated first. </li></ul><ul><li>Parentheses can also be u...
NOT   <ul><li>The NOT operator negates the experssion to its right. </li></ul><ul><li>If the <expression> is TRUE, then NO...
Special Operators   <ul><li>WHERE <column-name> BETWEEN <value/exp> AND <value/exp>  </li></ul><ul><li>WHERE age BETWEEN 3...
Constraints <ul><li>Key Constraint or Primary Key Constraint </li></ul><ul><li>The key may have any value but cannot be id...
<ul><li>Obtain tutorial 2 from your tutor. </li></ul>
tablename.columnname and aliases <ul><li>Each column–name used in any SQL statement may be prefixed by the table name. </l...
FROM with multiple tables <ul><li>SELECT … FROM <table1> [table1-alias], <table2> [table2-alias] [,…] </li></ul><ul><li>SQ...
SQL JOIN <ul><li>SELECT … FROM <table1> [table1-alias], <table2> [table2-alias] [,…] </li></ul><ul><li>[ WHERE … <foreign ...
Effects of a missing Join <ul><li>If the join is missing, then the DBMS will merge data from each row in table 1 with ever...
Multiple Foreign Keys <ul><li>A relation/ table can have multiple foreign keys </li></ul>EMPLOYEE BRANCH DEPARTMENT 55000 ...
SQL JOIN (a table with 2 foreign keys) <ul><li>SELECT  d.deptdescr, e.branch, e.empno, e.name, b.branchph, e.salary,  </li...
Multiple Foreign Keys (2) <ul><li>Each table relation can have foreign key links to other tables. </li></ul>EMPLOYEE BRANC...
SQL JOIN (3 tables each with a   FK ) <ul><li>SELECT  e.name, reg.regiondescr  </li></ul><ul><li>FROM  employee e, branch ...
Drop Table <ul><li>DROP TABLE <tablename> </li></ul><ul><li>You cannot create a table that already exists. </li></ul><ul><...
DELETE records <ul><li>DELETE <table-name> </li></ul><ul><li>WHERE … </li></ul><ul><li>DELETE student  will delete all row...
COUNT <ul><li>COUNT counts the number of records in a table (that meet a criteria). </li></ul><ul><li>PART ( partnumb, par...
SUM , AVERAGE , MAX , MIN <ul><li>SUM totals a column (that meet a criteria). </li></ul><ul><li>ORDLNE (ordnumb, partnumb,...
GROUP BY <ul><li>The following statement requires a part number in the criteria. </li></ul><ul><li>SELECT SUM(  numbord * ...
GROUP BY rules <ul><li>An aggregate expression contain aggregate words such as count, sum… </li></ul><ul><li>The select st...
HAVING <ul><li>Having 'works on' the results of the Group By. </li></ul><ul><li>The previous Group By showed: </li></ul><u...
Review <ul><li>SELECT  Column names / expressions / aggregate expressions </li></ul><ul><li>Column names should be precede...
Sub Queries <ul><li>Some queries cannot be completed in a simple single SQL statement. </li></ul><ul><li>Determine the ave...
Sub Query Examples <ul><li>SELECT *  </li></ul><ul><li>FROM part  </li></ul><ul><li>WHERE unitprce >  ( SELECT AVG(unitprc...
Dates & related functions <ul><li>Using today's date: </li></ul><ul><li>SELECT  sysdate  FROM  dual  25-MAY-02 </li></ul><...
References <ul><li>A List of Oracle Functions </li></ul><ul><li>This site gives a list of the functions that are use the m...
Self Joins <ul><li>Suppose we have an Employee Table. </li></ul><ul><li>The Manager column contains the employee number of...
Inner Joins <ul><li>The join syntax we have used so far in often referred to as a INNER JOIN. </li></ul><ul><li>The result...
Upcoming SlideShare
Loading in …5
×

Sql 2006

1,212 views

Published on

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,212
On SlideShare
0
From Embeds
0
Number of Embeds
16
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • 4
  • 4
  • 14
  • tkjgjmmg. dghh dfhdfh dfhdhgdf
  • Sql 2006

    1. 1. SQL 2006 By Cathie Usher
    2. 2. SQL
    3. 3. Introduction to SQL SQL stands for Structured Query Language In simple terms it is a universal language that permits the construction of tables and the manipulation of Data that lies within a table. SQL is extensively used in many areas of industry and is fast becoming the backbone of Internet display and functionality. In this section we concentrate on the construction and population of tables. This area is referred as the Data Definition Language of SQL (DDL). The following 2 sections concentrate on Data Manipulation Language (DML) where we do the actual queries. You will also be required to create tables yourself and perform some fundamental exercises in the Tutorials.
    4. 4. <ul><li>SQL consists of two sub languages: </li></ul><ul><ul><ul><li>DML (Data manipulation language) </li></ul></ul></ul><ul><ul><ul><li>DDL (Data definition language) </li></ul></ul></ul><ul><li>SQL is relatively easy to learn. </li></ul><ul><ul><li>SQL is a non-procedural ( declarative) language. Users need only specify what data they want, not how this data is found. </li></ul></ul><ul><li>ANSI prescribes a standard SQL. </li></ul><ul><ul><li>Commercial Relational DBMS implement a standard SQL core. </li></ul></ul><ul><ul><li>IBM initiated SQL in 1973. In 1983 the International Standards Organization (ISO) began to develop a standard for relational database languages based on SQL. The latest standard is SQL2 or SQL-92, but SQL3 is now under consideration and will include OO features. </li></ul></ul>Introduction to SQL
    5. 5. Structured Query Language (SQL) <ul><li>D ata D efinition L anguage (DDL) involves </li></ul><ul><ul><li>Data types (Characters, Dates etc) </li></ul></ul><ul><ul><li>Creating tables and basic data management (Create, identifying Primary and Foreign Keys etc) </li></ul></ul><ul><li>Advanced Data Management the variation and changes to tables that exist </li></ul>
    6. 6. Vocabulary The following terminologies are used in this area of SQL
    7. 7. DML, DDL and Transaction Control <ul><li>Data Manipulation Language </li></ul><ul><ul><li>Query or manipulate the data in database tables </li></ul></ul><ul><ul><li>Commands: SELECT, INSERT, UPDATE, DELETE </li></ul></ul><ul><li>Data Definition Language </li></ul><ul><ul><li>Change the database structure </li></ul></ul><ul><ul><li>Commands: CREATE, ALTER, DROP, GRANT, REVOKE </li></ul></ul><ul><li>Transaction Control </li></ul><ul><ul><li>Organise commands into logical transactions and commit them to the database or roll them back. </li></ul></ul><ul><ul><li>Commands: COMMIT, ROLLBACK, SAVEPOINT </li></ul></ul>
    8. 8. Common Data Types <ul><li>Before we can create tables we need to know about data types . Here is a summary of the data types and their formats for both Oracle and ANSI if different. </li></ul>Numeric NUMBER(L,D) Oracle INTEGER ANSI SMALLINT ANSI DECIMAL(L,D) ANSI Character CHAR(L) Oracle VARCHAR2(L) Oracle Date DATE Oracle Data Type Format Standard
    9. 9. Values allowed by data types <ul><li>SMALLINT whole no -32,766 to 32,767 </li></ul><ul><li>INTEGER whole no -2,147,483,647 to 2,147,483,647 </li></ul><ul><li>DECIMAL(L,D) max of L digits, of which D digits follow the decimal point </li></ul><ul><li>CHAR(L) L characters from 0 to 255, fixed storage length </li></ul><ul><li>VARCHAR2(L) L characters from 0 to 255, variable storage length </li></ul>Here is a list of the values that are allowed and the method of predefining them.
    10. 10. <ul><li>These commands relate in particular to the creation of tables. </li></ul><ul><li>DDL implement Integrity Constraints </li></ul><ul><ul><li>Entity Integrity </li></ul></ul><ul><ul><ul><li>PRIMARY KEY is NOT NULL </li></ul></ul></ul><ul><ul><li>Referential Integrity </li></ul></ul><ul><ul><ul><li>FOREIGN KEY </li></ul></ul></ul>Data Definition Commands It is critical when creating the tables that we define the Primary and Foreign Keys as displayed on the Database Schema and the consequential Network diagram.
    11. 11. Creating a Table (1) <ul><li>The CREATE TABLE statement sets up a table in which rows of data can be stored. </li></ul><ul><li>In its simplest form this is: </li></ul><ul><ul><li>CREATE TABLE name ( column_name data_type column_constraint ); </li></ul></ul>
    12. 12. Creating a Table (1) sql> CREATE TABLE DEPARTMENT (DEPT_CODE CHAR(1) NOT NULL, DNAME VARCHAR(25) NOT NULL, MAIL_NO CHAR(2) NOT NULL, PRIMARY KEY (DEPT_CODE));
    13. 13. Creating the Table (2) sql> CREATE TABLE EMPLOYEE (EMP_ID CHAR(3) NOT NULL, ENAME VARCHAR(25) NOT NULL, DEPT CHAR(1) NOT NULL, MANAGER CHAR(3), DATE_JOINED DATE, DOB DATE, PRIMARY KEY (EMP_ID), FOREIGN KEY (MANAGER) REFERENCES EMPLOYEE, FOREIGN KEY (DEPT) REFERENCE DEPARTMENT); Note: This table cannot be created until the Department table has been created, as it references the Department table.
    14. 14. SQL <ul><li>A simple sql statement that retrieves data from a table has the following key structure. Keywords are in capitals </li></ul><ul><li>SELECT data you want to retrieve - usually column names </li></ul><ul><li>FROM table-name </li></ul><ul><li>WHERE meeting this criteria – usually column-name matches a value(s) </li></ul><ul><li>SELECT empno, name, salary </li></ul><ul><li>FROM employee </li></ul><ul><li>WHERE salary > 50000 </li></ul><ul><li>SELECT empno, name, salary FROM employee WHERE salary > 50000 </li></ul>
    15. 15. Result Set <ul><li>The result of a Select Statement is often referred to as the Result Set. (That's we will call it anyway). </li></ul><ul><li>An SQL statement is said to 'return' some data via the result set. </li></ul><ul><li>The result set is often displayed on the screen but it could be sent to a printer, saved to a file, passed to a program or application etc. </li></ul><ul><li>People often mean 'the result set' when they say </li></ul><ul><li>&quot;The SQL statement returns / displays / lists / outputs some data&quot; </li></ul>
    16. 16. SELECT item list FROM table-name <ul><li>SELECT < item-list [ [AS] <alias>] >… </li></ul><ul><li>The item list is usually a list of column-names or formula </li></ul><ul><li>The sequence of columns in the result set is determined by the order of expressions in the item-list </li></ul>Output Col Sequence SQL statement &quot; SELECT name AS &quot;Employee Name&quot;, salary FROM emplo &quot; SELECT name, (salary * 1.1) &quot;New_Salary&quot; FROM emplo &quot; SELECT name, (salary * 1.1) FROM employee In item-list sequence SELECT name, salary, salary * 1.1 FROM employee As listed in table def SELECT * FROM employee In item-list sequence SELECT empno, salary, name FROM employee In item-list sequence SELECT empno, name, salary FROM employee
    17. 17. Select Distinct <ul><li>SELECT [ALL / DISTINCT] <item-list >… </li></ul><ul><li>ALL is the default. All possible records are return in the result set. </li></ul><ul><li>DISTINCT eliminates duplicate </li></ul><ul><li>records in the result set. </li></ul>SELECT DISTINCT firstname, dept FROM … SELECT DISTINCT dept FROM employee 1 Jones Ted John Ted Ted firstname 1 Jones 2 Jones 1 Smith dept surname 1 John Ted Ted firstname 2 1 dept 2 1 dept
    18. 18. Order By <ul><li>The Order By clause specifies the sequence of records in the result-set. </li></ul><ul><ul><li>The order is specified by the column number or the column name of the result-set. </li></ul></ul><ul><ul><li>Multiple columns can be specified. </li></ul></ul><ul><ul><li>Each column may be ordered in ASCending or DESCending sequence (descending is the default) </li></ul></ul><ul><li>If no order by clause is specified, the result set may be ordered by the physical sequence of records in the table. However, this would produce different results if the physical order is ever changed. </li></ul>
    19. 19. Order By <ul><li>SELECT … FROM … </li></ul><ul><li>[ ORDER BY <column-name / column-no> [ASC / DESC] [,…] ] </li></ul><ul><li>SELECT empno, name, salary FROM EMPLOYEE ORDER BY name </li></ul><ul><li>result set records are in ascending name sequence </li></ul><ul><li>SELECT empno, name, salary FROM EMPLOYEE ORDER BY name ASC </li></ul><ul><li>result set records are in ascending name sequence </li></ul><ul><li>SELECT empno, name, salary FROM EMPLOYEE ORDER BY name DESC </li></ul><ul><li>result set records are in descending name sequence </li></ul><ul><li>SELECT empno, name, salary FROM EMPLOYEE ORDER BY salary DESC, empno ASC </li></ul><ul><li>result set records are in descending salary sequence. Within each salary, records are listed in ascending employee number sequence </li></ul><ul><li>SELECT empno, name, salary FROM EMPLOYEE ORDER BY 3, 1 </li></ul><ul><li>result set records are in ascending salary sequence. Within each salary, records are listed in ascending employee number sequence </li></ul>
    20. 20. WHERE clause <ul><li>SELECT … FROM … </li></ul><ul><li>[ WHERE <search-condition> ] </li></ul><ul><li>[ ORDER BY … </li></ul><ul><li>The WHERE clause specifies the criteria that a record must meet to be included in the result set. </li></ul><ul><li>… WHERE surname = &quot;Smith&quot;… </li></ul><ul><li>… WHERE salary > 50000… </li></ul><ul><li>… WHERE salary <> 50000… </li></ul>
    21. 21. Data Types <ul><li>When specifying a value stored in a character field you must use quotes around the value you search for. </li></ul><ul><li>e.g. Select * from employee where empname = &quot;Smith&quot; </li></ul><ul><li>Some DBMSs require the use of &quot; double quotes while others use ' single quotes. Some DBMSs will accept either. </li></ul><ul><li>Most DBMSs are case-sensitive. Ie. 'SMITH' is not equal to 'Smith' </li></ul><ul><li>There is usually a SQL setting to turn case-sensitivity on/off. </li></ul>
    22. 22. Data Types <ul><li>When specifying a value stored in a numeric field you should not use quotes around the value you search for. Do no use commas between thousands. Decimals are OK. </li></ul><ul><li>e.g. select * from employee where salary > 29999.99 </li></ul>
    23. 23. Summary <ul><li>SELECT - FROM - WHERE Syntax </li></ul><ul><li>SELECT </li></ul><ul><ul><li>* shows all rows </li></ul></ul><ul><ul><li>distinct distinct shows only unique rows </li></ul></ul><ul><ul><li>select list specifies what columns to display, usually a set of column names </li></ul></ul><ul><li>FROM table specification </li></ul><ul><li>can be more than one table name here </li></ul><ul><li>[WHERE search condition] </li></ul><ul><li>specifies which rows to display </li></ul><ul><li>[GROUP BY column name] </li></ul><ul><li>specifies columns used to define groups </li></ul><ul><li>[HAVING search condition] </li></ul><ul><li>specifies which groups to exclude from display </li></ul><ul><li>[ORDER BY ordering specification] </li></ul><ul><li>specifies how to order results </li></ul>
    24. 24. Activity <ul><li>Complete Tut 1. </li></ul>
    25. 25. Multiple criteria in the Where Clause <ul><li>Use AND / OR when your query needs to meet multiple criteria. </li></ul><ul><li>Some simple examples: </li></ul><ul><li>SELECT * FROM employee </li></ul><ul><li>WHERE surname = 'SMITH' OR surname = 'JONES' </li></ul><ul><li>SELECT * FROM employee WHERE salary > 20000 AND salary < 30000 </li></ul><ul><li>Confused about whether to use AND or OR or ranges? </li></ul><ul><li>Consider a single row. Can the surname equal Smith AND Jones. No. </li></ul><ul><li>Draw a simple graph when dealing </li></ul><ul><li>with ranges. </li></ul>10000 0 20000 30000 40000 > 20000 < 30000 AND includes range common to both lines OR includes range covered by either line
    26. 26. And Operator <ul><li>The AND operator is used in the where clause. </li></ul><ul><li>It evaluates and merges two conditions </li></ul><ul><li>It returns results only when both conditons are TRUE. </li></ul><ul><li>Consider the clause: </li></ul><ul><li>… WHERE AGE >20 AND SEX = ‘M… </li></ul>FALSE FALSE Condition 2 False FALSE TRUE Condition 2 True Condition 1 False Condition 1 True AND FALSE M 18 FALSE F 19 M F Sex Result Age TRUE 22 FALSE 21
    27. 27. OR Operator <ul><li>The OR operator is used in the where clause. </li></ul><ul><li>It evaluates and merges two conditions </li></ul><ul><li>It returns results only when either conditions are TRUE. </li></ul><ul><li>Consider the clause: </li></ul><ul><li>… WHERE AGE >20 OR SEX = ‘M… </li></ul>FALSE TRUE Condition 2 False TRUE TRUE Condition 2 True Condition 1 False Condition 1 True OR TRUE M 18 FALSE F 19 M F Sex Result Age TRUE 22 TRUE 21
    28. 28. Multiple operators <ul><li>Where multiple operators exist, evaluate one operator at a time then the next, then the next… </li></ul><ul><li>Consider … </li></ul><ul><li>WHERE AGE >19 AND SEX = 'F' AND HEIGHT = '166' and WEIGHT > 50 </li></ul><ul><li>Evaluate AGE > 19 AND SEX = 'F' </li></ul><ul><li>Evaluate TRUE AND HEIGHT > 166 </li></ul><ul><li>Evaluate TRUE AND WEIGHT > 50 </li></ul><ul><li>Evaluate AGE > 19 AND SEX = 'F' </li></ul>171 Height 86 Weight F 24 Sex Age 183 Height 93 Weight M 24 Sex Age
    29. 29. ANDs and ORs <ul><li>When both AND and OR operators are used in the where clause, </li></ul><ul><li>the AND operators take precedence and are evaluated first. </li></ul><ul><li>Consider … </li></ul><ul><li>WHERE AGE <17 OR AGE > 23 AND SEX = 'F' </li></ul><ul><li>Evaluate AGE > 23 AND SEX = 'F' first </li></ul><ul><li>WHERE SEX = 'M' OR AGE > 22 AND SEX = 'F' OR AGE <17 </li></ul>180 Height M 24 Sex Age 180 Height M 21 Sex Age
    30. 30. Parentheses <ul><li>Operators within parentheses are always evaluated first. </li></ul><ul><li>Parentheses can also be used just for readability. </li></ul><ul><li>Consider … </li></ul><ul><li>WHERE AGE < 13 OR AGE > 19 AND SEX = 'M' </li></ul><ul><li>Evaluate AGE > 19 AND SEX = 'M' first, then </li></ul><ul><li>Evaluate AGE < 13 OR … </li></ul><ul><li>WHERE ( AGE < 13 OR AGE > 19 ) AND SEX = 'M' </li></ul><ul><li>Evaluate ( AGE < 13 OR AGE > 19 ) first, then </li></ul><ul><li>Evaluate … AND SEX = 'M' </li></ul><ul><li>WHERE (SEX = 'M' OR SEX = 'F') AND ( AGE >18 AND AGE <= 20 ) </li></ul><ul><li>Eval either ( SEX = 'M' OR SEX = 'F') or ( AGE >18 AND AGE <= 20 ) first </li></ul><ul><li>The age checking doesn't need parentheses , but it makes reading easier. </li></ul>
    31. 31. NOT <ul><li>The NOT operator negates the experssion to its right. </li></ul><ul><li>If the <expression> is TRUE, then NOT <expression> is FALSE </li></ul><ul><li>If the <expression> is FALSE, then NOT <expression> is TRUE </li></ul><ul><li>Consider … </li></ul><ul><li>WHERE AGE >= 20 AND AGE <= 29 </li></ul><ul><li>WHERE NOT ( AGE >= 20 AND AGE <= 29 ) </li></ul><ul><li>WHERE NOT AGE >= 20 AND AGE <= 29 </li></ul>FALSE 17 TRUE 24 RESULT AGE TRUE 17 FALSE 24 RESULT AGE 17 24 RESULT AGE
    32. 32. Special Operators <ul><li>WHERE <column-name> BETWEEN <value/exp> AND <value/exp> </li></ul><ul><li>WHERE age BETWEEN 30 and 40 </li></ul><ul><li>WHERE < column-name > LIKE <string with % wildcards> </li></ul><ul><li>WHERE name LIKE 'SMI%' </li></ul><ul><li>WHERE name LIKE '%SMITH%' </li></ul><ul><li>WHERE < column-name > IN <expression1 [,…]> </li></ul><ul><li>WHERE name IN ('JONES', 'BROWN', 'LEE', 'SOO') </li></ul><ul><li>WHERE age IN (24, 26, 28, 30) </li></ul><ul><li>same as WHERE age = 24 OR age = 26 OR age = 28 OR age = 30 </li></ul><ul><li>WHERE < column-name > IS NULL / IS NOT NULL </li></ul><ul><li>WHERE height IS NULL </li></ul><ul><li>WHERE name IS NOT NULL </li></ul>
    33. 33. Constraints <ul><li>Key Constraint or Primary Key Constraint </li></ul><ul><li>The key may have any value but cannot be identical to an existing key </li></ul><ul><li>The key (or part key if the key is a composite key) cannot be null </li></ul><ul><li>Referential Integrity Constraint or Foreign Key Constraint </li></ul><ul><li>A foreign key must match a primary key value in another relation or the </li></ul><ul><li>foreign key must be null </li></ul>
    34. 34. <ul><li>Obtain tutorial 2 from your tutor. </li></ul>
    35. 35. tablename.columnname and aliases <ul><li>Each column–name used in any SQL statement may be prefixed by the table name. </li></ul><ul><li>SELECT empno, name, salary FROM employee </li></ul><ul><li>WHERE sex = 'F' AND age => 50 </li></ul><ul><li>SELECT employee.empno, employee.name, employee.salary FROM employee </li></ul><ul><li>WHERE employee.sex = 'F' AND employee.age => 50 </li></ul><ul><li>A table may be given an alias which can be used throughout the rest of the SQL statement. The alias name is given immediately after the table name. </li></ul><ul><li>SELECT e.empno, e.name, e.salary FROM employee e </li></ul><ul><li>WHERE e.name LIKE 'DAV%' AND e.salary => 50000 </li></ul>
    36. 36. FROM with multiple tables <ul><li>SELECT … FROM <table1> [table1-alias], <table2> [table2-alias] [,…] </li></ul><ul><li>SQL SELECT statements can work with data from more than one table. </li></ul><ul><li>The FROM clause specifies which tables will be used. </li></ul><ul><li>As column-names may be identical in two different tables, column-names are usually prefixed by the table name </li></ul><ul><li>SELECT e.empno, e.name, e.salary b.branchaddr </li></ul><ul><li>FROM employee e, branch b </li></ul>
    37. 37. SQL JOIN <ul><li>SELECT … FROM <table1> [table1-alias], <table2> [table2-alias] [,…] </li></ul><ul><li>[ WHERE … <foreign column-name> = <primary-key column-name> ] </li></ul><ul><li>or <primary-key column-name> = <foreign column-name> </li></ul><ul><li>Within the Where clause, you specify foreign key column must = the primary key column </li></ul><ul><li>SELECT e.empno, e.name, e.salary, b.branchaddr </li></ul><ul><li>FROM employee e, branch b </li></ul><ul><li>WHERE e.branch=b.branch </li></ul><ul><li>This statement will display all employees and corresponding branch addresses </li></ul>
    38. 38. Effects of a missing Join <ul><li>If the join is missing, then the DBMS will merge data from each row in table 1 with every row in table two. Large tables create very large result sets </li></ul>BRANCH RESULT SET EMPLOYEE 55000 37500 48000 Salary Hawthorn Box Hill Hawthorn Branch 345 119 207 EmpNo Carol Kent Jane Pitt John Smith Name 1 John St 1 Station St BranchAddr Hawthorn Box Hill Branch 1 Station St Box Hill 55000 Hawthorn Carol Kent 345 1 John St Hawthorn 37500 Box Hill Jane Pitt 119 1 John St Hawthorn 48000 Hawthorn John Smith 207 55000 37500 48000 Salary Hawthorn Box Hill Box Hill BranchCode 1 John St 1 Station St 1 Station St BranchAddr Hawthorn Box Hill Hawthorn Branch 345 119 207 EmpNo Carol Kent Jane Pitt John Smith Name
    39. 39. Multiple Foreign Keys <ul><li>A relation/ table can have multiple foreign keys </li></ul>EMPLOYEE BRANCH DEPARTMENT 55000 37500 48000 Salary 2 2 1 Dept Hawthorn Box Hill Kew Branch 345 119 207 EmpNo Carol Kent Jane Pitt John Smith Name 1 High St 1 John St 1 Station St BranchAddr Kew Hawthorn Box Hill Branch 9999-1234 9999-2222 9999-5678 BranchPh Reception Admin Sales DeptDescr 3 2 1 DeptCode
    40. 40. SQL JOIN (a table with 2 foreign keys) <ul><li>SELECT d.deptdescr, e.branch, e.empno, e.name, b.branchph, e.salary, </li></ul><ul><li>FROM employee e, branch b, department d </li></ul><ul><li>WHERE e.branch = b.branch </li></ul><ul><li>AND e.dept = d.deptcode </li></ul><ul><li>AND e.salary > 380000 </li></ul>RESULT SET Joins employee to branch Joins employee to department Admin Sales deptdescr Hawthorn Kew branch 55000 48000 Salary 9999-2222 9999-1234 BranchPh 345 207 EmpNo Carol Kent John Smith Name
    41. 41. Multiple Foreign Keys (2) <ul><li>Each table relation can have foreign key links to other tables. </li></ul>EMPLOYEE BRANCH REGION 75000 37500 48000 Salary Penrith Box Hill Kew Branch 667 119 207 EmpNo John Dill Jane Pitt John Smith Name 1 Puckle St 1 John St 1 High St BranchAddr Penrith Hawthorn Kew Branch SW ME ME Region Sydney West Melbourne East RegionDescr SW ME RegionCode
    42. 42. SQL JOIN (3 tables each with a FK ) <ul><li>SELECT e.name, reg.regiondescr </li></ul><ul><li>FROM employee e, branch b, region reg </li></ul><ul><li>WHERE e.branch = b.branch </li></ul><ul><li>AND b.region = reg.regioncode </li></ul><ul><li>AND e.empno > 200 </li></ul><ul><li>Notice how this query does not display any columns from the branch table </li></ul>RESULT SET Joins employee to branch Joins branch to region Sydney West Melbourne East RegionDescr John Dill John Smith Name
    43. 43. Drop Table <ul><li>DROP TABLE <tablename> </li></ul><ul><li>You cannot create a table that already exists. </li></ul><ul><li>You will need to DROP a table first, if you want to re-create it. </li></ul><ul><li>DROP TABLE student; </li></ul><ul><li>CREATE TABLE student… </li></ul>
    44. 44. DELETE records <ul><li>DELETE <table-name> </li></ul><ul><li>WHERE … </li></ul><ul><li>DELETE student will delete all rows from the student table </li></ul><ul><li>DELETE student WHERE stu_height < 150 </li></ul><ul><li>will delete all rows fro the student table that meet the criteria. </li></ul>
    45. 45. COUNT <ul><li>COUNT counts the number of records in a table (that meet a criteria). </li></ul><ul><li>PART ( partnumb, partdesc, unonhand, itemclss, wrhsnumb, unitprce ) </li></ul><ul><li>SELECT COUNT(*) FROM part </li></ul><ul><li>SELECT COUNT(partnumb) FROM part </li></ul><ul><li>SELECT COUNT(*) FROM part WHERE itemclass = 'HW' </li></ul><ul><li>SELECT COUNT(partnumb) FROM part WHERE itemclass = 'HW' </li></ul>
    46. 46. SUM , AVERAGE , MAX , MIN <ul><li>SUM totals a column (that meet a criteria). </li></ul><ul><li>ORDLNE (ordnumb, partnumb, numbord, quotprce ) </li></ul><ul><li>SELECT SUM( numbord ) FROM ordlne </li></ul><ul><li>SELECT AVG( numbord ) FROM ordlne </li></ul><ul><li>SELECT MIN( numbord ) FROM ordlne </li></ul><ul><li>SELECT MAX( numbord ) FROM ordlne </li></ul><ul><li>SELECT SUM( numbord * quotprce ) FROM ordlne </li></ul><ul><li>SELECT SUM( numbord * quotprce ) FROM ordlne </li></ul><ul><li>WHERE partnumb = 'BT04' </li></ul>
    47. 47. GROUP BY <ul><li>The following statement requires a part number in the criteria. </li></ul><ul><li>SELECT SUM( numbord * quotprce ) FROM ordlne </li></ul><ul><li>WHERE partnumb = 'BT04' </li></ul><ul><li>Imagine if you had 1000 products. You would have to type 1000 product codes. </li></ul><ul><li>The GROUP BY clause, will display an aggregate total for each 'group' </li></ul><ul><li>The following records are 'grouped' by order number. </li></ul><ul><li>SELECT ordnumb, SUM( numbord * quotprce ) </li></ul><ul><li>FROM ordlne </li></ul><ul><li>GROUP BY ordnumb </li></ul>ordnumb Sum 12489 164.45 12491 714.94 12494 700.00 12495 115.90 12498 65.70 12500 402.99 12504 217.98
    48. 48. GROUP BY rules <ul><li>An aggregate expression contain aggregate words such as count, sum… </li></ul><ul><li>The select statement may contain any mixture of aggregate and non-aggregate expressions. </li></ul><ul><li>Every non aggregate expression in the select clause must appear in the Group By Clause </li></ul><ul><li>Aggregate expressions in the Select clause do not appear in the Group By clause </li></ul><ul><li>A subtotal will be calculated for each change in the non-aggregate column values </li></ul><ul><li>SELECT wrhsnumb, </li></ul><ul><li>itemclss, count(*) </li></ul><ul><li>FROM part </li></ul><ul><li>GROUP BY </li></ul><ul><li>wrhsnumb, itemclss </li></ul>wrhsnumb itemclss count 1 SG 2 2 AP 1 2 SG 2 3 AP 1 3 HW 4 <ul><li>wrhsnumb itemclss </li></ul><ul><li>HW </li></ul><ul><li>2 SG </li></ul><ul><li>1 SG </li></ul><ul><li>3 HW </li></ul><ul><li>2 AP </li></ul><ul><li>3 AP </li></ul><ul><li>3 HW </li></ul><ul><li>1 SG </li></ul><ul><li>3 HW </li></ul><ul><li>2 SG </li></ul>Part Table Result Set Part Table
    49. 49. HAVING <ul><li>Having 'works on' the results of the Group By. </li></ul><ul><li>The previous Group By showed: </li></ul><ul><li>Suppose we only wanted to details of product </li></ul><ul><li>classes that had more than one item. </li></ul><ul><li>That means we want to specify a criteria based on the result of the Group By. </li></ul><ul><li>The HAVING clause is used to do this. Do not use the WHERE clause. </li></ul><ul><li>The HAVING clause must use a aggregate expression from the SELECT clause. </li></ul><ul><li>SELECT wrhsnumb, itemclss, count(*) </li></ul><ul><li>FROM part </li></ul><ul><li>GROUP BY wrhsnumb, itemclss </li></ul><ul><li>HAVING count(*) >= 2 </li></ul>wrhsnumb itemclss count 1 SG 2 2 AP 1 2 SG 2 3 AP 1 3 HW 4
    50. 50. Review <ul><li>SELECT Column names / expressions / aggregate expressions </li></ul><ul><li>Column names should be preceded by table names </li></ul><ul><li>especially when multiple tables are used </li></ul><ul><li>FROM Table names (aliases may be used for Table Names) </li></ul><ul><li>WHERE Specifies criteria that rows must match to be selected. </li></ul><ul><li>This is where 'joins' are specified in Oracle 8. </li></ul><ul><li>The join is usually foreign-key column = primary key column. </li></ul><ul><li>GROUP BY Calculate subtotals. All non-aggregate SELECT expressions </li></ul><ul><li>must be included here </li></ul><ul><li>HAVING Used in conjuction with Group By. Specifies criteria that </li></ul><ul><li>Group By aggregate expressions must match to be selected. </li></ul><ul><li>The criteria is based on the results of the Group By. </li></ul><ul><li>Only aggregate expressions from the SELECT clause may </li></ul><ul><li>appear here. </li></ul><ul><li>ORDER BY Specifies the sequence of rows in the RESULT SET </li></ul>
    51. 51. Sub Queries <ul><li>Some queries cannot be completed in a simple single SQL statement. </li></ul><ul><li>Determine the average unit price of all parts. </li></ul><ul><li>OK SELECT AVG(unitprce) from part </li></ul><ul><li>ERROR SELECT * from price WHERE unitprce > AVG( unitprce ) </li></ul><ul><li>Aggregate commands are not allowed in the WHERE clause. </li></ul><ul><li>However subqueries are allowed. </li></ul><ul><li>A subquery is a complete SQL statement WITHIN another SQL statement. </li></ul>
    52. 52. Sub Query Examples <ul><li>SELECT * </li></ul><ul><li>FROM part </li></ul><ul><li>WHERE unitprce > ( SELECT AVG(unitprce) FROM part ) </li></ul><ul><li>SELECT partnumb , partdesc </li></ul><ul><li>FROM part </li></ul><ul><li>WHERE partnumb NOT IN ( SELECT DISTINCT partnumb FROM ordlne ) </li></ul>
    53. 53. Dates & related functions <ul><li>Using today's date: </li></ul><ul><li>SELECT sysdate FROM dual 25-MAY-02 </li></ul><ul><li>SELECT * </li></ul><ul><li>FROM orders, dual </li></ul><ul><li>WHERE orddte < sysdate ---- No Join necessary </li></ul><ul><li>Convert Character String to Date </li></ul><ul><li>to_date('25-dec-02') </li></ul><ul><li>SELECT TO_DATE('25-dec-02') - sysdate FROM dual ----- 151.65480 </li></ul><ul><li>SELECT ROUND (TO_DATE('25-dec-02') – sysdate) FROM dual ------ 152 </li></ul>
    54. 54. References <ul><li>A List of Oracle Functions </li></ul><ul><li>This site gives a list of the functions that are use the most in Oracle. </li></ul><ul><li>SQL*Plus User's Guide and Reference, Release 8.1.5 </li></ul><ul><li>Guide that explains all the concepts behind PL/SQL and illustrates every facet of the language. </li></ul><ul><li>Oracle8i SQL Reference Reference that contains a complete description of the (SQL) </li></ul><ul><li>Oracle Underground FAQ </li></ul><ul><li>A site giving a wide variety of topics on Oracle. </li></ul><ul><li>Oracle FAQs Forum </li></ul><ul><li>Post your questions on anything about Oracle Developer. You can also learn a lot from others' experience and answers. </li></ul>
    55. 55. Self Joins <ul><li>Suppose we have an Employee Table. </li></ul><ul><li>The Manager column contains the employee number of each employee's manager. </li></ul><ul><li>The Manager column may contain nulls </li></ul><ul><li>as some managers will not have a </li></ul><ul><li>manager of their own. </li></ul><ul><li>To extract employee & manager details, </li></ul><ul><li>we must employee as 2 different tables. </li></ul><ul><li>SELECT emp.name Employee_Name, </li></ul><ul><li>mgr.name Manager_Name </li></ul><ul><li>FROM employee AS emp, </li></ul><ul><li>employee AS mgr </li></ul><ul><li>WHERE emp.manager = mgr.empno </li></ul>EMPLOYEE Column Heading Same table – 2 aliases 543 37500 Jane Pitt 119 543 55000 Carol Kent 345 70000 48000 Salary ┴ 543 Manager 543 207 EmpNo Dave Bligh John Smith Name
    56. 56. Inner Joins <ul><li>The join syntax we have used so far in often referred to as a INNER JOIN. </li></ul><ul><li>The result set only includes rows that have matching data from both tables. </li></ul><ul><li>&quot;Show me a list of all parts and show me quantities sold&quot; </li></ul><ul><li>SELECT o.ordnumb, o.numbord, p.partnumb, p.partdesc </li></ul><ul><li>FROM ordlne o, part p </li></ul><ul><li>WHERE o.partnumb = p.partnumb </li></ul><ul><li>Parts BH22 & CA14 are not in the list – as they have not been ordered </li></ul>ordnumb partnumb numbord partdesc 12489 AX12 11 IRON 12491 BT04 1 STOVE 12491 BZ66 1 WASHER 12494 CB03 4 BIKE 12495 CX11 2 MIXER 12498 AZ52 2 SKATES 12498 BA74 4 BASEBALL 12500 BT04 1 STOVE 12504 CZ81 2 WEIGHTS

    ×