You are on page 1of 35

1

Allsofthelp.c om 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 NAME AGE LODGING 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>; Null? Type ---------------------------NUMBER VARCHAR2(15) ----------------------------------------- --------

They are

NOT NULL VARCHAR2(25)

Allsofthelp.c om

SQL> DESCRIBE worker Name NAME AGE LODGING Null? Type ---------------------------NUMBER VARCHAR2(15) ----------------------------------------- --------

NOT NULL VARCHAR2(25)

SQL> SELECT age, name FROM worker; AGE ---------22 43 16 33 15 27 41 21 18 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

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

Allsofthelp.c om
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 ------------------------WILLIAM SWING HELEN BRANDT DONALD ROLLO DICK JONES PAT LAVAY BART SARJEANT ADAH TALBOT PETER LAWSON JOHN PEARSON ANDREW DYE VICTORIA LYNN NAME ------------------------JED HOPKINS ROLAND BRANDT GEORGE OSCAR ELBERT TALBOT GERHARDT KENTGEN WILFRED LOWELL AGE ---------15 15 16 18 21 22 23 25 27 29 32 AGE ---------33 35 41 43 55 67 ROSE HILL WEITBROCHT MATTS ROSE HILL ROSE HILL CRANMER PAPA KING CRANMER ROSE HILL ROSE HILL MULLERS LODGING --------------MATTS MATTS ROSE HILL WEITBROCHT PAPA KING LODGING --------------CRANMER

KAY AND PALMER WALLBOM RICHARD KOCH AND BROTHERS

The following restrict the rows returned by using a WHERE clause: SELECT <column_name> FROM <table_name> WHERE <condition>;

Allsofthelp.c om
SQL> DESCRIBE newspaper Name ----------------------------------------FEATURE SECTION PAGE Null? -------NOT NULL Type -------------------VARCHAR2(15) CHAR(1) NUMBER

SQL> SELECT Feature, Section, Page FROM newspaper WHERE Section = 'F'; FEATURE --------------Births Classified Obituaries Doctor Is In F F F F S PAGE ---------7 8 6 6

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 --------------Births Classified Doctor Is In Obituaries F F F F S PAGE ---------7 8 6 6

Using ORDER BY with more than one selection: SQL> SELECT feature, section, page FROM newspaper WHERE section =F ORDER BY page, feature; FEATURE S PAGE

Allsofthelp.c om
--------------Doctor Is In Obituaries Births Classified F F F F ---------6 6 7 8

Changing the page ordering to DESCENDING order: SQL> SELECT feature, section, page FROM newspaper WHERE section =F ORDER BY page DESC, feature; FEATURE --------------Classified Births Doctor Is In Obituaries F F F F S PAGE ---------8 7 6 6

Using GREATER THAN to restrict the rows returned: SQL> SELECT feature, section, page FROM newspaper WHERE page >4; FEATURE --------------Editorials Television Births Classified Obituaries Doctor Is In A B F F F F S PAGE ---------12 7 7 8 6 6

SQL> SELECT feature, section, page FROM newspaper WHERE section >B; FEATURE --------------Sports Business Weather Births D E C F S PAGE ---------1 1 2 7

Allsofthelp.c om
Classified Comics Obituaries Doctor Is In F C F F 8 4 6 6

Using NOT EQUALS: SQL> SELECT feature, section, page FROM newspaper WHERE page !=1; FEATURE --------------Editorials Weather Television Births Classified Comics Movies Bridge Obituaries Doctor Is In A C B F F C B B F F S PAGE ---------12 2 7 7 8 4 4 2 6 6

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 --------------Modern Life Movies B B S PAGE ---------1 4

