+ All Categories
Home > Technology > Sql 2009

Sql 2009

Date post: 18-Jan-2015
Category:
Upload: cathie101
View: 418 times
Download: 0 times
Share this document with a friend
Description:
 
Popular Tags:
28
©Chisholm Institute SQL 2009 By Cathie Usher 1 SQL 2
Transcript
Page 1: Sql 2009

©Chisholm Institute

SQL2009

By CathieUsher

1

SQL

2

Page 2: Sql 2009

©Chisholm Institute

Introduction to SQLSQL 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

bl SQL i i l d i f i d d i f 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

3

fundamental exercises in the Tutorials.

SQL consists of two sub languages:DML (Data manipulation language)

DDL (Data definition language)

Introduction to SQL

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

4

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.

Page 3: Sql 2009

©Chisholm Institute

Structured Query Language (SQL)

D t D finiti n L n (DDL) Data Definition Language (DDL)involves Data types

(Characters, Dates etc) Creating tables and basic data management

(Create, identifying Primary and Foreign Keys etc)Advanced Data Management

5

Advanced Data Managementthe variation and changes to tables that exist

VocabularyThe following terminologies are used in this area of SQL

CREATE TABLE COMMIT

INSERT

DROP TABLE

6

DATA TYPE

Page 4: Sql 2009

©Chisholm Institute

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

7

Transaction Control Organise commands into logical transactions and commit

them to the database or roll them back. Commands: COMMIT, ROLLBACK, SAVEPOINT

Numeric NUMBER(L D) Oracle

Data Type Format Standard

Common Data Types Before we can

create tables we need to Numeric NUMBER(L,D) Oracle

INTEGER ANSISMALLINT ANSIDECIMAL(L,D) ANSI

Character CHAR(L) OracleVARCHAR2(L) Oracle

know about data types. Here is a summary of the data types and their formats for both Oracle

d ANSI if

8

VARCHAR2(L) Oracle

Date DATE Oracle

and ANSI if different.

Page 5: Sql 2009

©Chisholm Institute

Values allowed by data types

SMALLINT h l n 32 766 t 32 767

Here is a list of the values that are allowed and the method of predefining them.

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

9

CHAR(L) L characters from 0 to 255, fixed storage length

VARCHAR2(L) L characters from 0 to 255, variable storage length

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.

These commands relate in particular to the creation of tables.

DDL implement Integrity Constraints

Entity Integrity PRIMARY KEY is NOT NULL

10

PRIMARY KEY is NOT NULL

Referential Integrity FOREIGN KEY

Page 6: Sql 2009

©Chisholm Institute

Creating aTable (1)

The CREATE TABLE statement sets up a table h h f d din which rows of data can be stored.

In its simplest form this is:

CREATE TABLE name( l d

11

(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));

12

Page 7: Sql 2009

©Chisholm Institute

Creating the Table (2)

sql> CREATE TABLE EMPLOYEE

