Sie sind auf Seite 1von 34

SQL COMMANDS

The following are syntax, table descriptions, and sql examples.


executed from an sql prompt:
Selecting a column from a table:
DESCRIBE <tablename>
SELECT <column_name> FROM <table_name>;
SQL> DESCRIBE worker
Name

Null?

Type

----------------------------------------- --------

----------------------------

NAME

VARCHAR2(25)

NOT NULL

AGE

NUMBER

LODGING

VARCHAR2(15)

SQL> SELECT name FROM worker;


NAME
------------------------BART SARJEANT
ELBERT TALBOT
DONALD ROLLO
JED HOPKINS
WILLIAM SWING
JOHN PEARSON
GEORGE OSCAR
KAY AND PALMER WALLBOM
PAT LAVAY
RICHARD KOCH AND BROTHERS
DICK JONES
Multiple columns can be selected:
Describe <tablename>
SELECT <column_name>, <column_name...> FROM <table_name>;

They are

SQL> DESCRIBE worker


Name

Null?

Type

----------------------------------------- --------

----------------------------

NAME

VARCHAR2(25)

NOT NULL

AGE

NUMBER

LODGING

VARCHAR2(15)

SQL> SELECT age, name FROM worker;


AGE

NAME

----------

-------------------------

22

BART SARJEANT

43

ELBERT TALBOT

16

DONALD ROLLO

33

JED HOPKINS

15

WILLIAM SWING

27

JOHN PEARSON

41

GEORGE OSCAR
KAY AND PALMER WALLBOM

21

PAT LAVAY
RICHARD KOCH AND BROTHERS

18

DICK JONES

The following statement removes duplicates from the output of information:


SELECT DISTINCT <column_name> FROM <table_name>;
SELECT DISTINCT lodging FROM worker;
SQL> SELECT DISTINCT lodging FROM worker;
LODGING
--------------CRANMER
MATTS
MULLERS
PAPA KING
ROSE HILL
WEITBROCHT

The following orders the results returned, using an ORDER BY clause:


SELECT Name, Age, Lodging FROM worker ORDER BY Age;
SQL> SELECT Name, Age, Lodging FROM worker ORDER BY Age;
NAME

AGE

LODGING

-------------------------

----------

---------------

WILLIAM SWING

15

CRANMER

HELEN BRANDT

15

DONALD ROLLO

16

MATTS

DICK JONES

18

ROSE HILL

PAT LAVAY

21

ROSE HILL

BART SARJEANT

22

CRANMER

ADAH TALBOT

23

PAPA KING

PETER LAWSON

25

CRANMER

JOHN PEARSON

27

ROSE HILL

ANDREW DYE

29

ROSE HILL

VICTORIA LYNN

32

MULLERS

NAME

AGE

LODGING

-------------------------

----------

---------------

JED HOPKINS

33

MATTS

ROLAND BRANDT

35

MATTS

GEORGE OSCAR

41

ROSE HILL

ELBERT TALBOT

43

WEITBROCHT

GERHARDT KENTGEN

55

PAPA KING

WILFRED LOWELL

67

KAY AND PALMER WALLBOM

ROSE HILL

RICHARD KOCH AND BROTHERS

WEITBROCHT

The following restrict the rows returned by using a WHERE clause:


SELECT <column_name> FROM <table_name> WHERE <condition>;
SQL> DESCRIBE newspaper
Name

Null?

Type

-----------------------------------------

--------

--------------------

FEATURE

NOT NULL

VARCHAR2(15)

SECTION

CHAR(1)

PAGE

NUMBER

SQL> SELECT Feature, Section, Page FROM newspaper WHERE Section = 'F';
FEATURE

PAGE

---------------

----------

Births

Classified

Obituaries

Doctor Is In

The following select fails, the Section column in the table newspaper is character
data, the characters in the single quotes must match exactly (case).
SQL> SELECT feature, section, page FROM newspaper where section ='f';
no rows selected
Restrict the rows returned by using a WHERE clause, order the results using
ORDER BY:
SQL> SELECT feature, section, page FROM newspaper WHERE section =F
ORDER BY feature;
FEATURE

PAGE

---------------

----------

Births

Classified

Doctor Is In

Obituaries

Using ORDER BY with more than one selection:


SQL> SELECT feature, section, page FROM newspaper WHERE section =F
ORDER BY page, feature;
FEATURE

PAGE

---------------

----------

Doctor Is In

Obituaries

Births

Classified

Changing the page ordering to DESCENDING order:


SQL> SELECT feature, section, page FROM newspaper WHERE section =F
ORDER BY page DESC, feature;
FEATURE

PAGE

---------------

----------

Classified

Births

Doctor Is In

Obituaries

Using GREATER THAN to restrict the rows returned:


SQL> SELECT feature, section, page FROM newspaper WHERE page >4;
FEATURE

PAGE

---------------

----------

Editorials

12

Television

Births

Classified

Obituaries

Doctor Is In

SQL> SELECT feature, section, page FROM newspaper WHERE section >B;
FEATURE

PAGE

---------------

----------

Sports

Business

Weather

Births

Classified

Comics

Obituaries

Doctor Is In

Using NOT EQUALS:


