SlideShare a Scribd company logo
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 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.
SQL consists of two sub languages:   DML (Data manipulation language)   DDL (Data definition language)   SQL is relatively easy to learn. SQL is a non-procedural ( declarative)  language. Users need only specify  what  data they want, not  how  this data is found.  ANSI prescribes a standard SQL. Commercial Relational DBMS implement a standard SQL core. 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. Introduction to SQL
Structured Query Language (SQL) D ata  D efinition  L anguage (DDL) involves Data types (Characters, Dates etc) Creating tables and basic data management (Create, identifying Primary and Foreign Keys etc) Advanced Data Management the variation and changes to tables that exist
Vocabulary The following terminologies are used in this area of SQL
DML, DDL and Transaction Control Data Manipulation Language Query or manipulate the data in database tables Commands: SELECT, INSERT, UPDATE, DELETE Data Definition Language Change the database structure Commands: CREATE, ALTER, DROP, GRANT, REVOKE Transaction Control   Organise commands into logical transactions and commit them to the database or roll them back. Commands: COMMIT, ROLLBACK, SAVEPOINT
Common Data Types 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. 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
Values allowed by data types SMALLINT  whole no -32,766 to 32,767 INTEGER  whole no -2,147,483,647 to 2,147,483,647 DECIMAL(L,D)  max of L digits, of which D digits follow the decimal point CHAR(L)  L characters from 0 to 255, fixed storage length VARCHAR2(L)  L characters from 0 to 255, variable storage length Here is a list of the values that are allowed and the method of predefining them.
These  commands  relate in particular to the creation of tables. DDL implement  Integrity Constraints Entity Integrity PRIMARY KEY  is  NOT NULL Referential Integrity FOREIGN KEY  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.
Creating a Table  (1)   The CREATE TABLE statement sets up a table in which rows of data can be stored. In its simplest form this is: CREATE TABLE  name ( column_name  data_type  column_constraint );
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));
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.
SQL A simple sql statement that retrieves data from a table has the following key structure. Keywords are in capitals SELECT data you want to retrieve - usually column names FROM  table-name WHERE meeting this criteria – usually column-name matches a value(s) SELECT empno, name, salary FROM  employee WHERE salary > 50000 SELECT empno, name, salary FROM employee WHERE salary > 50000
Result Set The result of a Select Statement is often referred to as the Result Set. (That's we will call it anyway). An SQL statement is said to 'return' some data via the result set. 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. People often mean 'the result set' when they say "The SQL statement returns / displays / lists / outputs some data"
SELECT item list FROM table-name SELECT < item-list [ [AS]  <alias>]  >… The item list is usually a list of column-names or formula  The sequence of columns in the result set is determined by the order of expressions in the item-list 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
Select Distinct SELECT [ALL / DISTINCT] <item-list >… ALL is the default. All possible records  are return in the result set. DISTINCT eliminates duplicate  records in the result set.  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
Order By The Order By clause specifies the sequence of records in the result-set. The order is specified by the column number or the  column name of the result-set. Multiple columns can be specified. Each column may be ordered in ASCending or DESCending sequence (descending is the default) 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.
Order By SELECT … FROM … [ ORDER BY <column-name / column-no> [ASC / DESC] [,…] ] SELECT empno, name, salary FROM EMPLOYEE ORDER BY name result set records are in ascending name sequence SELECT empno, name, salary FROM EMPLOYEE ORDER BY name ASC result set records are in ascending name sequence SELECT empno, name, salary FROM EMPLOYEE ORDER BY name DESC result set records are in descending name sequence SELECT empno, name, salary FROM EMPLOYEE ORDER BY salary DESC,  empno ASC result set records are in descending salary sequence. Within each salary,  records are listed in ascending employee number sequence SELECT empno, name, salary FROM EMPLOYEE ORDER BY  3, 1 result set records are in ascending salary sequence. Within each salary,  records are listed in ascending employee number sequence
WHERE clause SELECT … FROM … [ WHERE <search-condition> ] [ ORDER BY … The  WHERE  clause specifies the  criteria  that a record must meet to be included in the result set. … WHERE surname = &quot;Smith&quot;… … WHERE salary >  50000… … WHERE salary <>  50000…
Data Types When specifying a value stored in a  character  field you must use quotes around the value you search for. e.g. Select * from employee where empname = &quot;Smith&quot; Some DBMSs require the use of  &quot;  double quotes while others use  '  single quotes. Some DBMSs will accept either. Most DBMSs are case-sensitive. Ie. 'SMITH' is not equal to 'Smith' There is usually a SQL setting to turn case-sensitivity on/off.
Data Types 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. e.g. select * from employee where salary > 29999.99
Summary SELECT - FROM - WHERE Syntax SELECT *  shows all rows distinct  distinct shows only unique rows select list  specifies what columns to display, usually a set of column names FROM table specification can be more than one table name here [WHERE search condition] specifies which rows to display [GROUP BY column name] specifies columns used to define groups [HAVING search condition] specifies which groups to exclude from display [ORDER BY ordering specification] specifies how to order results
Activity Complete Tut 1.
Multiple criteria in the Where   Clause Use AND / OR when your query needs to meet multiple criteria. Some simple examples: SELECT * FROM employee  WHERE surname = 'SMITH' OR surname = 'JONES' SELECT * FROM employee WHERE salary > 20000 AND salary < 30000 Confused about whether to use AND or OR or ranges? Consider a single row. Can the surname equal Smith AND Jones. No. Draw a simple graph when dealing with ranges. 10000 0 20000 30000 40000 > 20000 < 30000 AND includes range  common  to both lines OR includes range covered by either line
And Operator The  AND  operator is used in the where clause. It evaluates and merges two conditions It returns results only when  both  conditons are TRUE. Consider the clause: … WHERE AGE >20 AND SEX = ‘M… 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
OR Operator The  OR  operator is used in the where clause. It evaluates and merges two conditions It returns results only when  either  conditions are TRUE. Consider the clause: … WHERE AGE >20 OR SEX = ‘M… 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
Multiple operators Where multiple operators exist, evaluate one operator at a time then the next, then the next… Consider … WHERE AGE >19  AND  SEX = 'F'   AND HEIGHT = '166' and WEIGHT > 50 Evaluate AGE > 19 AND SEX = 'F' Evaluate TRUE  AND HEIGHT > 166 Evaluate TRUE  AND   WEIGHT > 50 Evaluate AGE > 19 AND SEX = 'F' 171 Height 86 Weight F 24 Sex Age 183 Height 93 Weight M 24 Sex Age
ANDs and ORs When  both  AND and OR operators are used in the where clause,  the  AND operators take precedence  and are evaluated first. Consider … WHERE AGE <17  OR  AGE  > 23  AND  SEX = 'F' Evaluate  AGE > 23 AND SEX = 'F'  first WHERE  SEX = 'M'  OR  AGE  > 22  AND  SEX = 'F'  OR  AGE <17 180 Height M 24 Sex Age 180 Height M 21 Sex Age
Parentheses   Operators within parentheses are always evaluated first. Parentheses can also be used just for readability. Consider … WHERE AGE < 13  OR  AGE > 19 AND SEX = 'M' Evaluate   AGE > 19 AND SEX = 'M'   first, then Evaluate   AGE < 13 OR … WHERE ( AGE < 13  OR  AGE > 19 )  AND SEX = 'M' Evaluate   ( AGE < 13  OR  AGE > 19 )   first, then Evaluate  … AND  SEX = 'M' WHERE (SEX = 'M' OR SEX = 'F') AND ( AGE >18 AND AGE <= 20 ) Eval  either ( SEX = 'M' OR SEX = 'F')  or  ( AGE >18 AND AGE <= 20 )  first The age checking doesn't need  parentheses , but it makes reading easier.
NOT   The NOT operator negates the experssion to its right. If the <expression> is TRUE, then NOT <expression> is FALSE If the <expression> is FALSE, then NOT <expression> is TRUE Consider … WHERE AGE  >= 20 AND AGE <= 29  WHERE NOT ( AGE  >= 20 AND AGE <= 29 ) WHERE NOT AGE  >= 20 AND AGE <= 29  FALSE 17 TRUE 24 RESULT AGE TRUE 17 FALSE 24 RESULT AGE 17 24 RESULT AGE
Special Operators   WHERE <column-name> BETWEEN <value/exp> AND <value/exp>  WHERE age BETWEEN 30 and 40 WHERE  <  column-name  > LIKE <string with % wildcards> WHERE name LIKE 'SMI%' WHERE name LIKE '%SMITH%' WHERE  <  column-name  > IN <expression1 [,…]> WHERE name IN ('JONES', 'BROWN', 'LEE', 'SOO') WHERE age IN (24, 26, 28, 30) same as WHERE age = 24 OR age = 26 OR age = 28 OR age = 30 WHERE  <  column-name  > IS NULL  /  IS NOT NULL  WHERE height IS NULL  WHERE name IS NOT NULL
Constraints Key Constraint or Primary Key Constraint The key may have any value but cannot be identical to an existing key The key (or part key if the key is a composite key) cannot be null Referential Integrity Constraint  or  Foreign Key Constraint A foreign key must match a primary key value in another relation or the  foreign key must be null
Obtain tutorial 2 from your tutor.
tablename.columnname and aliases Each column–name used in any SQL statement may be prefixed by the table name. SELECT empno, name, salary FROM employee WHERE sex = 'F'  AND age => 50 SELECT employee.empno, employee.name, employee.salary FROM employee WHERE employee.sex = 'F'  AND employee.age => 50 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. SELECT e.empno, e.name, e.salary FROM employee e WHERE e.name LIKE 'DAV%'  AND e.salary => 50000
FROM with multiple tables SELECT … FROM <table1> [table1-alias], <table2> [table2-alias] [,…] SQL SELECT statements can work with data from more than one table. The FROM clause specifies which tables will be used. As column-names may be identical in two different tables, column-names are usually prefixed by the table name SELECT  e.empno, e.name, e.salary b.branchaddr  FROM  employee e,  branch b
SQL JOIN SELECT … FROM <table1> [table1-alias], <table2> [table2-alias] [,…] [ WHERE … <foreign column-name>  =  <primary-key column-name>  ] or <primary-key column-name> = <foreign column-name> Within the Where clause, you specify foreign key column must = the primary key column SELECT e.empno, e.name, e.salary, b.branchaddr FROM employee e, branch b WHERE e.branch=b.branch This statement will display all employees and corresponding branch addresses
Effects of a missing Join 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 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
Multiple Foreign Keys A relation/ table can have multiple foreign keys 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
SQL JOIN (a table with 2 foreign keys) SELECT  d.deptdescr, e.branch, e.empno, e.name, b.branchph, e.salary,  FROM  employee e, branch b, department d WHERE  e.branch = b.branch AND  e.dept = d.deptcode AND  e.salary > 380000 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
Multiple Foreign Keys (2) Each table relation can have foreign key links to other tables. 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
SQL JOIN (3 tables each with a   FK ) SELECT  e.name, reg.regiondescr  FROM  employee e, branch b, region reg WHERE  e.branch = b.branch AND  b.region = reg.regioncode AND  e.empno > 200 Notice how this query does not display any columns from the branch table RESULT SET Joins employee to branch Joins branch to region Sydney West Melbourne East RegionDescr John Dill John Smith Name
Drop Table DROP TABLE <tablename> You cannot create a table that already exists. You will need to DROP a table first, if you want to re-create it. DROP  TABLE student; CREATE TABLE student…
DELETE records DELETE <table-name> WHERE … DELETE student  will delete all rows from the student table DELETE student  WHERE stu_height < 150  will delete all rows fro the student table that meet the criteria.
COUNT COUNT counts the number of records in a table (that meet a criteria). PART ( partnumb, partdesc, unonhand, itemclss, wrhsnumb, unitprce ) SELECT COUNT(*) FROM part SELECT COUNT(partnumb) FROM part  SELECT COUNT(*) FROM part WHERE itemclass = 'HW' SELECT COUNT(partnumb) FROM part WHERE itemclass = 'HW'
SUM , AVERAGE , MAX , MIN SUM totals a column (that meet a criteria). ORDLNE (ordnumb, partnumb, numbord, quotprce ) SELECT SUM( numbord ) FROM ordlne SELECT AVG( numbord ) FROM ordlne SELECT MIN( numbord ) FROM ordlne SELECT MAX( numbord ) FROM ordlne SELECT SUM(  numbord * quotprce  ) FROM ordlne SELECT SUM(  numbord * quotprce  ) FROM ordlne WHERE partnumb = 'BT04'
GROUP BY The following statement requires a part number in the criteria. SELECT SUM(  numbord * quotprce  ) FROM ordlne  WHERE partnumb = 'BT04' Imagine if you had 1000 products. You would have to type 1000 product codes. The GROUP BY clause, will display an aggregate total for each 'group' The following records are 'grouped' by order number. SELECT ordnumb, SUM(  numbord * quotprce  )  FROM ordlne  GROUP BY ordnumb ordnumb  Sum 12489 164.45 12491 714.94 12494 700.00 12495 115.90 12498 65.70 12500 402.99 12504 217.98
GROUP BY rules An aggregate expression contain aggregate words such as count, sum… The select statement may contain any mixture of aggregate and non-aggregate expressions. Every non aggregate expression in the select clause must appear in the Group By Clause  Aggregate expressions in the Select clause do not appear in the Group By clause A subtotal will be calculated for each change in the non-aggregate column values SELECT wrhsnumb,  itemclss, count(*) FROM part GROUP BY  wrhsnumb, itemclss wrhsnumb itemclss count 1 SG 2 2 AP 1 2 SG 2 3 AP 1 3 HW 4 wrhsnumb itemclss HW 2 SG 1 SG 3 HW 2 AP 3 AP 3 HW 1 SG 3 HW 2 SG Part Table Result Set Part Table
HAVING Having 'works on' the results of the Group By. The previous Group By showed: Suppose we only wanted to details of product  classes that had more than one item. That means we want to specify a criteria based on the result of the Group By. The HAVING clause is used to do this.  Do not use the WHERE clause. The HAVING clause must use a aggregate expression from the SELECT clause. SELECT  wrhsnumb, itemclss, count(*) FROM  part GROUP BY  wrhsnumb, itemclss HAVING  count(*) >= 2 wrhsnumb itemclss count 1 SG 2 2 AP 1 2 SG 2 3 AP 1 3 HW 4
Review SELECT  Column names / expressions / aggregate expressions Column names should be preceded by table names  especially when multiple tables are used FROM  Table names (aliases may be used for Table Names) WHERE  Specifies criteria that rows must match to be selected. This is where 'joins' are specified in Oracle 8. The join is usually foreign-key column = primary key column. GROUP BY  Calculate subtotals. All non-aggregate SELECT expressions must be included here HAVING  Used in conjuction with Group By. Specifies criteria that  Group By aggregate expressions must match to be selected.  The criteria is based on the results of the Group By. Only aggregate expressions from the SELECT clause may  appear here. ORDER BY  Specifies the sequence of rows in the RESULT SET
Sub Queries Some queries cannot be completed in a simple single SQL statement. Determine the average unit price of all parts. OK  SELECT AVG(unitprce) from part ERROR  SELECT * from price WHERE unitprce  >  AVG( unitprce ) Aggregate commands are not allowed in the WHERE clause. However subqueries are allowed. A subquery is a complete SQL statement WITHIN another SQL statement.
Sub Query Examples SELECT *  FROM part  WHERE unitprce >  ( SELECT AVG(unitprce) FROM part ) SELECT partnumb , partdesc FROM part  WHERE  partnumb NOT  IN  ( SELECT DISTINCT partnumb FROM ordlne )
Dates & related functions Using today's date: SELECT  sysdate  FROM  dual  25-MAY-02 SELECT *  FROM  orders, dual  WHERE orddte < sysdate  ----  No Join necessary Convert Character String to Date to_date('25-dec-02') SELECT TO_DATE('25-dec-02') - sysdate  FROM  dual  -----  151.65480 SELECT ROUND (TO_DATE('25-dec-02') – sysdate)  FROM dual  ------ 152
References A List of Oracle Functions This site gives a list of the functions that are use the most in Oracle. SQL*Plus User's Guide and Reference, Release 8.1.5 Guide that explains all the concepts behind PL/SQL and illustrates every facet of the language.  Oracle8i SQL Reference Reference that contains a complete description of the (SQL) Oracle Underground FAQ A site giving a wide variety of topics on Oracle. Oracle  FAQs  Forum Post your questions on anything about Oracle Developer. You can also learn a lot from others' experience and answers.
Self Joins Suppose we have an Employee Table. The Manager column contains the employee number of each  employee's manager. The Manager column may contain nulls as some managers will not have a  manager of their own. To extract employee & manager details, we must employee as 2 different tables. SELECT emp.name Employee_Name,  mgr.name Manager_Name FROM  employee AS emp, employee AS mgr WHERE  emp.manager = mgr.empno 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
Inner Joins The join syntax we have used so far in often referred to as a INNER JOIN. The result set only includes rows that have matching data from both tables. &quot;Show me a list of all parts and show me quantities sold&quot; SELECT o.ordnumb, o.numbord, p.partnumb, p.partdesc FROM ordlne o, part p WHERE  o.partnumb =  p.partnumb Parts BH22 & CA14 are not in the list – as they have not been ordered 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

More Related Content

PDF
Database Management Essentials: Module 4 Basic Query Formulation with SQL
PPT
SQL200.1 Module 1
PPTX
Structure query language (sql)
PPTX
Introduction to SQL
PPTX
Introduction to SQL
PPTX
Xml part1
PPTX
Xml part3
PPTX
Xml part2
Database Management Essentials: Module 4 Basic Query Formulation with SQL
SQL200.1 Module 1
Structure query language (sql)
Introduction to SQL
Introduction to SQL
Xml part1
Xml part3
Xml part2

What's hot (19)

PPTX
Introduction to CSS
PPT
Sql server T-sql basics ppt-3
PPTX
Sql commands
PPTX
Subqueries, Backups, Users and Privileges
PDF
Sql tutorial
PPTX
Xml part4
PPTX
SQL Basics
PPTX
SQL Commands
PPTX
Introduction to SQL (for Chicago Booth MBA technology club)
PPT
SQL- Introduction to PL/SQL
PPTX
Intro to T-SQL – 2nd session
PPT
Chapter 07 ddl_sql
PDF
PPTX
SQL Assessment Command Statements
DOC
A must Sql notes for beginners
DOC
Module 3
PPT
Sql – Structured Query Language
PDF
SQL Overview
PDF
Ch05
Introduction to CSS
Sql server T-sql basics ppt-3
Sql commands
Subqueries, Backups, Users and Privileges
Sql tutorial
Xml part4
SQL Basics
SQL Commands
Introduction to SQL (for Chicago Booth MBA technology club)
SQL- Introduction to PL/SQL
Intro to T-SQL – 2nd session
Chapter 07 ddl_sql
SQL Assessment Command Statements
A must Sql notes for beginners
Module 3
Sql – Structured Query Language
SQL Overview
Ch05
Ad

Similar to Sql 2006 (20)

DOC
Introduction to sql
DOC
PPTX
SQL Queries Information
PPTX
My SQL.pptx
DOCX
Learning sql from w3schools
PPTX
DOCX
Teradata imp
PDF
SQL_BASIC AND ADVANCED.pdf
PDF
SQL Basics and Advanced for analytics.pdf
DOCX
DOC
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
PPTX
SQL(NEW).pptx
PDF
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
PPTX
PPTX
DOC
SQLQueries
DOCX
It6312 dbms lab-ex2
PDF
Basic sqlstatements
DOC
Sql Document in Testing
PDF
Oracle sql tutorial
Introduction to sql
SQL Queries Information
My SQL.pptx
Learning sql from w3schools
Teradata imp
SQL_BASIC AND ADVANCED.pdf
SQL Basics and Advanced for analytics.pdf
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
SQL(NEW).pptx
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
SQLQueries
It6312 dbms lab-ex2
Basic sqlstatements
Sql Document in Testing
Oracle sql tutorial
Ad

More from Cathie101 (20)

PPT
Page Layout 2010
PPT
Css 2010
PPT
Xhtml 2010
PPT
Dynamic Web Pages Ch 8 V1.0
PPT
Dynamic Web Pages Ch 6 V1.0
PPT
Dynamic Web Pages Ch 1 V1.0
PPT
Dynamic Web Pages Ch 9 V1.0
PPT
Dynamic Web Pages Ch 7 V1.0
PPT
Dynamic Web Pages Ch 5 V1.0
PPT
Dynamic Web Pages Ch 4 V1.0
PPT
Dynamic Web Pages Ch 3 V1.0
PPT
Dynamic Web Pages Ch 2 V1.0
PDF
Dynamic Web Pages 2009v2.1
DOC
Database Fdd
DOC
Sql All Tuts 2009
DOC
Database Fdd
DOC
Database Er
PPT
Database Design E R 2009
PPT
Database Design Fdd 2009
PPTX
Database Design E R 2009
Page Layout 2010
Css 2010
Xhtml 2010
Dynamic Web Pages Ch 8 V1.0
Dynamic Web Pages Ch 6 V1.0
Dynamic Web Pages Ch 1 V1.0
Dynamic Web Pages Ch 9 V1.0
Dynamic Web Pages Ch 7 V1.0
Dynamic Web Pages Ch 5 V1.0
Dynamic Web Pages Ch 4 V1.0
Dynamic Web Pages Ch 3 V1.0
Dynamic Web Pages Ch 2 V1.0
Dynamic Web Pages 2009v2.1
Database Fdd
Sql All Tuts 2009
Database Fdd
Database Er
Database Design E R 2009
Database Design Fdd 2009
Database Design E R 2009

Recently uploaded (20)

PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Onica Farming 24rsclub profitable farm business
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Pre independence Education in Inndia.pdf
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PDF
Module 3: Health Systems Tutorial Slides S2 2025
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
Open folder Downloads.pdf yes yes ges yes
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Cell Structure & Organelles in detailed.
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Onica Farming 24rsclub profitable farm business
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Pre independence Education in Inndia.pdf
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Module 3: Health Systems Tutorial Slides S2 2025
Renaissance Architecture: A Journey from Faith to Humanism
NOI Hackathon - Summer Edition - GreenThumber.pptx
Open folder Downloads.pdf yes yes ges yes
Revamp in MTO Odoo 18 Inventory - Odoo Slides
The Final Stretch: How to Release a Game and Not Die in the Process.
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Cell Structure & Organelles in detailed.

Sql 2006

  • 1. SQL 2006 By Cathie Usher
  • 2. SQL
  • 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. SQL consists of two sub languages: DML (Data manipulation language) DDL (Data definition language) SQL is relatively easy to learn. SQL is a non-procedural ( declarative) language. Users need only specify what data they want, not how this data is found. ANSI prescribes a standard SQL. Commercial Relational DBMS implement a standard SQL core. 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. Introduction to SQL
  • 5. Structured Query Language (SQL) D ata D efinition L anguage (DDL) involves Data types (Characters, Dates etc) Creating tables and basic data management (Create, identifying Primary and Foreign Keys etc) Advanced Data Management the variation and changes to tables that exist
  • 6. Vocabulary The following terminologies are used in this area of SQL
  • 7. DML, DDL and Transaction Control Data Manipulation Language Query or manipulate the data in database tables Commands: SELECT, INSERT, UPDATE, DELETE Data Definition Language Change the database structure Commands: CREATE, ALTER, DROP, GRANT, REVOKE Transaction Control Organise commands into logical transactions and commit them to the database or roll them back. Commands: COMMIT, ROLLBACK, SAVEPOINT
  • 8. Common Data Types 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. 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. Values allowed by data types SMALLINT whole no -32,766 to 32,767 INTEGER whole no -2,147,483,647 to 2,147,483,647 DECIMAL(L,D) max of L digits, of which D digits follow the decimal point CHAR(L) L characters from 0 to 255, fixed storage length VARCHAR2(L) L characters from 0 to 255, variable storage length Here is a list of the values that are allowed and the method of predefining them.
  • 10. These commands relate in particular to the creation of tables. DDL implement Integrity Constraints Entity Integrity PRIMARY KEY is NOT NULL Referential Integrity FOREIGN KEY 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. Creating a Table (1) The CREATE TABLE statement sets up a table in which rows of data can be stored. In its simplest form this is: CREATE TABLE name ( column_name data_type column_constraint );
  • 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. 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. SQL A simple sql statement that retrieves data from a table has the following key structure. Keywords are in capitals SELECT data you want to retrieve - usually column names FROM table-name WHERE meeting this criteria – usually column-name matches a value(s) SELECT empno, name, salary FROM employee WHERE salary > 50000 SELECT empno, name, salary FROM employee WHERE salary > 50000
  • 15. Result Set The result of a Select Statement is often referred to as the Result Set. (That's we will call it anyway). An SQL statement is said to 'return' some data via the result set. 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. People often mean 'the result set' when they say &quot;The SQL statement returns / displays / lists / outputs some data&quot;
  • 16. SELECT item list FROM table-name SELECT < item-list [ [AS] <alias>] >… The item list is usually a list of column-names or formula The sequence of columns in the result set is determined by the order of expressions in the item-list 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. Select Distinct SELECT [ALL / DISTINCT] <item-list >… ALL is the default. All possible records are return in the result set. DISTINCT eliminates duplicate records in the result set. 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. Order By The Order By clause specifies the sequence of records in the result-set. The order is specified by the column number or the column name of the result-set. Multiple columns can be specified. Each column may be ordered in ASCending or DESCending sequence (descending is the default) 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.
  • 19. Order By SELECT … FROM … [ ORDER BY <column-name / column-no> [ASC / DESC] [,…] ] SELECT empno, name, salary FROM EMPLOYEE ORDER BY name result set records are in ascending name sequence SELECT empno, name, salary FROM EMPLOYEE ORDER BY name ASC result set records are in ascending name sequence SELECT empno, name, salary FROM EMPLOYEE ORDER BY name DESC result set records are in descending name sequence SELECT empno, name, salary FROM EMPLOYEE ORDER BY salary DESC, empno ASC result set records are in descending salary sequence. Within each salary, records are listed in ascending employee number sequence SELECT empno, name, salary FROM EMPLOYEE ORDER BY 3, 1 result set records are in ascending salary sequence. Within each salary, records are listed in ascending employee number sequence
  • 20. WHERE clause SELECT … FROM … [ WHERE <search-condition> ] [ ORDER BY … The WHERE clause specifies the criteria that a record must meet to be included in the result set. … WHERE surname = &quot;Smith&quot;… … WHERE salary > 50000… … WHERE salary <> 50000…
  • 21. Data Types When specifying a value stored in a character field you must use quotes around the value you search for. e.g. Select * from employee where empname = &quot;Smith&quot; Some DBMSs require the use of &quot; double quotes while others use ' single quotes. Some DBMSs will accept either. Most DBMSs are case-sensitive. Ie. 'SMITH' is not equal to 'Smith' There is usually a SQL setting to turn case-sensitivity on/off.
  • 22. Data Types 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. e.g. select * from employee where salary > 29999.99
  • 23. Summary SELECT - FROM - WHERE Syntax SELECT * shows all rows distinct distinct shows only unique rows select list specifies what columns to display, usually a set of column names FROM table specification can be more than one table name here [WHERE search condition] specifies which rows to display [GROUP BY column name] specifies columns used to define groups [HAVING search condition] specifies which groups to exclude from display [ORDER BY ordering specification] specifies how to order results
  • 25. Multiple criteria in the Where Clause Use AND / OR when your query needs to meet multiple criteria. Some simple examples: SELECT * FROM employee WHERE surname = 'SMITH' OR surname = 'JONES' SELECT * FROM employee WHERE salary > 20000 AND salary < 30000 Confused about whether to use AND or OR or ranges? Consider a single row. Can the surname equal Smith AND Jones. No. Draw a simple graph when dealing with ranges. 10000 0 20000 30000 40000 > 20000 < 30000 AND includes range common to both lines OR includes range covered by either line
  • 26. And Operator The AND operator is used in the where clause. It evaluates and merges two conditions It returns results only when both conditons are TRUE. Consider the clause: … WHERE AGE >20 AND SEX = ‘M… 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. OR Operator The OR operator is used in the where clause. It evaluates and merges two conditions It returns results only when either conditions are TRUE. Consider the clause: … WHERE AGE >20 OR SEX = ‘M… 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. Multiple operators Where multiple operators exist, evaluate one operator at a time then the next, then the next… Consider … WHERE AGE >19 AND SEX = 'F' AND HEIGHT = '166' and WEIGHT > 50 Evaluate AGE > 19 AND SEX = 'F' Evaluate TRUE AND HEIGHT > 166 Evaluate TRUE AND WEIGHT > 50 Evaluate AGE > 19 AND SEX = 'F' 171 Height 86 Weight F 24 Sex Age 183 Height 93 Weight M 24 Sex Age
  • 29. ANDs and ORs When both AND and OR operators are used in the where clause, the AND operators take precedence and are evaluated first. Consider … WHERE AGE <17 OR AGE > 23 AND SEX = 'F' Evaluate AGE > 23 AND SEX = 'F' first WHERE SEX = 'M' OR AGE > 22 AND SEX = 'F' OR AGE <17 180 Height M 24 Sex Age 180 Height M 21 Sex Age
  • 30. Parentheses Operators within parentheses are always evaluated first. Parentheses can also be used just for readability. Consider … WHERE AGE < 13 OR AGE > 19 AND SEX = 'M' Evaluate AGE > 19 AND SEX = 'M' first, then Evaluate AGE < 13 OR … WHERE ( AGE < 13 OR AGE > 19 ) AND SEX = 'M' Evaluate ( AGE < 13 OR AGE > 19 ) first, then Evaluate … AND SEX = 'M' WHERE (SEX = 'M' OR SEX = 'F') AND ( AGE >18 AND AGE <= 20 ) Eval either ( SEX = 'M' OR SEX = 'F') or ( AGE >18 AND AGE <= 20 ) first The age checking doesn't need parentheses , but it makes reading easier.
  • 31. NOT The NOT operator negates the experssion to its right. If the <expression> is TRUE, then NOT <expression> is FALSE If the <expression> is FALSE, then NOT <expression> is TRUE Consider … WHERE AGE >= 20 AND AGE <= 29 WHERE NOT ( AGE >= 20 AND AGE <= 29 ) WHERE NOT AGE >= 20 AND AGE <= 29 FALSE 17 TRUE 24 RESULT AGE TRUE 17 FALSE 24 RESULT AGE 17 24 RESULT AGE
  • 32. Special Operators WHERE <column-name> BETWEEN <value/exp> AND <value/exp> WHERE age BETWEEN 30 and 40 WHERE < column-name > LIKE <string with % wildcards> WHERE name LIKE 'SMI%' WHERE name LIKE '%SMITH%' WHERE < column-name > IN <expression1 [,…]> WHERE name IN ('JONES', 'BROWN', 'LEE', 'SOO') WHERE age IN (24, 26, 28, 30) same as WHERE age = 24 OR age = 26 OR age = 28 OR age = 30 WHERE < column-name > IS NULL / IS NOT NULL WHERE height IS NULL WHERE name IS NOT NULL
  • 33. Constraints Key Constraint or Primary Key Constraint The key may have any value but cannot be identical to an existing key The key (or part key if the key is a composite key) cannot be null Referential Integrity Constraint or Foreign Key Constraint A foreign key must match a primary key value in another relation or the foreign key must be null
  • 34. Obtain tutorial 2 from your tutor.
  • 35. tablename.columnname and aliases Each column–name used in any SQL statement may be prefixed by the table name. SELECT empno, name, salary FROM employee WHERE sex = 'F' AND age => 50 SELECT employee.empno, employee.name, employee.salary FROM employee WHERE employee.sex = 'F' AND employee.age => 50 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. SELECT e.empno, e.name, e.salary FROM employee e WHERE e.name LIKE 'DAV%' AND e.salary => 50000
  • 36. FROM with multiple tables SELECT … FROM <table1> [table1-alias], <table2> [table2-alias] [,…] SQL SELECT statements can work with data from more than one table. The FROM clause specifies which tables will be used. As column-names may be identical in two different tables, column-names are usually prefixed by the table name SELECT e.empno, e.name, e.salary b.branchaddr FROM employee e, branch b
  • 37. SQL JOIN SELECT … FROM <table1> [table1-alias], <table2> [table2-alias] [,…] [ WHERE … <foreign column-name> = <primary-key column-name> ] or <primary-key column-name> = <foreign column-name> Within the Where clause, you specify foreign key column must = the primary key column SELECT e.empno, e.name, e.salary, b.branchaddr FROM employee e, branch b WHERE e.branch=b.branch This statement will display all employees and corresponding branch addresses
  • 38. Effects of a missing Join 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 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. Multiple Foreign Keys A relation/ table can have multiple foreign keys 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. SQL JOIN (a table with 2 foreign keys) SELECT d.deptdescr, e.branch, e.empno, e.name, b.branchph, e.salary, FROM employee e, branch b, department d WHERE e.branch = b.branch AND e.dept = d.deptcode AND e.salary > 380000 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. Multiple Foreign Keys (2) Each table relation can have foreign key links to other tables. 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. SQL JOIN (3 tables each with a FK ) SELECT e.name, reg.regiondescr FROM employee e, branch b, region reg WHERE e.branch = b.branch AND b.region = reg.regioncode AND e.empno > 200 Notice how this query does not display any columns from the branch table RESULT SET Joins employee to branch Joins branch to region Sydney West Melbourne East RegionDescr John Dill John Smith Name
  • 43. Drop Table DROP TABLE <tablename> You cannot create a table that already exists. You will need to DROP a table first, if you want to re-create it. DROP TABLE student; CREATE TABLE student…
  • 44. DELETE records DELETE <table-name> WHERE … DELETE student will delete all rows from the student table DELETE student WHERE stu_height < 150 will delete all rows fro the student table that meet the criteria.
  • 45. COUNT COUNT counts the number of records in a table (that meet a criteria). PART ( partnumb, partdesc, unonhand, itemclss, wrhsnumb, unitprce ) SELECT COUNT(*) FROM part SELECT COUNT(partnumb) FROM part SELECT COUNT(*) FROM part WHERE itemclass = 'HW' SELECT COUNT(partnumb) FROM part WHERE itemclass = 'HW'
  • 46. SUM , AVERAGE , MAX , MIN SUM totals a column (that meet a criteria). ORDLNE (ordnumb, partnumb, numbord, quotprce ) SELECT SUM( numbord ) FROM ordlne SELECT AVG( numbord ) FROM ordlne SELECT MIN( numbord ) FROM ordlne SELECT MAX( numbord ) FROM ordlne SELECT SUM( numbord * quotprce ) FROM ordlne SELECT SUM( numbord * quotprce ) FROM ordlne WHERE partnumb = 'BT04'
  • 47. GROUP BY The following statement requires a part number in the criteria. SELECT SUM( numbord * quotprce ) FROM ordlne WHERE partnumb = 'BT04' Imagine if you had 1000 products. You would have to type 1000 product codes. The GROUP BY clause, will display an aggregate total for each 'group' The following records are 'grouped' by order number. SELECT ordnumb, SUM( numbord * quotprce ) FROM ordlne GROUP BY ordnumb ordnumb Sum 12489 164.45 12491 714.94 12494 700.00 12495 115.90 12498 65.70 12500 402.99 12504 217.98
  • 48. GROUP BY rules An aggregate expression contain aggregate words such as count, sum… The select statement may contain any mixture of aggregate and non-aggregate expressions. Every non aggregate expression in the select clause must appear in the Group By Clause Aggregate expressions in the Select clause do not appear in the Group By clause A subtotal will be calculated for each change in the non-aggregate column values SELECT wrhsnumb, itemclss, count(*) FROM part GROUP BY wrhsnumb, itemclss wrhsnumb itemclss count 1 SG 2 2 AP 1 2 SG 2 3 AP 1 3 HW 4 wrhsnumb itemclss HW 2 SG 1 SG 3 HW 2 AP 3 AP 3 HW 1 SG 3 HW 2 SG Part Table Result Set Part Table
  • 49. HAVING Having 'works on' the results of the Group By. The previous Group By showed: Suppose we only wanted to details of product classes that had more than one item. That means we want to specify a criteria based on the result of the Group By. The HAVING clause is used to do this. Do not use the WHERE clause. The HAVING clause must use a aggregate expression from the SELECT clause. SELECT wrhsnumb, itemclss, count(*) FROM part GROUP BY wrhsnumb, itemclss HAVING count(*) >= 2 wrhsnumb itemclss count 1 SG 2 2 AP 1 2 SG 2 3 AP 1 3 HW 4
  • 50. Review SELECT Column names / expressions / aggregate expressions Column names should be preceded by table names especially when multiple tables are used FROM Table names (aliases may be used for Table Names) WHERE Specifies criteria that rows must match to be selected. This is where 'joins' are specified in Oracle 8. The join is usually foreign-key column = primary key column. GROUP BY Calculate subtotals. All non-aggregate SELECT expressions must be included here HAVING Used in conjuction with Group By. Specifies criteria that Group By aggregate expressions must match to be selected. The criteria is based on the results of the Group By. Only aggregate expressions from the SELECT clause may appear here. ORDER BY Specifies the sequence of rows in the RESULT SET
  • 51. Sub Queries Some queries cannot be completed in a simple single SQL statement. Determine the average unit price of all parts. OK SELECT AVG(unitprce) from part ERROR SELECT * from price WHERE unitprce > AVG( unitprce ) Aggregate commands are not allowed in the WHERE clause. However subqueries are allowed. A subquery is a complete SQL statement WITHIN another SQL statement.
  • 52. Sub Query Examples SELECT * FROM part WHERE unitprce > ( SELECT AVG(unitprce) FROM part ) SELECT partnumb , partdesc FROM part WHERE partnumb NOT IN ( SELECT DISTINCT partnumb FROM ordlne )
  • 53. Dates & related functions Using today's date: SELECT sysdate FROM dual 25-MAY-02 SELECT * FROM orders, dual WHERE orddte < sysdate ---- No Join necessary Convert Character String to Date to_date('25-dec-02') SELECT TO_DATE('25-dec-02') - sysdate FROM dual ----- 151.65480 SELECT ROUND (TO_DATE('25-dec-02') – sysdate) FROM dual ------ 152
  • 54. References A List of Oracle Functions This site gives a list of the functions that are use the most in Oracle. SQL*Plus User's Guide and Reference, Release 8.1.5 Guide that explains all the concepts behind PL/SQL and illustrates every facet of the language. Oracle8i SQL Reference Reference that contains a complete description of the (SQL) Oracle Underground FAQ A site giving a wide variety of topics on Oracle. Oracle FAQs Forum Post your questions on anything about Oracle Developer. You can also learn a lot from others' experience and answers.
  • 55. Self Joins Suppose we have an Employee Table. The Manager column contains the employee number of each employee's manager. The Manager column may contain nulls as some managers will not have a manager of their own. To extract employee & manager details, we must employee as 2 different tables. SELECT emp.name Employee_Name, mgr.name Manager_Name FROM employee AS emp, employee AS mgr WHERE emp.manager = mgr.empno 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. Inner Joins The join syntax we have used so far in often referred to as a INNER JOIN. The result set only includes rows that have matching data from both tables. &quot;Show me a list of all parts and show me quantities sold&quot; SELECT o.ordnumb, o.numbord, p.partnumb, p.partdesc FROM ordlne o, part p WHERE o.partnumb = p.partnumb Parts BH22 & CA14 are not in the list – as they have not been ordered 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

Editor's Notes