_ (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 %

Allsofthelp.c om
SQL> SELECT feature, section, page FROM newspaper WHERE feature LIKE __i%; FEATURE --------------Editorials Bridge Obituaries S A B F 6 PAGE ---------12 2

Matches any word with two os : SQL> SELECT feature, section, page FROM newspaper WHERE feature LIKE '%o%o%'; FEATURE --------------Doctor Is In S F PAGE ---------6

Restricting data using NULL or NOT NULL WHERE clauses: SQL> SELECT city, sampledate, precipitation FROM comfort WHERE Precipitation IS NOT NULL; CITY ------------KEENE KEENE SAN FRANCISCO SAN FRANCISCO SAN FRANCISCO SAN FRANCISCO KEENE NULL; CITY ------------KEENE SAMPLEDAT --------23-SEP-93 PRECIPITATION ------------SAMPLEDAT --------22-JUN-93 22-DEC-93 21-MAR-93 22-JUN-93 23-SEP-93 22-DEC-93 21-MAR-93 PRECIPITATION ------------1.3 3.9 .5 .1 .1 2.3 4.4

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

Restricting data using IN or NOT IN WHERE clauses:

Allsofthelp.c om

SELECT feature, section, page FROM newspaper WHERE section IN ('A', 'B', 'F'); FEATURE --------------Editorials Television Births Classified Modern Life Movies Bridge Obituaries Doctor Is In A B F F B B B F F S PAGE ---------1 12 7 7 8 1 4 2 6 6

National News A

SELECT feature, section, page FROM newspaper WHERE section NOT IN ('A', 'B', 'F'); FEATURE --------------Sports Business Weather Comics D E C C S PAGE ---------1 1 2 4

Restricting data using BETWEEN in a WHERE clause: SELECT feature, section, page FROM newspaper WHERE page BETWEEN 7 and 10; FEATURE --------------- Television Births Classified B F F S PAGE ---------7 7 8

Restricting data using WHERE clauses with multiple restrictions: SELECT feature, section, page FROM newspaper WHERE section =F AND page > 7; FEATURE S PAGE

Allsofthelp.c om
--------------Classified F ---------8

SELECT feature, section, page FROM newspaper WHERE section = F OR page > 7; FEATURE --------------Editorials Births Classified Obituaries Doctor Is In A F F F F S PAGE ---------12 7 8 6 6

SELECT feature, section, page FROM newspaper WHERE section = F AND page BETWEEN 7 AND 10; FEATURE --------------Births Classified F F S PAGE ---------7 8

SELECT feature, section, page FROM newspaper WHERE section =A OR section = 'B' AND page > 2; FEATURE --------------National News Editorials Television Movies S A A B B PAGE ---------1 12 7 4

SELECT feature, section, page FROM newspaper WHERE section = A AND page > 2 OR section = 'B'; FEATURE --------------Editorials Television A B S PAGE ---------12 7

10

Allsofthelp.c om
Modern Life Movies Bridge B B B 1 4 2

SELECT feature, section, page FROM newspaper WHERE page >2 AND section = 'A' OR section = 'B'; FEATURE ---------------Editorials Television Movies Bridge A B 1 4 2 B B S PAGE ---------12 7

Modern Life B

Using parenthesis and WHERE clauses: SELECT feature, section, page FROM newspaper WHERE page > 2 AND (section = 'A' OR section = 'B'); FEATURE --------------Editorials Television Movies A B B S PAGE ---------12 7 4

SELECT section FROM newspaper WHERE feature = Doctor Is In; S F SELECT feature FROM newspaper WHERE section = F; FEATURE --------------Births Classified Obituaries

11

Allsofthelp.c om
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 --------------Sports Editorials Business Weather Television Modern Life Comics Movies Bridge D A E C B B C B B S PAGE ---------1 1 12 1 2 7 1 4 4 2

National News A

Selecting from more than one table: First select from weather, then location, then combine the two:

12

Allsofthelp.c om

SELECT city, condition, temperature FROM weather; CITY ----------LIMA PARIS MANCHESTER ATHENS CHICAGO SYDNEY SPARTA CONDITION TEMPERATURE --------RAIN CLOUDY FOG SUNNY RAIN SNOW CLOUDY ----------45 81 66 97 66 29 74

SELECT city, longitude, eastwest, latitude, northsouth FROM location; CITY ATHENS CHICAGO CONAKRY LIMA MADRAS MANCHESTER MOSCOW PARIS SHENYANG ROME TOKYO CITY SYDNEY SPARTA MADRID LONGITUDE 23.43 87.38 13.43 77.03 80.17 2.15 37.35 2.2 123.27 12.29 139.46 LONGITUDE 151.13 22.27 3.41 E LATITUDE N E W W W E W E E E E E ---------- 37.58 41.53 9.31 12.03 13.05 53.3 55.45 48.52 41.48 41.54 35.42 N N N S N N N N N N N ------------------------- ----------

E LATITUDE N E E W 33.52 37.05 40.24 S N N

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

13

Allsofthelp.c om

SELECT weather.city, condition, temperature, latitude, northsouth, longitude, eastwest FROM weather, location WHERE weather.city = location.city; CITY ----------ATHENS CHICAGO LIMA PARIS SPARTA SYDNEY CONDITION TEMPERATURE LATITUDE N LONGITUDE E --------SUNNY RAIN RAIN CLOUDY CLOUDY SNOW ----------97 66 45 66 81 74 29 ---------37.58 41.53 12.03 53.3 48.52 37.05 33.52 N N S N N N S ---------- 23.43 87.38 77.03 2.15 2.2 22.27 151.13 E W W W E E E

MANCHESTER FOG

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 CITY CONDITION TEMPERATURE LATITUDE NORTHSOUTH LONGITUDE EASTWEST Null? Type VARCHAR2(11) VARCHAR2(9) NUMBER NUMBER CHAR(1) NUMBER CHAR(1) ----------------------------------------- -------- ----------------------------

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

14

Allsofthelp.c om
CITY ----------ATHENS CHICAGO LIMA PARIS SPARTA SYDNEY CONDITION TEMPERATURE LATITUDE N LONGITUDE E --------SUNNY RAIN RAIN CLOUDY CLOUDY SNOW ----------97 66 45 66 81 74 29 ---------37.58 41.53 12.03 53.3 48.52 37.05 33.52 N N S N N N S ---------23.43 87.38 77.03 2.15 2.2 22.27 151.13 E W W W E E E

MANCHESTER FOG

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

15

Allsofthelp.c om
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

16

Allsofthelp.c om

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:

17

Allsofthelp.c om
Use: concatenates two strings together CONCATenates two strings together INITial CAPital. Changes the first letter of a word to uppercase.

Function Name || CONCAT INITCAP

INSTR Finds the location of a character IN a STRing. LENGTH LOWER 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 SUBSTR UPPER 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,'.') ----------------------------------LIMA............................... PARIS.............................. MANCHESTER......................... ATHENS............................. CHICAGO............................ SYDNEY............................. SPARTA............................. TEMPERATURE ----------45 81 66 97 66 29 74 Finds words that SOUND like the EXample passed in. SUBSTRing. Clips out a piece of a string. Converts every letter in a string to UPPERcase. Returns the LENGTH of a string. converts every letter in a string to LOWER case.