SQL> SELECT feature, section, page FROM newspaper WHERE page !=1;
FEATURE

PAGE

---------------

----------

Editorials

12

Weather

Television

Births

Classified

Comics

Movies

Bridge

Obituaries

Doctor Is In

Using pattern matching with character data:


% matches any number of characters
case of character data must match exactly within the quotes
SQL> SELECT feature, section, page FROM newspaper WHERE feature LIKE
Mo%;
FEATURE

PAGE

---------------

----------

Modern Life

Movies

_ (underscore) matches any one character, the select statement has two
underscores together, will match any word where the third letter is i, any
other characters after the i are matched by the %
SQL> SELECT feature, section, page FROM newspaper WHERE feature LIKE
__i%;
FEATURE
---------------

PAGE

----------

Editorials

12

Bridge

Obituaries

Matches any word with two os :


SQL> SELECT feature, section, page FROM newspaper WHERE feature LIKE
'%o%o%';
FEATURE

PAGE

---------------

----------

Doctor Is In

Restricting data using NULL or NOT NULL WHERE clauses:


SQL> SELECT city, sampledate, precipitation FROM comfort WHERE
Precipitation IS NOT NULL;
CITY

SAMPLEDAT

PRECIPITATION

-------------

---------

-------------

KEENE

22-JUN-93

1.3

KEENE

22-DEC-93

3.9

SAN FRANCISCO

21-MAR-93

.5

SAN FRANCISCO

22-JUN-93

.1

SAN FRANCISCO

23-SEP-93

.1

SAN FRANCISCO

22-DEC-93

2.3

KEENE

21-MAR-93

4.4

SQL> SELECT city, sampledate, precipitation FROM comfort WHERE precipitation IS


NULL;
CITY

SAMPLEDAT

------------KEENE

PRECIPITATION

---------

-------------

23-SEP-93

Restricting data using IN or NOT IN WHERE clauses:


SELECT feature, section, page FROM newspaper WHERE section IN ('A', 'B', 'F');
FEATURE
---------------

S
-

PAGE
----------

National News A

Editorials

12

Television

Births

Classified

Modern Life

Movies

Bridge

Obituaries

Doctor Is In

SELECT feature, section, page FROM newspaper WHERE section NOT IN ('A', 'B', 'F');
FEATURE

PAGE

---------------

----------

Sports

Business

Weather

Comics

Restricting data using BETWEEN in a WHERE clause:


SELECT feature, section, page FROM newspaper WHERE page BETWEEN 7 and 10;
FEATURE

PAGE

--------------- -

----------

Television

Births

Classified

Restricting data using WHERE clauses with multiple restrictions:


SELECT feature, section, page FROM newspaper WHERE section =F
AND page > 7;
FEATURE

PAGE

---------------

----------

Classified

SELECT feature, section, page FROM newspaper WHERE section = F


OR page > 7;
FEATURE

PAGE

---------------

----------

Editorials

12

Births

Classified

Obituaries

Doctor Is In

SELECT feature, section, page FROM newspaper WHERE section = F


AND page BETWEEN 7 AND 10;
FEATURE

PAGE

---------------

----------

Births

Classified

SELECT feature, section, page FROM newspaper WHERE section =A


OR section = 'B' AND page > 2;
FEATURE

PAGE

---------------

----------

National News

Editorials

12

Television

Movies

SELECT feature, section, page FROM newspaper WHERE section = A


AND page > 2 OR section = 'B';
FEATURE

PAGE

---------------

----------

Editorials

12

Television

Modern Life

Movies

Bridge

SELECT feature, section, page FROM newspaper WHERE page >2


AND section = 'A' OR section = 'B';
FEATURE

----------------

PAGE
----------

Editorials

12

Television

Modern Life B

Movies

Bridge

Using parenthesis and WHERE clauses:


SELECT feature, section, page FROM newspaper WHERE page > 2
AND (section = 'A' OR section = 'B');
FEATURE

PAGE

---------------

----------

Editorials

12

Television

Movies

SELECT section FROM newspaper WHERE feature = Doctor Is In;


S
F
SELECT feature FROM newspaper WHERE section = F;
FEATURE
--------------Births
Classified
Obituaries
Doctor Is In
Combining the above two queries:
SELECT feature FROM newspaper WHERE section = (SELECT section FROM
newspaper WHERE feature=Doctor Is In);
FEATURE
--------------Births
Classified
Obituaries
Doctor Is In

All the logical operators that test single values can work with subqueries, as long
as the subquery returns a single row. The subquery section from newspaper where
feature=Doctor Is In returns the single value F.

The next select (select * from

newspaper where section < ) returns every value where section < F.
SELECT * FROM newspaper WHERE section < (SELECT section FROM newspaper
WHERE feature='Doctor Is In');
FEATURE

---------------

PAGE
----------

National News A

Sports

Editorials

12

Business

Weather

Television

Modern Life

Comics

Movies

Bridge

Selecting from more than one table:


First select from weather, then location, then combine the two:
SELECT city, condition, temperature FROM weather;
CITY

CONDITION TEMPERATURE

-----------

---------

-----------

LIMA

RAIN

45

PARIS

CLOUDY

81

MANCHESTER

FOG

66

ATHENS

SUNNY

97

CHICAGO