(EMP_ID CHAR(3) NOT NULL,

ENAME VARCHAR(25) NOT NULLENAME VARCHAR(25) NOT NULL,

DEPT CHAR(1) NOT NULL,

MANAGER CHAR(3),

DATE_JOINED DATE,

DOB DATE,

PRIMARY KEY (EMP ID)

13

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.

SQLA 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 namesSELECT data you want to retrieve - usually column namesFROM table-nameWHERE meeting this criteria – usually column-name matches a value(s)

SELECT empno, name, salaryFROM employeeWHERE salary > 50000

14

WHERE salary 50000

SELECT empno, name, salary FROM employee WHERE salary > 50000

Page 8: Sql 2009

©Chisholm Institute

Result SetThe 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 Q m mthe 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.

15

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

b th d f i i th it li tby the order of expressions in the item-listSQL statement Output Col Sequence

SELECT empno, name, salary FROM employee In item-list sequence

SELECT empno, salary, name FROM employee In item-list sequenceSELECT * FROM employee As listed in table defSELECT name, salary, salary * 1.1 FROM employee In item-list sequence

16

SELECT name, salary, salary 1.1 FROM employee In item list sequenceSELECT name, (salary * 1.1) FROM employee "

SELECT name, (salary * 1.1) "New_Salary" FROM emplo

"

SELECT name AS "Employee Name", salary FROM emplo

"

Page 9: Sql 2009

©Chisholm Institute

Select Distinct SELECT [ALL / DISTINCT] <item-list >…

ALL is the default. All possible records are return in the result set.DISTINCT eliminates duplicate

firstname surname dept

Ted Smith 1Ted Jones 2

DISTINCT eliminates duplicate records in the result set. John Jones 1

Ted Jones 1

SELECT DISTINCT firstname, dept FROM …

firstname dept

SELECT DISTINCT deptFROM employee

17

firstname dept

Ted 1Ted 2

John 1

dept

12

Order ByThe Order By clause specifies the sequence of records in the result-set.

The order is specified by the column number or the • 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

18

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.

Page 10: Sql 2009

©Chisholm Institute

Order By SELECT … FROM …[ ORDER BY <column-name / column-no> [ASC / DESC] [,…] ]SELECT empno, name, salary FROM EMPLOYEE ORDER BY name

s lt s t ds i s di m s result set records are in ascending name sequenceSELECT empno, name, salary FROM EMPLOYEE ORDER BY name ASC result set records are in ascending name sequenceSELECT empno, name, salary FROM EMPLOYEE ORDER BY name DESC result set records are in descending name sequenceSELECT empno, name, salary FROM EMPLOYEE ORDER BY salary DESC,

empno ASCresult set records are in descending salary sequence Within each

19

result set records are in descending salary sequence. Within each salary, records are listed in ascending employee number sequenceSELECT 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 = "Smith"… …WHERE salary > 50000… …WHERE salary <> 50000…

20

Page 11: Sql 2009

©Chisholm Institute

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 = "Smith" e.g. Select * from employee where empname = Smith

Some DBMSs require the use of " double quotes while others use' single quotes. Some DBMSs will accept either.

Most DBMSs are case-sensitive. Ie. 'SMITH' is not equal to 'Smith'

21

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

22

Page 12: Sql 2009

©Chisholm Institute

Summary SELECT - FROM - WHERE Syntax SELECT

* shows all rowsd d h l 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

G P B l

23

[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.

24

Page 13: Sql 2009

©Chisholm Institute

Multiple criteria in the Where ClauseUse 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 dealingwith ranges

25

with ranges.

100000 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

AND Condition 1 True Condition 1 FalseCondition 2 True TRUE FALSE

Condition 2 False FALSE FALSE

Age Sex Result18 M FALSE

26

…WHERE AGE >20 AND SEX = M… F E19 F FALSE21 F FALSE22 M TRUE

Page 14: Sql 2009

©Chisholm Institute

OR OperatorThe OR operator is used in the where clause.It evaluates and merges two conditionsIt returns results only when either conditions are TRUE.t returns results only when e ther cond t ons are E.

OR Condition 1 True Condition 1 FalseCondition 2 True TRUE TRUE

Condition 2 False TRUE FALSE

Age Sex Result18 M TRUE

27

Consider the clause:…WHERE AGE >20 OR SEX = ‘M…

18 M TRUE19 F FALSE

21 F TRUE22 M TRUE

Multiple operatorsWhere multiple operators exist, evaluate one operator at a time then the next, then the next…

Consider Consider …WHERE AGE >19 AND SEX = 'F' AND HEIGHT = '166' and WEIGHT > 50

Evaluate AGE > 19 AND SEX = 'F'Evaluate TRUE AND HEIGHT > 166Evaluate TRUE AND WEIGHT > 50

Age Sex Height Weight24 F 171 86

28

Evaluate TRUE AND WEIGHT > 50

Evaluate AGE > 19 AND SEX = 'F' Age Sex Height Weight24 M 183 93

Page 15: Sql 2009

©Chisholm Institute

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' WHERE AGE <17 OR AGE > 23 AND SEX = 'F'

Evaluate AGE > 23 AND SEX = 'F' first

Age Sex Height24 M 180

29

WHERE SEX = 'M' OR AGE > 22 AND SEX = 'F' OR AGE <17 Age Sex Height

21 M 180

ParenthesesOperators within parentheses are always evaluated first.Parentheses can also be used just for readability.Consider …WHERE AGE < 13 OR AGE > 19 AND SEX = 'M'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'

30

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.

Page 16: Sql 2009

©Chisholm Institute

NOTThe NOT operator negates the experssion to its right.If the <expression> is TRUE, then NOT <expression> is FALSEIf the <expression> is FALSE, then NOT <expression> is TRUE

AGE RESULTConsider …WHERE AGE >= 20 AND AGE <= 29

WHERE NOT ( AGE >= 20 AND AGE <= 29 )

AGE RESULT24 TRUE17 FALSE

AGE RESULT24 FALSE17 TRUE

31

WHERE NOT AGE >= 20 AND AGE <= 29

AGE RESULT2417

Special OperatorsWHERE <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

32

g g g g

WHERE < column-name > IS NULL / IS NOT NULL WHERE height IS NULL WHERE name IS NOT NULL

Page 17: Sql 2009

©Chisholm Institute

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

33

Obtain tutorial 2 from your tutor.

34

Page 18: Sql 2009

©Chisholm Institute

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 f th SQL t t t Th li i i i di t l ft

35

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 t bltable.

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

36

SELECT e.empno, e.name, e.salary b.branchaddr FROM employee e, branch b

Page 19: Sql 2009

©Chisholm Institute

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

37

WHERE e.branch=b.branch

This statement will display all employees and corresponding branch addresses

Effects of a missing Join

EmpNo Name Branch Salary Branch BranchAddr

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

BRANCHEMPLOYEE

EmpNo Name Branch Salary207 John

SmithHawthorn 48000

119 Jane Pitt Box Hill 37500345 Carol Kent Hawthorn 55000

Box Hill 1 Station StHawthorn 1 John St

RESULT SET

EmpNo Name Branch Salary BranchCode BranchAddr

38

EmpNo Name Branch Salary BranchCode BranchAddr207 John Smith Hawthorn 48000 Box Hill 1 Station St207 John Smith Hawthorn 48000 Hawthorn 1 John St119 Jane Pitt Box Hill 37500 Box Hill 1 Station St119 Jane Pitt Box Hill 37500 Hawthorn 1 John St345 Carol Kent Hawthorn 55000 Box Hill 1 Station St345 Carol Kent Hawthorn 55000 Hawthorn 1 John St

Page 20: Sql 2009

©Chisholm Institute

Multiple Foreign Keys

EmpNo Name Branch Salary Dept207 J h Smith K 48000 1

A relation/ table can have multiple foreign keys

EMPLOYEE

207 John Smith Kew 48000 1119 Jane Pitt Box Hill 37500 2345 Carol Kent Hawthorn 55000 2

Branch BranchAddr BranchPhBRANCH

DeptCode DeptDescrDEPARTMENT

39

Box Hill 1 Station St 9999-5678Hawthorn 1 John St 9999-2222Kew 1 High St 9999-1234

1 Sales2 Admin3 Reception

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 Joins employee to branch AND e.salary > 380000

deptdescr branch EmpNo Name BranchPh SalarySales Kew 207 John Smith 9999-1234 48000Admin Hawthorn 345 Carol Kent 9999-2222 55000

RESULT SET

Jo s e p oyee to b a c

Joins employee to department

40

dm n Hawthorn 3 5 arol Kent 9999 55

Page 21: Sql 2009

©Chisholm Institute

Multiple Foreign Keys (2)

EmpNo Name Branch Salary

Each table relation can

EMPLOYEE

EmpNo Name Branch Salary207 John Smith Kew 48000119 Jane Pitt Box Hill 37500667 John Dill Penrith 75000

Branch BranchAddr Region

have foreign key links to other tables.

BRANCHREGION

41

Kew 1 High St MEHawthorn 1 John St MEPenrith 1 Puckle St SW

RegionCode RegionDescrME Melbourne EastSW Sydney West

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 Joins employee to branch AND b.region = reg.regioncode AND e.empno > 200

Name RegionDescrJohn Smith Melbourne East

RESULT SET

Jo s e p oyee to b a c

Joins branch to region

42

Notice how this query does not display any columns from the branch table

John Dill Sydney West

Page 22: Sql 2009

©Chisholm Institute

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…

43

DELETE recordsDELETE <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.

44

Page 23: Sql 2009

©Chisholm Institute

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'

45

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

46

SELECT SUM( numbord quotprce ) FROM ordlne WHERE partnumb = 'BT04'

Page 24: Sql 2009

©Chisholm Institute

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

ordnumb Sum12489 164.45

47

FROM ordlne GROUP BY ordnumb 12491 714.94

12494 700.0012495 115.9012498 65.7012500 402.9912504 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 p y 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

wrhsnumb itemclss3 HW2 SG1 SG3 HW

Part Table

Result Set

Part Table

48

wrhsnumb, itemclss wrhsnumb itemclss count1 SG 22 AP 12 SG 23 AP 13 HW 4

3 HW2 AP3 AP3 HW1 SG3 HW2 SG

Page 25: Sql 2009

©Chisholm Institute

HAVING

Having 'works on' the results of the Group By. The previous Group By showed:

Suppose we only wanted to details of product

wrhsnumb itemclss count1 SG 22 AP 12 SG 2Suppose we only wanted to deta ls 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 t

3 AP 13 HW 4

49

FROM part GROUP BY wrhsnumb, itemclss HAVING count(*) >= 2

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 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.

50

Only aggregate expressions from the SELECT clause may appear here. ORDER BY Specifies the sequence of rows in the RESULT SET

Page 26: Sql 2009

©Chisholm Institute

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 ) 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.

51

Sub Query Examples SELECT * FROM part WHERE unitprce > ( SELECT AVG(unitprce) FROM part )

SELECT partnumb partdesc SELECT partnumb , partdesc FROM part WHERE partnumb NOT IN ( SELECT DISTINCT partnumb FROM ordlne )

52

Page 27: Sql 2009

©Chisholm Institute

Dates & related functions Using today's date: SELECT sysdate FROM dual 25-MAY-02

SELECT * FROM orders dual 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

53

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.

O l FAQ F

54

Oracle FAQs Forum Post your questions on anything about Oracle Developer. You can

also learn a lot from others' experience and answers.

Page 28: Sql 2009

©Chisholm Institute

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

EMPLOYEEEmpNo Name Salary Manager 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,

l AS

EmpNo Name Salary Manager119 Jane Pitt 37500 543207 John

Smith48000 543

345 Carol Kent 55000 543543 Dave Bligh 70000 ┴

55

employee AS mgr WHERE emp.manager = mgr.empno

Column Heading

Same table – 2 aliases

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. "Show me a list of all parts and show me quantities sold" SELECT o.ordnumb, o.numbord, p.partnumb, p.partdesc FROM ordlne o part p FROM ordlne o, part p WHERE o.partnumb = p.partnumb

ordnumb partnumb numbord partdesc12489 AX12 11 IRON 12491 BT04 1 STOVE 12491 BZ66 1 WASHER 12494 CB03 4 BIKE 12495 CX11 2 MIXER

56

Parts BH22 & CA14 are not in the list – as they have not been ordered

12495 CX11 2 MIXER 12498 AZ52 2 SKATES 12498 BA74 4 BASEBALL12500 BT04 1 STOVE 12504 CZ81 2 WEIGHTS


Recommended