18

Allsofthelp.c om

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 MANCHESTER ATHENS CHICAGO SYDNEY SPARTA of strings: SELECT LTRIM(RTRIM(Title,'."'),'"') FROM magazine; Original output: SELECT name, title, page FROM magazine; NAME ---------------TITLE ------------------------------------PAGE ---------70 320 246 279 20 ----------45 81 66 97 66 29 74

Using both functions to trim off unwanted characters from the right and left ends

BERTRAND MONTHLY THE BARBERS WHO SHAVE THEMSELVES. LIVE FREE OR DIE "HUNTING THOREAU IN NEW HAMPSHIRE" PSYCHOLOGICA FADED ISSUES ENTROPY WIT 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: THE ETHNIC NEIGHBORHOOD RELATIONAL DESIGN AND ENTHALPY "INTERCONTINENTAL RELATIONS."

19

Allsofthelp.c om

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-^-^-^-^-^-^-^PSYCHOLOGICA FADED ISSUES ENTROPY WIT THE ETHNIC NEIGHBORHOOD-^-^-^-^-^-^-^-^-^-^-^-^ RELATIONAL DESIGN AND ENTHALPY-^-^-^-^-^-^-^-^INTERCONTINENTAL RELATIONS-^-^-^-^-^-^-^-^-^-^320 246 279 20

NUMBER Functions: Function Value1 + value2 Value1 value2 Value1 * value2 Value1 / value2 ABS(value) CEIL(value) COS(value) COSH(value) EXP(value) FLOOR(value) LN(value) LOG(value) MOD(value) NVL(value) POWER(value) ROUND(value) SIGN(value) SIN(value) SINH(value) SQRT(value) Definition Addition Subtraction Multiplication Division ABSolute value Smallest integer larger than or equal to value COSine of value Hyberbolic COSine of value e raised to value EXPonent Largest integer smaller than or equal to value Natural logarithm of value Base 10 LOGarithm of value MODulus Substitute for value if value is NULL value raised to an exponent POWER ROUNDing of value to precision 1 if value is positive, -1 is value is negative, 0 if value is 0 SINe of value Hyperbolic SINe of value SQuare RooT of value

20