RAIN

66

SYDNEY

SNOW

29

SPARTA

CLOUDY

74

SELECT city, longitude, eastwest, latitude, northsouth FROM location;


CITY

LONGITUDE

E LATITUDE N

------------------------- ----------

---------- -

ATHENS

23.43

37.58

CHICAGO

87.38

41.53

CONAKRY

13.43

9.31

LIMA

77.03

12.03

MADRAS

80.17

13.05

2.15

53.3

37.35

55.45

2.2

48.52

123.27

41.48

12.29

41.54

139.46

35.42

MANCHESTER
MOSCOW
PARIS
SHENYANG
ROME
TOKYO
CITY

LONGITUDE

E LATITUDE N

------------------------- ---------- - ---------- SYDNEY

151.13

33.52

SPARTA

22.27

37.05

MADRID

3.41

40.24

SELECT weather.city, condition, temperature, latitude, northsouth, longitude, eastwest


FROM weather, location WHERE weather.city = location.city;
CITY

CONDITION TEMPERATURE LATITUDE N LONGITUDE E

-----------

---------

-----------

----------

ATHENS

SUNNY

97

37.58

23.43

CHICAGO

RAIN

66

41.53

87.38

LIMA

RAIN

45

12.03

77.03

MANCHESTER FOG

66

53.3

2.15

PARIS

CLOUDY

81

48.52

2.2

SPARTA

CLOUDY

74

37.05

22.27

SYDNEY

SNOW

29

33.52

151.13

---------- -

Creating views: Creating views allows restricted access to tables, the where
clause can be used to join two tables based on a common column. Views are

dynamic, and reflect the data in the underlying tables. Views limit or change the
way the data is seen by a user.
CREATE view invasion AS SELECT weather.city, condition, temperature, latitude,
northsouth, longitude, eastwest FROM weather, location
WHERE weather.city = location.city;
View created.
DESCRIBE invasion;
Name

Null?

Type

----------------------------------------- -------- ---------------------------CITY

VARCHAR2(11)

CONDITION

VARCHAR2(9)

TEMPERATURE

NUMBER

LATITUDE

NUMBER

NORTHSOUTH

CHAR(1)

LONGITUDE

NUMBER

EASTWEST

CHAR(1)

SELECT city, condition, temperature, latitude, northsouth, longitude, eastwest FROM


invasion;
CITY

CONDITION TEMPERATURE LATITUDE N LONGITUDE E

-----------

---------

-----------

----------

----------

ATHENS

SUNNY

97

37.58

23.43

CHICAGO

RAIN

66

41.53

87.38

LIMA

RAIN

45

12.03

77.03

MANCHESTER FOG

66

53.3

2.15

PARIS

CLOUDY

81

48.52

2.2

SPARTA

CLOUDY

74

37.05

22.27

SYDNEY

SNOW

29

33.52

151.13

Using an invalid column name when selecting from the view, the column is in the
original table, but not the view:
SELECT city, condition, temperature, latitude, northsouth, longitude, eastwest
FROM invasion WHERE country=GREECE;

WHERE country = 'GREECE'


*
ERROR at line 3:
ORA-00904: invalid column name
Recreate the view using invalid column name:
CREATE OR REPLACE view invasion AS
SELECT weather.city, condition, temperature, latitude, northsouth, longitude, eastwest
FROM weather, location WHERE weather.city=location.city AND country = 'GREECE';
View created.
SELECT city, condition, temperature, latitude, northsouth, longitude, eastwest
FROM invasion;
Using concatenation function or symbol CONCAT ||
SELECT CONCAT(city, country) FROM location;
CONCAT(CITY,COUNTRY)
-------------------------------------------------ATHENSGREECE
CHICAGOUNITED STATES
CONAKRYGUINEA
LIMAPERU
MADRASINDIA
MANCHESTERENGLAND
MOSCOWRUSSIA
PARISFRANCE
SHENYANGCHINA
ROMEITALY
TOKYOJAPAN
SYDNEYAUSTRALIA
SPARTAGREECE
MADRIDSPAIN
SELECT city||country FROM location;

CONCAT(CITY,COUNTRY)
-------------------------------------------------ATHENSGREECE
CHICAGOUNITED STATES
CONAKRYGUINEA
LIMAPERU
MADRASINDIA
MANCHESTERENGLAND
MOSCOWRUSSIA
PARISFRANCE
SHENYANGCHINA
ROMEITALY
TOKYOJAPAN
SYDNEYAUSTRALIA
SPARTAGREECE
MADRIDSPAIN
Formatting CONCAT results using and spaces, commas:
City is concatenated with , a space, and the country
SELECT city ||', '||country FROM location;
CITY||','||COUNTRY
---------------------------------------------------ATHENS, GREECE
CHICAGO, UNITED STATES
CONAKRY, GUINEA
LIMA, PERU
MADRAS, INDIA
MANCHESTER, ENGLAND
MOSCOW, RUSSIA
PARIS, FRANCE
SHENYANG, CHINA
ROME, ITALY
TOKYO, JAPAN

SYDNEY, AUSTRALIA
SPARTA, GREECE
MADRID, SPAIN
Using functions:
SELECT <function_type> (<column_name>) FROM <table_name>;
SELECT COUNT(<column_name>) FROM <table_name>;
SELECT COUNT(DISTINCT <column_name>) FROM <table_name>;
SELECT <column_name1>, SUM(<column_name2>) FROM <table_name>
GROUP BY <column_name1>;
SELECT <column_name1>, SUM(<column_name2>) FROM <table_name>
GROUP BY <column_name1> HAVING (<arithematic function condition>);
Aliasing column names:
SELECT <table_alias>.<column_name1>, <column_alias> FROM
<table_name>.<table_alias>;
Character functions:
Function Name

Use:

||

concatenates two strings together

CONCAT

CONCATenates two strings together

INITCAP

INITial CAPital.
Changes the first letter of a word to uppercase.

INSTR

Finds the location of a character IN a STRing.

LENGTH

Returns the LENGTH of a string.

LOWER

converts every letter in a string to LOWER case.

LPAD

Left PAD
Pads a string to a certain length by adding with the
characters passed in as parameters on the left.

RPAD

Right PAD
Pads a string to a certain length by adding with the
characters passed in as parameters on the right.

RTRIM

Right TRIM
Trims all occurrences of a set of characters passed in as
parameters off the right side of a string.

SOUNDEX

Finds words that SOUND like the EXample passed in.

SUBSTR

SUBSTRing. Clips out a piece of a string.

UPPER

Converts every letter in a string to UPPERcase.

Examples:
RPAD pads the right side of a column up to 35 characters with a period.
SELECT RPAD(city,35,'.'), temperature FROM weather;
RPAD(CITY,35,'.')

TEMPERATURE

-----------------------------------

-----------

LIMA...............................

45

PARIS..............................

81

MANCHESTER.........................

66

ATHENS.............................

97

CHICAGO............................

66

SYDNEY.............................

29

SPARTA.............................

74

LPAD pads the left side of a column up to 11 characters with a space.