Allsofthelp.c om
TANgent of value Hyperbolic TANgent of value value TRUNCated to precision of value storage size of value in Oracle AveraGe of value for group of rows COUNT of rows for value MAXimum of all values for group of rows MINimum of all values for group of rows StanDard DEViation of all values for group of rows SUM of all values for group of rows VARIANCE of all values for group of tows LEAST value in list

TAN(value) TANH(value) TRUNC(value) VSIZE(value) GROUP Number Functions: AVG(value) COUNT(value) MAX(value) MIN(value) STDDEV(value) SUM(value) VARIANCE(value) LEAST(value1, value2..) Examples: DESCRIBE shipping Name CLIENT WEIGHT

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

Null?

Type VARCHAR2(13) NUMBER

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

SELECT client, weight FROM shipping; CLIENT ------------JOHNSON TOOL DAGG SOFTWARE 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. WEIGHT ---------59 27

21

Allsofthelp.c om

SELECT client, NVL(Weight,43) FROM shipping; CLIENT ------------JOHNSON TOOL DAGG SOFTWARE TULLY ANDOVER ROUND and TRUNC: DESCRIBE math Name NAME ABOVE BELOW EMPTY Null? Type ---------------------------VARCHAR2(12) NUMBER NUMBER NUMBER ----------------------------------------- -------NVL(WEIGHT,43) -------------59 27 43

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 LOW DECIMAL MID DECIMAL HIGH DECIMAL

11 33.33 55.5 66.666

-22 -44.44 -55.5 -77.777

11 33.33 55.5 66.67

-22 -44.44 -55.5 -77.78

11 33.33 55.5 66.66

-22 -44.44 -55.5 -77.77

Single and Group Functions: DESCRIBE comfort Name ----------------------------------------Null? -------Type ----------------------------

22
CITY

Allsofthelp.c om
NOT NULL NOT NULL VARCHAR2(13) DATE NUMBER(3,1) NUMBER(3,1) NUMBER

SAMPLEDATE NOON MIDNIGHT PRECIPITATION

SQL> SELECT AVG(Noon), COUNT(Noon), MAX(Noon), Min(Noon), SUM(Noon) FROM comfort WHERE city = 'SAN FRANCISCO'; AVG(NOON) COUNT(NOON) ---------55.4 ----------3 MAX(NOON) MIN(NOON) SUM(NOON) ---------62.5 ---------51.1 ---------166.2

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 ------------KEENE SAN FRANCISCO AVG(NOON) MAX(NOON) ---------54.4 55.4 ---------99.8 62.5 MIN(NOON) ----------7.2 51.1 SWING ---------107 11.4

Grouping items together, renaming columns in the output shown to users DESCRIBE ledger Name ----------------------------------------ACTIONDATE ACTION ITEM QUANTITY Null? Type DATE VARCHAR2(8) VARCHAR2(30) NUMBER -------- ----------------------------

23

Allsofthelp.c om
VARCHAR2(10) NUMBER NUMBER(9,2) VARCHAR2(25)

QUANTITYTYPE RATE AMOUNT PERSON

SELECT person, SUM(amount) total FROM ledger WHERE action=PAID' GROUP BY person HAVING person like 'P%' ORDER BY SUM(amount) DESC; PERSON ------------------------PAT LAVAY PETER LAWSON TOTAL ---------3 3

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 ------------------------PAT LAVAY PETER LAWSON Date Functions: TOTAL ---------3 3

24

Allsofthelp.c om

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 ADD_MONTHS(date, count) GREATEST(date1, date2,) LEAST(date1, date2, ) LAST_DAY(date) description adds count months to date picks the latest date from the list of dates picks the earliest date from the list of dates 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) NEW_TIME(date, this, other) gives date of the next day after date, where day is Monday, Tuesday. 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) TO_CHAR(date, format) without format specified, sets a date to 12 AM, the beginning of the next day. reformats date according to format

25

Allsofthelp.c om
converts a string into an Oracle date.

TO_DATE(string, format) Examples: SQL> DESC holiday Name ----------------------------------------HOLIDAY ACTUALDATE CELEBRATEDDATE SQL> select * from holiday; HOLIDAY ------------------------NEW YEAR DAY MARTIN LUTHER KING, JR. LINCOLNS BIRTHDAY WASHINGTONS BIRTHDAY FAST DAY, NEW HAMPSHIRE MEMORIAL DAY INDEPENDENCE DAY LABOR DAY COLUMBUS DAY THANKSGIVING 10 rows selected.