SELECT LPAD(city,11), temperature FROM weather;
LPAD(CITY,1 TEMPERATURE
-----------

----------LIMA
PARIS

45
81

MANCHESTER

66

ATHENS

97

CHICAGO

66

SYDNEY

29

SPARTA

74

Using both functions to trim off unwanted characters from the right and left ends
of strings:
SELECT LTRIM(RTRIM(Title,'."'),'"') FROM magazine;
Original output:
SELECT name, title, page FROM magazine;
NAME

TITLE

PAGE

----------------

-------------------------------------

----------

BERTRAND MONTHLY THE BARBERS WHO SHAVE THEMSELVES.

70

LIVE FREE OR DIE "HUNTING THOREAU IN NEW HAMPSHIRE"

320

PSYCHOLOGICA

246

THE ETHNIC NEIGHBORHOOD

FADED ISSUES

RELATIONAL DESIGN AND ENTHALPY

279

ENTROPY WIT

"INTERCONTINENTAL RELATIONS."

20

Trimmed output:
SELECT LTRIM(RTRIM(Title,'."'),'"') FROM magazine;
LTRIM(RTRIM(TITLE,'."'),'"')
------------------------------------THE BARBERS WHO SHAVE THEMSELVES
HUNTING THOREAU IN NEW HAMPSHIRE
THE ETHNIC NEIGHBORHOOD
RELATIONAL DESIGN AND ENTHALPY
INTERCONTINENTAL RELATIONS
Padding with -^, trimming off quotes, periods:
SELECT name, RPAD(RTRIM(LTRIM(title,'"'),'."'),47,'-^'), page FROM magazine;
NAME

RPAD(RTRIM(LTRIM(TITLE,'"'),'."'),47,'-^')

PAGE

---------------- ----------------------------------------------- ---------BERTRAND MONTHLY THE BARBERS WHO SHAVE THEMSELVES-^-^-^-^-^-^-^70


LIVE FREE OR DIE HUNTING THOREAU IN NEW HAMPSHIRE-^-^-^-^-^-^-^-

320

PSYCHOLOGICA

246

THE ETHNIC NEIGHBORHOOD-^-^-^-^-^-^-^-^-^-^-^-^

FADED ISSUES

RELATIONAL DESIGN AND ENTHALPY-^-^-^-^-^-^-^-^-

ENTROPY WIT

INTERCONTINENTAL RELATIONS-^-^-^-^-^-^-^-^-^-^-

NUMBER Functions:
Function

Definition

Value1 + value2

Addition

Value1 value2

Subtraction

Value1 * value2

Multiplication

Value1 / value2

Division

ABS(value)

ABSolute value

CEIL(value)

Smallest integer larger than or equal to value

279
20

COS(value)

COSine of value

COSH(value)

Hyberbolic COSine of value

EXP(value)

e raised to value EXPonent

FLOOR(value)

Largest integer smaller than or equal to value

LN(value)

Natural logarithm of value

LOG(value)

Base 10 LOGarithm of value

MOD(value)

MODulus

NVL(value)

Substitute for value if value is NULL

POWER(value)

value raised to an exponent POWER

ROUND(value)

ROUNDing of value to precision

SIGN(value)

1 if value is positive, -1 is value is negative, 0 if value is 0

SIN(value)

SINe of value

SINH(value)

Hyperbolic SINe of value

SQRT(value)

SQuare RooT of value

TAN(value)

TANgent of value

TANH(value)

Hyperbolic TANgent of value

TRUNC(value)

value TRUNCated to precision of value

VSIZE(value)

storage size of value in Oracle

GROUP Number Functions:


AVG(value)

AveraGe of value for group of rows

COUNT(value)

COUNT of rows for value

MAX(value)

MAXimum of all values for group of rows

MIN(value)

MINimum of all values for group of rows

STDDEV(value)

StanDard DEViation of all values for group of rows

SUM(value)

SUM of all values for group of rows

VARIANCE(value)

VARIANCE of all values for group of tows

GREATEST(value1, value2..) GREATEST value in list


LEAST(value1, value2..)

LEAST value in list

Examples:
DESCRIBE shipping
Name

Null?

Type

-------------------------------------- -------- ----------------------------

CLIENT

VARCHAR2(13)

WEIGHT

NUMBER

SELECT client, weight FROM shipping;


CLIENT

WEIGHT

-------------

----------

JOHNSON TOOL

59

DAGG SOFTWARE

27

TULLY ANDOVER
NVL substitutes a number entered as the second parameter for any NULL
shipping weight. It can be used as an estimate when NULLs are allowed.
SELECT client, NVL(Weight,43) FROM shipping;
CLIENT

NVL(WEIGHT,43)

-------------

--------------

JOHNSON TOOL

59

DAGG SOFTWARE

27

TULLY ANDOVER

43

ROUND and TRUNC:


DESCRIBE math
Name

Null?

Type

----------------------------------------- --------

----------------------------

NAME

VARCHAR2(12)

ABOVE

NUMBER

BELOW

NUMBER

EMPTY

NUMBER

SELECT Name, Above, Below, ROUND(Above,2), ROUND(Below,2), TRUNC(Above,2),


TRUNC(Below,2) FROM math;

NAME

ABOVE

BELOW ROUND(ABOVE,2) ROUND(BELOW,2) TRUNC(ABOVE,2)TRUNC(BELOW,2)

WHOLE NUMBER

11

LOW DECIMAL

33.33

MID DECIMAL

55.5

HIGH DECIMAL

66.666

-22
-44.44
-55.5
-77.777

11

-22

33.33
55.5
66.67

11

-22

-44.44

33.33

-44.44

-55.5

55.5

-55.5

-77.78

66.66

-77.77

Single and Group Functions:


DESCRIBE comfort
Name

Null?

Type

-----------------------------------------

--------

----------------------------

CITY

NOT NULL

VARCHAR2(13)

SAMPLEDATE

NOT NULL

DATE

NOON

NUMBER(3,1)

MIDNIGHT

NUMBER(3,1)

PRECIPITATION

NUMBER

SQL> SELECT AVG(Noon), COUNT(Noon), MAX(Noon), Min(Noon), SUM(Noon)


FROM comfort WHERE city = 'SAN FRANCISCO';
AVG(NOON) COUNT(NOON)

MAX(NOON) MIN(NOON) SUM(NOON)

----------

----------

----------

----------

62.5

51.1

166.2

55.4

----------3

SWING is the column heading for the maximum difference between the noon
temperatures, for example, low and high noon temperatures for a year.
SQL> SELECT city, AVG(noon), MAX(noon), MIN(noon),MAX(Noon) - MIN(Noon)
SWING FROM comfort GROUP BY city;
CITY

AVG(NOON) MAX(NOON)

MIN(NOON)

SWING

-------------

----------

----------

----------

----------

KEENE

54.4

99.8

-7.2

107

SAN FRANCISCO

55.4

62.5

51.1

11.4

Grouping items together, renaming columns in the output shown to users


DESCRIBE ledger
Name

Null?

Type

-----------------------------------------

-------- ----------------------------

ACTIONDATE

DATE

ACTION

VARCHAR2(8)

ITEM

VARCHAR2(30)

QUANTITY

NUMBER

QUANTITYTYPE

VARCHAR2(10)

RATE

NUMBER

AMOUNT

NUMBER(9,2)

PERSON

VARCHAR2(25)

SELECT person, SUM(amount) total FROM ledger WHERE action=PAID'


GROUP BY person HAVING person like 'P%' ORDER BY SUM(amount) DESC;
PERSON

TOTAL

-------------------------

----------

PAT LAVAY

PETER LAWSON

The above query is executed in this order:


1. WHERE action = 'PAID';
2. GROUP BY person
3. SUM(amount)
4. HAVING person LIKE 'P%';
5. ORDER BY SUM(amount) DESC
The query will execute faster if the WHERE clause further restricts the SELECT
clause :
add step 4 to step 1

SQL> SELECT person, SUM(amount) Total FROM ledger


WHERE action = 'PAID' AND person LIKE 'P%'
GROUP BY person ORDER BY SUM(amount) DESC;
PERSON

TOTAL

-------------------------

----------

PAT LAVAY

PETER LAWSON

Date Functions:
Sysdate returns the operating system current date and time:
SQL> select sysdate from dual;
SYSDATE
--------07-AUG-02
Dual is an Oracle table that has one column and one row. Using dual allows you to test
functions and select statements. For example, select POWER(4,3) from dual; returns:
SQL> select POWER(4,3) from dual;
POWER(4,3)
---------64
Which returns 4 raised to the 3th power, 4*4*4, or 64.
DATE FUNCTION

description

ADD_MONTHS(date, count)

adds count months to date

GREATEST(date1, date2,)

picks the latest date from the list of dates

LEAST(date1, date2, )

picks the earliest date from the list of dates

LAST_DAY(date)

gives the date of the last day of the month that date
is in.

MONTHS_BETWEEN(date2, date1) gives the date2-date1 in months


NEXT_DAY(date, day)

gives date of the next day after date, where day is


Monday, Tuesday.

NEW_TIME(date, this, other)

gives the date and time in this time zone. This is


replaced by the current time zone abbreviation,
other is replaced by the abbreviation for the time
zone for which you want to know the time and date.

ROUND(date, format)

without format specified, rounds a date to 12 AM if


time of date before noon, else rounds up to the next
day.

TRUNC(date, format)

without format specified, sets a date to 12 AM, the


beginning of the next day.

TO_CHAR(date, format)

reformats date according to format

TO_DATE(string, format)

converts a string into an Oracle date.

Examples:
SQL> DESC holiday
Name

Null?

Type

-----------------------------------------

-------- ----------------------

HOLIDAY

VARCHAR2(25)

ACTUALDATE

DATE

CELEBRATEDDATE

DATE

SQL> select * from holiday;


HOLIDAY

ACTUALDAT CELEBRATE

-------------------------

---------

---------

NEW YEAR DAY

01-JAN-95

01-JAN-95

MARTIN LUTHER KING, JR.

15-JAN-95

16-JAN-95

LINCOLNS BIRTHDAY

12-FEB-95

20-FEB-95

WASHINGTONS BIRTHDAY

22-FEB-95

20-FEB-95

FAST DAY, NEW HAMPSHIRE

22-FEB-95

22-FEB-95

MEMORIAL DAY

30-MAY-95

29-MAY-95

INDEPENDENCE DAY

04-JUL-95

04-JUL-95

LABOR DAY

04-SEP-95

04-SEP-95

COLUMBUS DAY

08-OCT-95

09-OCT-95

THANKSGIVING

23-NOV-95

23-NOV-95

10 rows selected.
Which holidays (in 1995) are not celebrated on the actual date?
SQL> SELECT holiday, actualdate, celebrateddate FROM holiday
WHERE celebrateddate - actualdate != 0;
HOLIDAY

ACTUALDAT CELEBRATE

-------------------------

---------

---------

MARTIN LUTHER KING, JR.

15-JAN-95

16-JAN-95

LINCOLNS BIRTHDAY

12-FEB-95

20-FEB-95

WASHINGTONS BIRTHDAY

22-FEB-95

20-FEB-95

MEMORIAL DAY

30-MAY-95

29-MAY-95

COLUMBUS DAY

08-OCT-95

09-OCT-95

Adding months:
SQL> SELECT ADD_MONTHS(celebrateddate, 6) FeastDay FROM holiday
WHERE holiday like 'FAST%';
FEASTDAY
--------22-AUG-95
Subtracting months, for example if reservations need to be made 6 months in advance:
SQL> SELECT ADD_MONTHS(celebrateddate, -6) -1 lastday FROM holiday
WHERE holiday = 'COLUMBUS DAY';
LASTDAY
--------08-APR-95
GREATEST/LEAST:
SQL> SELECT holiday, LEAST(actualdate, celebrateddate) first, actualdate,
celebrateddate FROM holiday WHERE actualdate - celebrateddate != 0;
HOLIDAY

FIRST

ACTUALDAT CELEBRATE

-------------------------

---------

---------

---------

MARTIN LUTHER KING, JR.

15-JAN-95

15-JAN-95

16-JAN-95

LINCOLNS BIRTHDAY

12-FEB-95

12-FEB-95

20-FEB-95

WASHINGTONS BIRTHDAY

20-FEB-95

22-FEB-95

20-FEB-95

MEMORIAL DAY

29-MAY-95

30-MAY-95

29-MAY-95

COLUMBUS DAY

08-OCT-95

08-OCT-95

09-OCT-95

The columns in the holiday table are date datatype, therefore the information returned is
correct. If the data is character type, you must use the TO_DATE function.
Incorrect data returned:
SQL> SELECT LEAST('20-JAN-95', '20-DEC-95') FROM dual;
LEAST('20
--------20-DEC-95
Correct data returned:
SQL> SELECT LEAST(TO_DATE('20-JAN-95'), TO_DATE('20-DEC-95')) FROM dual;
LEAST(TO_
--------20-JAN-95
Combining date functions:
Job review is given after 6 months on job:
SQL> SELECT sysdate TODAY, LAST_DAY(ADD_MONTHS(sysdate, 6)) + 1 REVIEW
FROM dual;
TODAY

REVIEW

---------

---------

07-AUG-02

01-MAR-03

ADD_MONTHS adds six months to the system date, sysdate. LAST_DAY returns the
last day of the month.
Creating views containing results of functions
The view is using a function to calculate a result and renaming the column in the
view.
LAST_DAY(actiondate) is renamed MONTH
SUM(amount) is renamed total
CREATE OR REPLACE view monthtotal

AS SELECT last_day(actiondate) MONTH, SUM(amount) Total


FROM ledger WHERE action = 'PAID' GROUP BY last_day(actiondate);
View created.
Oracle automatically takes the single word, MONTH without quotes and uses it to
rename the column it follows.
** do not use quotation marks around a column name, it may force the database to
store a column name in mixed case, and Oracle will have problems locating the
column later.
CREATE OR REPLACE view yeartotal AS
SELECT SUM(Amount) yeartotal
FROM ledger WHERE action = 'PAID';
View created.
Using both newly created views:
SQL> SELECT month, total, (total/yeartotal)*100 PERCENT
FROM monthtotal, yeartotal ORDER BY month;
MONTH

TOTAL

PERCENT

---------

----------

----------

31-JAN-01

3.5

5.90916765

28-FEB-01

1.5

2.53250042

31-MAR-01

6.75333446

30-APR-01

10

16.8833361

31-MAY-01

3.4

5.74033429

30-JUN-01

4.25

7.17541786

31-JUL-01

5.2

8.7793348

31-AUG-01

11.7

19.7535033

30-SEP-01

4.25

7.17541786

31-OCT-01

4.93

8.32348472

30-NOV-01

4.25

7.17541786

31-DEC-01

2.25

3.79875063

12 rows selected.
The VIEW yeartotal returns only one row therefore there is no need for a join
clause.
Using logic in a HAVING clause:
SELECT person, SUM(amount) total
FROM ledger WHERE action = 'PAID'
GROUP BY person
HAVING COUNT(item) > 1
ORDER BY SUM(amount) DESC;
The HAVING clause selects the persons that completed more than one task
The INSERT command allows you to place a row of information directly into a
table or indirectly through a view.
SQL> DESC comfort
Name

Null?

Type

-----------------------------------------

--------

-------------------

CITY

NOT NULL

VARCHAR2(13)

SAMPLEDATE

NOT NULL

DATE

NOON

NUMBER(3,1)

MIDNIGHT

NUMBER(3,1)

INSERT INTO comfort VALUES


(WALPOLE, TO_DATE(21-MAR-1993, DD-MON-YYYY), 56.7, 43.8, 0);
1 row created.
A character string must be inserted using single quote marks. Each field is separated by
commas, and the fields must be in the same order as the columns are when the table is
described. A date must be in single quote marks and in the default Oracle date format.
To insert a date not in the default format, use the TO_DATE function, with a formatting
mask as shown in the following:

INSERT into comfort VALUES (WALPOLE, TO_DATE(06/22/1993 1:35,


MM/DD/YYYY HH24:MI), 56.7, 43.8, 0);
1 row created.
Columns can also be inserted out of the order they appear when described, if the order
the data is in is listed. It doesnt change the order of the columns in the table, it just
allows you to list the data fields in a different order.
INSERT into comfort (sampledate, precipitation, city, noon, midnight) VALUES
(TO_DATE(23-SEP-1993, DD-MON-YYYY), NULL, WALPOLE, 86.3, 72.1);
1 row created.
You can also insert information that has been selected from a table. In the following
statement, columns selected from the comfort table, together with values for sampledate
and city are inserted:
INSERT into comfort (sampledate, precipitation, city, noon, midnight) SELECT
TO_DATE(22-DEC-1993, DD-MON-YYYY), precipitation, WALPOLE, noon, midnight
FROM comfort WHERE city=KEENE and sampledate=22_DEC-93;
1 row created.
SELECT * FROM comfort WHERE city = WALPOLE;
CITY

SAMPLEDAT

-------------

---------

WALPOLE

NOON

MIDNIGHT

PRECIPITATION

----------

----------

-------------

21-MAR-93

56.7

43.8

WALPOLE

22-JUN-93

56.7

43.8

WALPOLE

23-SEP-93

86.3

72.1

WALPOLE

22-DEC-93

-7.2

-1.2

3.9

4 rows selected.
You can use the APPEND hint to improve the performance of large inserts.

The

APPEND hint will tell the database to find the last block into which the tables data has

ever been inserted. The new record will be inserted starting in the next block following
the last previously used block. To specify the APPEND hint, use the following syntax:
INSERT /*+APPEND*/ INTO worker (name) SELECT name from prospect;
8 rows created.
Using the APPEND hint may increase the tables space requirements since new records
will not attempt to reuse the available space the table already has used.
UPDATE requires setting specific values for each column you wish to change
using a WHERE clause:

UPDATE comfort SET precipitation = .5, midnight = 73.1 WHERE city = WALPOLE;
4 rows updated.
You can also do calculations, string functions, and others when setting a value for
the UPDATE command.
UPDATE comfort SET midnight = midnight +1, noon = noon + 1 WHERE city
=WALPOLE;
4 rows updated.
SELECT * from comfort WHERE city = WALPOLE;
CITY
SAMPLEDAT
NOON MIDNIGHT
------------- ------------------ ---------WALPOLE
21-MAR-93
57.7
74.1
WALPOLE
22-JUN-93
57.7
74.1
WALPOLE
23-SEP-93
87.3
74.1
WALPOLE
22-DEC-93
-6.2
74.1
.5

PRECIPITATION
------------.5
.5
.5

UPDATE with embedded SELECT:


Set values in an update statement by embedding a select statement in the middle of
the update:
UPDATE comfort SET midnight = (SELECT temperature FROM weather WHERE city
= MANCHESTER) WHERE city = WALPOLE AND sampledate = TO_DATE(22DEC-1993, DD-MON-YYYY);
1 row updated.
When using subqueries with UPDATE you must make sure the subquery returns
one record for each of the updated records, otherwise the UPDATE will fail. You
can UPDATE multiple columns at once. The columns must be in parentheses and
separated by commas :

UPDATE comfort SET (noon, midnight) =


(SELECT humidity, temperature FROM weather
WHERE city = MANCHESTER)
WHERE city = WALPOLE
AND sampledate = TO_DATE(22-DEC-1993, DDMON-YYYY);
1 row updated.
DELETE removes one or more rows from a table. The WHERE clause selectively
deletes rows. Not using a WHERE clause will remove all rows.

DELETE from comfort WHERE city = WALPOLE;


4 rows deleted.
ROLLBACK : when you INSERT, UPDATE, or DELETE data from tables, you can
reverse the work youve done by issuing the ROLLBACK statement:
SQL> SELECT * from comfort WHERE city = 'WALPOLE';
no rows selected.
SQL> ROLLBACK;
Rollback complete.
SQL> SELECT * from comfort WHERE city = 'WALPOLE';
CITY

SAMPLEDAT

------------- ---------

NOON MIDNIGHT PRECIPITATION


---------- ----------

-------------

WALPOLE

21-MAR-93

56.7

43.8

WALPOLE

22-JUN-93

56.7

43.8

WALPOLE

23-SEP-93

86.3

72.1

WALPOLE

22-DEC-93

-7.2

-1.2

3.9

Advanced use of FUNCTIONS and VARIABLES:


Functions can be used in an ORDER BY clause to change the sorting sequence.
The SUBSTR function below causes the list of authors to be put in alphabetical
order by first name, by using the embedded function, INSTR. INSTR searches in a
string for a certain set of characters, using two parameters. The first parameter
tells INSTR which string to search, for example, the author column. The second
parameter is the character to be found, in this case, the comma. INSTR returns

the number position of the comma in the string.

SUBSTR orders the string

starting with this position, the comma plus two characters, or the first name.
SELECT author FROM magazine ORDER BY SUBSTR(author, INSTR(author, ,)+2);
AUTHOR
------------------------WHITEHEAD, ALFRED
BONHOEFFER, DIETRICH
CHESTERTON, G.K.
RUTH, GEORGE HERMAN
CROOKES, WILLIAM
Translate converts characters in a string into different characters, based on a
substitution string. TRANSLATE(string, if, then)
SELECT TRANSLATE ( NOW VOWELS ARE UNDER ATTACK, TAEIOU, Taeiou)
FROM dual;
When any of the characters in TAEIOU are found they are replaced with the
corresponding character in Taeiou. The change is all upper case vowels are
replaced with lower case vowels.
TRANSLATE('NOWVOWELSAREUNDER
---------------------------NoW VoWeLS aRe uNDeR attack
You can eliminate characters by using no corresponding character in the then
string:
SELECT TRANSLATE ( NOW VOWELS ARE UNDER ATTACK, TAEIOU, T) FROM
dual;
TRANSLATE('NOWVOWEL
------------------NW VWLS R NDR TTCK

All the upper case vowels are replaced by nothing.

TRANSLATE is useful in

cleaning up data. For example, instead of using LTRIM and RTRIM, TRANSLATE
can be used:
SELECT title FROM magazine;
TITLE
------------------------------------THE BARBERS WHO SHAVE THEMSELVES.
"HUNTING THOREAU IN NEW HAMPSHIRE"
THE ETHNIC NEIGHBORHOOD
RELATIONAL DESIGN AND ENTHALPY
"INTERCONTINENTAL RELATIONS."
SELECT LTRIM(RTRIM(title,.),) FROM magazine;
LTRIM(RTRIM(TITLE,'."'),'"')
------------------------------------THE BARBERS WHO SHAVE THEMSELVES
HUNTING THOREAU IN NEW HAMPSHIRE
THE ETHNIC NEIGHBORHOOD
RELATIONAL DESIGN AND ENTHALPY
INTERCONTINENTAL RELATIONS
Can be also cleaned up by using:
SELECT TRANSLATE(title, T.,T) title FROM magazine;
TITLE
------------------------------------THE BARBERS WHO SHAVE THEMSELVES
HUNTING THOREAU IN NEW HAMPSHIRE
THE ETHNIC NEIGHBORHOOD
RELATIONAL DESIGN AND ENTHALPY
INTERCONTINENTAL RELATIONS

Sample table : Store_information


Table layout:
Column1

column2

column3

Store_name

sales

Date

Los Angeles

$1500

Jan-05-1999

San Diego

$250

Jan-07-1999

Los Angeles

$300

Jan-08-1999

Boston

$700

Jan-08-1999

SELECT A1.store_name Store, SUM(A1.Sales Total Sales


FROM Store_Information A1
GROUP BY A1.store_name;

Das könnte Ihnen auch gefallen