Null?

Type VARCHAR2(25) DATE DATE

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

ACTUALDAT CELEBRATE --------01-JAN-95 15-JAN-95 12-FEB-95 22-FEB-95 22-FEB-95 30-MAY-95 04-JUL-95 04-SEP-95 08-OCT-95 23-NOV-95 --------01-JAN-95 16-JAN-95 20-FEB-95 20-FEB-95 22-FEB-95 29-MAY-95 04-JUL-95 04-SEP-95 09-OCT-95 23-NOV-95

Which holidays (in 1995) are not celebrated on the actual date? SQL> SELECT holiday, actualdate, celebrateddate FROM holiday WHERE celebrateddate - actualdate != 0; HOLIDAY ------------------------MARTIN LUTHER KING, JR. LINCOLNS BIRTHDAY WASHINGTONS BIRTHDAY ACTUALDAT CELEBRATE --------15-JAN-95 12-FEB-95 22-FEB-95 --------16-JAN-95 20-FEB-95 20-FEB-95

26

Allsofthelp.c om
30-MAY-95 08-OCT-95 29-MAY-95 09-OCT-95

MEMORIAL DAY COLUMBUS DAY 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 ------------------------MARTIN LUTHER KING, JR. LINCOLNS BIRTHDAY WASHINGTONS BIRTHDAY MEMORIAL DAY COLUMBUS DAY FIRST --------15-JAN-95 12-FEB-95 20-FEB-95 29-MAY-95 08-OCT-95 ACTUALDAT CELEBRATE --------15-JAN-95 12-FEB-95 22-FEB-95 30-MAY-95 08-OCT-95 --------16-JAN-95 20-FEB-95 20-FEB-95 29-MAY-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 ---------

27

Allsofthelp.c om

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 --------07-AUG-02 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. REVIEW --------01-MAR-03

ADD_MONTHS adds six months to the system date, sysdate. LAST_DAY returns the

28

Allsofthelp.c om

** 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 --------31-JAN-01 28-FEB-01 31-MAR-01 30-APR-01 31-MAY-01 30-JUN-01 31-JUL-01 31-AUG-01 30-SEP-01 31-OCT-01 30-NOV-01 31-DEC-01 TOTAL ---------3.5 1.5 4 10 3.4 4.25 5.2 11.7 4.25 4.93 4.25 2.25 PERCENT ---------5.90916765 2.53250042 6.75333446 16.8833361 5.74033429 7.17541786 8.7793348 19.7535033 7.17541786 8.32348472 7.17541786 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:

29

Allsofthelp.c om

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 ----------------------------------------CITY SAMPLEDATE NOON MIDNIGHT 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. Null? -------NOT NULL NOT NULL Type ------------------VARCHAR2(13) DATE NUMBER(3,1) NUMBER(3,1)

30

Allsofthelp.c om

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 ------------WALPOLE WALPOLE WALPOLE WALPOLE 4 rows selected. You can use the APPEND hint to improve the performance of large inserts. The SAMPLEDAT --------21-MAR-93 22-JUN-93 23-SEP-93 22-DEC-93 NOON ---------56.7 56.7 86.3 -7.2 MIDNIGHT ---------43.8 43.8 72.1 -1.2 3.9 PRECIPITATION ------------0 0

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.

31

Allsofthelp.c om

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

32

Allsofthelp.c om
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 WALPOLE WALPOLE WALPOLE WALPOLE SAMPLEDAT 21-MAR-93 22-JUN-93 23-SEP-93 22-DEC-93 NOON MIDNIGHT PRECIPITATION ---------- ---------56.7 56.7 86.3 -7.2 43.8 43.8 72.1 -1.2 3.9 ------------0 0

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

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.

33

Allsofthelp.c om

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. can be used: TRANSLATE is useful in

cleaning up data. For example, instead of using LTRIM and RTRIM, TRANSLATE

34

Allsofthelp.c om

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

35

Allsofthelp.c om

Sample table : Store_information Table layout: Column1 Store_name Los Angeles San Diego Los Angeles Boston $700 column2 sales $1500 $250 $300 column3 Date Jan-05-1999 Jan-07-1999 Jan-08-1999 Jan-08-1999

SELECT A1.store_name Store, SUM(A1.Sales Total Sales FROM Store_Information A1 GROUP BY A1.store_name;