Professional Documents
Culture Documents
COMMAND SELECT: To extract data from a database. To select all columns SELECT * FROM TABLE NAME: will select all the Records/columns in the Table Name, and store them in a results table called the Result-Set.
CITY TEXAS LA NY
SELECT * FROM CUSTOMERS; The Result-Set is: P_ID LAST_NAME 1 JOHNSON 2 GOMES 3 MARK
CITY TEXAS LA NY
2.
To select specific columns SELECT COLUMN_NAME( S) FROM TABLE_NAME : used to extract certain columns from a table
CITY TEXAS LA NY
SELECT LAST_NAME, FIRST NAME FROM PERSONS; The Result-Set is: LAST_NAME JOHNSON GOMES MARK
3.
To suppress duplicates SELECT DISTINCT COLUMN_NAME( S) FROM TABLE_NAME: The DISTINCT keyword is used to return only distinct/different values.
CITY TEXAS NY NY
SELECT DISTINCT CITY FROM PERSONS; The Result-Set is: CITY TEXAS NY CUSTOMERS C_ID FIRST_NAME 1 JAMIE 2 KAREN 3 EDDIE
4.
USING ARITHMETIC OPERATORS ( +, -, *, / , %) %, Modulo returns the integer remainder of a division. 5%2=1 6%2=0
CITY TEXAS NY NY
SELECT P_ID, FIRST_NAME, PURCHASE+200 FROM CUSTOMERS; The Result-Set is: P_ID FIRST_NAME 1 JAMIE 2 KAREN 3 EDDIE
5.
OPERATOR PRECEDENCE * / + -
CITY TEXAS NY NY
The Result-Set is: P_ID FIRST_NAME 1 JAMIE 2 KAREN 3 EDDIE 6. USING PARENTHESES Parentheses are given priority. CUSTOMERS P_ID FIRST_NAME 1 JAMIE 2 KAREN 3 EDDIE
CITY TEXAS NY NY
SELECT P_ID, FIRST_NAME, 3*(PURCHASE+100) FROM CUSTOMERS; The Result-Set is: P_ID FIRST_NAME 1 JAMIE 2 KAREN 3 EDDIE 7. DEFINING A COLUMN ALIAS: An alias name can be given to a table or to a column. Useful when Table or column names are long and complex. # Single quotes cant be used while defining an alias. CUSTOMERS P_ID FIRST_NAME 1 JAMIE 2 KAREN 3 EDDIE
CITY TEXAS NY NY
SELECT P_ID AS ID, FIRST_NAME F_NAME FROM CUSTOMERS; OR SELECT P_ID ID, FIRST_NAME F_NAME FROM CUSTOMERS; The Result-Set is: ID F_NAME 1 JAMIE 2 KAREN 3 EDDIE
8.
USING CONCATENATIO N OPERATOR: The || (double pipe) symbol concatenates two strings.
CITY TEXAS NY NY
SELECT FIRST_NAME || ADDRESS AS CUSTOMER_INFO FROM CUSTOMERS; The Result-Set is: CUSTOMER_INFO JAMIE BARGE 23 KAREN STREET 68 EDDIE VIERSEN 7 # AS KEYWORD IS NOT NECESSARY TO USE.
9.
SELECT FIRST_NAME|| , || ADDRESS CUSTOMER_INFO FROM CUSTOMERS; The Result-Set is: CUSTOMER_INFO JAMIE ,BARGE 23 KAREN ,STREET 68 EDDIE ,VIERSEN 7
10.
#Statements such as is a, to, from etc. can be used. DISPLAYING TABLE STRUCTURE: Displays the information about the structure of the table.
DESCRIBE CUSTOMERS NAME _________ P-ID FIRST_NAME PURCHASE ADDRESS CITY NULL TYPE _______ ____________ NOT NULL VARCHAR(20) VARCHAR(20) NUMBER VARCHAR(20) VARCHAR(20)
11.
WHERE CLAUSE: Used to extract only those records that fulfil a specified criterion.
CITY TEXAS NY NY
SELECT * FROM CUSTOMERS WHERE CITY='NY'; The Result-Set is: P_ID 2 3 LAST_NAM E GOMES MARK FIRS_TNAME KAREN EDDIE ADDRESS STREET 68 VIERSEN 7 CITY NY NY
# With the WHERE clause, the following operators can be used: = (equals) <> (not equal to) , > (greater than), < (less than), >= (GT or equal), <= (LT or equal) BETWEEN (Between an inclusive range) LIKE (Search for a pattern) IN (If know exact value want to return for at least one of the columns) ## Character strings & date values are enclosed in single or double quotation marks.
### Character values are case sensitive & date values are format sensitive. Default date format DD-MM-YY. #### Numeric values should not be closed in quotes. 12. WHERE CLAUSE USING OPERATORS CUSTOMERS P_ID FIRST_NAME 1 JAMIE 2 KAREN 3 EDDIE
CITY TEXAS NY NY
SELECT FIRST_NAME, PURCHASE FROM CUSTOMERS WHERE PURCHASE>=2000 The Result-set is: FIRST_NAME PURCHASE JAMIE 3000 EDDIE 2500 13. WHERE CLAUSE USING BETWEEN CONDITION: To display rows based on a range values CUSTOMERS P_ID FIRST_NAME 1 JAMIE 2 KAREN 3 EDDIE 4 IAN 5 FIONA
SELECT FIRST_NAME, PURCHASE FROM CUSTOMERS WHERE PURCHASE BETWEEN 2200 AND 3000; The Result-Set is: FIRST_NAME PURCHASE JAMIE 3000 EDDIE 2500 FIONA 2200
14.
SELECT FIRST_NAME, CITY FROM CUSTOMERS WHERE CITY IN (NY, LA); The Result-Set is: P_ID FIRST_NAME 2 KAREN 3 EDDIE 4 IAN
CITY NY NY LA
15
WHERE CLAUSE USING LIKE CONDITION: to perform wildcard searches of valid search string values Search conditions can contain either literal characters or numbers: % denote zero or many characters Underscore (_) The underscore is the singlecharacter wildcard.
# C% Find Values that starts with C ## %C Find Values that ends with C CUSTOMERS P_ID FIRST_NAME 1 JAMIE 2 KAREN 3 EDDIE 4 IAN 5 FIONA
SELECT FIRST_NAME FROM CUSTOMERS WHERE FIRST_NAME LIKE %E; The Result-Set is: P_ID FIRST_NAME 1 JAMIE 3 EDDIE SELECT * FROM CUSTOMERS WHERE CITY LIKE N_; P_ID 2 3 FIRST_NAME KAREN EDDIE PURCHASE 2000 2500 ADDRESS STREET 68 VIERSEN 7 CITY NY NY
16.
USING ESCAPE CHARACTER: To search for the actual % & _ symbols present in the entries.
# USE \ OR % SYMBOL FOR DEFINING ESCAPE IDENTIFIER CUSTOMERS P_ID FIRST_NAME 1 JAMIE% 2 KAREN 3 EDDIE_ 4 ELPH_ 5 JOHN%
SELECT P_ID, FIRST_NAME FROM CUSTOMERS WHERE FIRST_NAME LIKE J%\% ESCAPE \; The Result-Set is: P_ID FIRST_NAME 1 JAMIE% 5 JOHN% ALSO SELECT P_ID, FIRST_NAME FROM CUSTOMERS WHERE FIRST_NAME LIKE E%!_ ESCAPE !; The Result-Set is: P_ID FIRST_NAME 3 EDDIE_ 4 ELPH_
17.
SELECT * FROM CUSTOMERS WHERE FIRST_NAME NOT LIKE E%; The Result-Set is: P_ID FIRST_NAME 1 JAMIE 2 KAREN 5 FIONA
18.
LOGICAL OPERATORS (AND, OR, NOT) Logical operators separate two or more conditions in the WHERE clause of an SQL statement.
MEANING Returns true if both component conditions are true Returns true if either component condition is true Returns true if the following condition is false
USING THE AND OPERATOR # Display records which fulfil both the conditions altogether.
EMPLOYEES E_ID FIRST_NAME YEARS_EMPL 101 178 154 87 184 JAMIE KAREN EDDIE ELPH FIONA 2 5 8 4 10
LEAVES_TAK EN 4 50 80 35 125
SELECT E_ID, FIRST_NAME, SALARY FROM EMPLOYEES WHERE SALARY>=20000 AND FIRST_NAME LIKE E% The Result-Set is: EMPLOYEES E_ID FIRST_NAME SALARY 154 EDDIE 50000 87 ELPH 30000 SELECT E_ID, FIRST_NAME, YEARS_EMPL, LEAVES_TAKEN FROM EMPLOYEES WHERE YEARS_EMPL>=5 AND LEVAES_TAKEN>40; The Result-Set is: EMPLOYEES E_ID FIRST_NAME 178 KAREN 154 EDDIE 184 FIONA
YEARS_EMPL 5 8 10
LEAVES_TAKEN 50 80 125
EMPLOYEES E_ID FIRST_NAME YEARS_EMPL 101 178 154 87 184 JAMIE KAREN EDDIE ELPH FIONA 2 5 8 4 10
LEAVES_TAK EN 4 50 80 35 125
SELECT E_ID, FIRST_NAME, SALARY FROM EMPLOYEES WHERE SALARY>=50000 OR FIRST_NAME LIKE J%; The Result-set is: E_ID FIRST_NAME 101 JAMIE 154 EDDIE 184 FIONA
YEARS_EMPL 2 8 10
LEAVES_TAKEN 4 80 125
USING THE NOT OPERATOR # NOT means just that. If the condition it applies to evaluates to TRUE, NOT make it FALSE. If the condition after the NOT is FALSE, it becomes TRUE. ## The NOT operator can also be used with other SQL operators, such as BETWEEN, LIKE, NULL.
EMPLOYEES E_ID FIRST_NAME YEARS_EMPL 101 178 154 87 184 JAMIE KAREN EDDIE ELPH FIONA 2 5 8 4 10
LEAVES_TAK EN 4 50 80 35 125
SELECT E_ID , FIRST_NAME, SALARY FROM EMPLOYEES WHERE SALARY NOT IN(20000,30000); The Result-Set is: EMPLOYEES E_ID FIRST_NAME 178 KAREN 154 EDDIE 184 FIONA
YEARS_EMPL 5 8 10
LEAVES_TAKEN 50 80 125
19.
USING SET OPERATORS UNION UNION returns the results of two queries minus the duplicate rows.
PLAYER_NAM E 47 JOHN 85 JAMIE 88 KELLY 48 EDDIE 32 CLARKSON SELECT PLAYER_NAME FROM SOCCER UNION SELECT PLAYER_NAME FROM GOLF; The Result-Set is: PLAYER_NAME JOHN CRAIG KELLY JOHNSON ALBERT JAMIE EDDIE CLARKSON 8 ROWS ARE SELECTED. DUPLICATE ROWS ARE NOT REPAETED. SELECT PLAYER_NAME FROM SOCCER UNION ALL SELECT PLAYER_NAME FROM GOLF PLAYER_NAME JOHN CRAIG KELLY JOHNSON ALBERT JOHN JAMIE KELLY EDDIE CLARKSON
UNION ALL UNION ALL works just like UNION except it does not eliminate duplicates.
20.
INTERSECT INTERSECT returns only the rows found by both queries. Returns only those records which are present on both the tables.
SELECT PLAYER_NAME FROM SOCCER INTERSECT SELECT PLAYER_NAME FROM GOLF; The Result-Set is: PLAYER_NAME JOHN KELLY 2 rows are selected. Players on both teams. 21. MINUS Minus returns the rows from the first query that were not present in the second. Return those records which are not repeated in both the tables. SELECT PLAYER_NAME FROM SOCCER MINUS SELECT PLAYER_NAME FROM GOLF; The Result-Set is: PLAYER_NAME CRAIG JOHNSON ALBERT # When the order is reversed SELECT PLAYER_NAME FROM GOLF MINUS SELECT PLAYER_NAME FROM SOCCER; PLAYER_NAME JAMIE EDDIE CLARKSON
22.
RULES OF PRECEDENCE
ORDER EVALUATED 1 2 3 4 5 6 7 8
OPERATOR ARITHMETIC OPERATORS CONCATENATION OPERATOR COMPARISON CONDITIONS IS[NOT] NULL, LIKE, [NOT] IN [NOT] BETWEEN NOT LOGICAL CONDITION AND LOGICAL CONDITION OR LOGICAL CONDITION
EMPLOYEES E_ID FIRST_NAME YEARS_EMPL 101 178 154 87 184 JAMIE KAREN EDDIE ELPH FIONA 2 5 8 4 10
LEAVES_TAK EN 4 50 80 35 125
SELECT E_ID, FIRST_NAME, SALARY FROM EMPLOYEES WHERE FIRST_NAME LIKE E% OR FIRST_NAME LIKE K% AND SALARY>=30000 The Result-Set is: E_ID FIRST_NAME 178 KAREN 154 EDDIE 87 ELPH
23.
FUNCTIONS Functions in SQL enable you to perform feats such as determining the sum of a column or converting all the characters of a string to uppercase AGGREGATE OR GROUP FUNCTIONS They return a value based on the values in a column. (After all, you wouldn't ask for the average of a single field.)
Aggregate functions Date and time functions Arithmetic functions Character functions Conversion functions Miscellaneous functions
TYPES OF GROUP FUNCTIONS FUNCTION COUNT AVG SUM MAX MIN STDDEV VARIANCE DESCRIPTION Returns the number of rows that satisfy the condition in the WHERE clause The AVG function computes the average of a column. SUM does just that. It returns the sum of all values in a column. To find the largest value in a column, use MAX It returns the lowest member of a column. Finds the standard deviation of a column of numbers Produces the square of the standard deviation, a number vital to many statistical calculations
COUNT FUNCTION The count function has 3 formats: 1.COUNT(*) 2.COUNT(EXPR) 3.COUNT(DISTINC T EXPR)
COUNT(*) : Returns the number of rows on a table that satisfy the criteria of the SELECT statement, including duplicate rows & rows containing null values in any of the columns. If a WHERE clause included in the SELECT statement, COUNT (*) returns the number of rows that satisfies the condition in the where clause. COUNT (expr): Returns the number of non-null values in the column identified by expr. COUNT (DISTINT expr): Returns the number of unique, non-null values in the column identified by expr.
EMPLOYEES E_ID FIRST_NAME YEARS_EMPL 101 178 154 87 184 JAMIE KAREN JAMIE JAMIE FIONA 2 5 8 4 10
LEAVES_TAK EN 4 50 80 35 125
SELECT COUNT(*) FROM EMPLOYEES WHERE SALARY=100000; The Result-Set is: COUNT(*) _________________ 2 SIMPLY REURNS THE TOTAL NUMBER OF ROWS IN THE TABLE SELECT COUNT(*) FROM EMPLOYEES; The Result-Set is: COUNT(*) _____________ 5
DISTINCT KEYWORD DISPLAY RECORDS ONLY ONCE EVEN IF THE VALUE IS REPEATED MULTIPLE TIMES IN THE ROW. ALSO COUNTS THE NULL VALUES
SELECT COUNT(DISTINCT SALARY) FROM EMPLOYEES; The Result-Set is: COUNT( DISTINCT SALARY) ______________________ 3
SELECT COUNT(SALARY) FROM EMPLOYEES WHERE FIRST_NAME=JAMIE; The Result-Set is: COUNT(SALARY) __________________ 3
AVG
EMPLOYEES E_ID FIRST_NAME YEARS_EMPL 101 178 154 87 184 JAMIE KAREN JAMIE JAMIE FIONA 2 5 8 4 10
LEAVES_TAK EN 4 50 80 35 125
SELECT AVG(YEARS_EMPL) FROM EMPLOYEES; The Result-Set is: AVG(YEARS_EMPL) _______________ 5.8 SELECT AVG(YEARS_EMPL) FROM EMPLOYEES WHERE FIRST_NAME=JAMIE; The Result-Set is: AVG(YEARS_EMPL) ____________ 3.6 SELECT SUM(YEARS_EMPL) YEARS FROM EMPLOYEES; The Result-Set is: YEARS 29
SUM
MAX
SELECT MAX(YEARS_EMPL) FROM EMPLOYEES; The Result-Set is: MAX(YEARS_EMPL) __________________________ 10 For a non-numeric column, MAX returns the highest (closest to Z) string. Finally, a function that works with both characters and number Step 1. Work out the mean In the formula above (the Greek letter "mu") is the mean of all our values 2+5+8+4+10/5= 5.8 So, = 5.8 (9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4) Step 2. Then for each number: subtract the Mean and square the result This is the part of the formula that says:
Step 3. Then work out the mean of those squared differences. To work out the mean, add up all the values then divide by how many. First add up all the values from the previous step. But how do we say "add them all up" in mathematics? We use "Sigma": The handy Sigma Notation says to sum up as many terms as we want:
Sigma Notation
We want to add up all the values from 1 to N, where N=20 in our case because there are 20 values: Example (continued):
Which means: Sum all values from (x1-7)2 to (xN-7)2 We already calculated (x1-7)2=4 etc. in the previous step, so just sum them up: = 4+25+4+9+25+0+1+16+4+16+0+9+25+4+9+9+4+1+4+9 = 178 But that isn't the mean yet, we need to divide by how many, which is simply done by multiplying by "1/N": Example (continued):
Mean of squared differences = (1/20) 178 = 8.9 (Note: this value is called the "Variance") Step 4. Take the square root of that and you are done! Example (concluded):
= (8.9) = 2.983... SELECT STDDEV(YEARS_EMPL) FROM EMPLOYEES; SELECT VARIANCE(YEARS_EMPL) FROM EMPLOYEES; DATE AND TIME FUNCTIONS We live in a civilization governed by times and dates, and most major implementations of SQL have functions to cope with these concepts PROJECT TASK T1 T2 T3 1. 2. 3. 4. 5. 6.
SELECT TASK START_DATE, END_DATE ORIGINAL_DATE, ADD_MONTHS(END_DATE,2) FROM PROJECT; The Result-Set is: TAS START_DAT K E T1 01-APR-95 T2 09-APR-96 T3 24-MAY-99
SELECT TASK TASKS_SHORTER_THAN_ONE_MONTH FROM PROJECT WHERE ADD_MONTHS(STARTDATE,1) > ENDDATE; The Result-Set is: TASKS_SHORTER_THAN_ONE_MONTH _______________________ T1
SELECT END_DATE, LAST_DAY(END_DATE) FROM PROJECT; The Result-Set is: ORIGINAL_DATE 01-APR-95 08-MAY-96 26-JULY-99
MONTHS _BETWEEN To know how many months fall between month x and month y, use MONTHS _BETWEE
SELECT TASK, STARTDATE, ENDDATE,MONTHS_BETWEEN(STARTDATE,ENDDATE) DURATION FROM PROJECT; The Result-Set is: TASK START_DATE END_DATE T1 01-APR-95 01-APR-95 T2 09-APR-96 08-MAY-96 T3 24-MAY-99 26-JULY-99
NEW_TIME To adjust the time according to the time zone you are in, the New_TIME function is for you. Here are the time zones you can use with this function: Abbreviation AST or ADT BST or BDT CST or CDT EST or EDT GMT MST or MDT HST or HDT NST PST or PDT YST or YDT Time Zone Atlantic standard or daylight time Bering standard or daylight time Central standard or daylight time Eastern standard or daylight time Greenwich mean time Mountain standard or daylight time Alaska-Hawaii standard or daylight time Newfoundland standard time Pacific standard or daylight time Yukon standard or daylight time
SELECT END_DATE EDT, NEW_TIME(END_DATE, 'EDT','PDT') FROM PROJECT; The Result-Set is: EDT NEW_TIME(END_DATE, 'EDT','PDT') 01-APR-95 31-MAR-95 08-MAY-96 07-MAY-96 26-JULY-99 25-JUL-99
NEXT_DAY Finds the name of the first day of the week that is equal to or later than another specified date
SELECT STARTDATE, NEXT_DAY(START_DATE, 'FRIDAY') FROM PROJECT; The Result-Set is: START_DATE NEXT_DAY(START_DATE, FRIDAY 01-APR-95 07-APR-95 08-MAY-96 12-APR-96 26-JULY-99 28-MAY-99 The output tells you the date of the first Friday that occurs after your START_DATE.
SELECT DISTINCT SYSDATE FROM PROJECT; SYSDATE SYSDATE returns the system time and date The Result-Set is: SYSDATE ______________ 03-SEP-13
If you wanted to see where you stood today in a certain project, you
could type SELECT * FROM PROJECT WHERE STARTDATE > SYSDATE; Now you can see what parts of the project start after today.
ARITHMETIC FUNCTIONS Many of the uses you have for the data you retrieve involve mathematics. Most implementations of SQL provide arithmetic functions similar to the functions covered here. ABS: returns the absolute value of the number you point to.
1. 2. 3. 4. 5. 6. 7. 8. 9.
ABS CEIL AND FLOOR COS,COSH,SIN,SINH,TAN,TANH EXP LN & LOG MOD POWER SIGN SQRT
B 4 .707 9 42 55 5.3
CEIL and FLOOR CEIL returns the smallest integer greater than or equal to its argument. FLOOR returns the largest integer equal to or less than its argument.
B 4 .707 9 42 55 5.3
SELECT B, CEIL(B) CEILING FROM NUMBERS; The Result-Set is: B 4 .707 9 42 55 5.3
CEILING 4 1 0 42 55 6
SELECT A, FLOOR(A) FLOORING FROM NUMBERS; A 3.1415 -45 5 -57.667 15 -3.2 COS, COSH, SIN, SINH, TAN, and TANH: The COS, SIN, and TAN functions provide support for various trigonometric concepts. They all work on the assumption that n is in radians. 3 -45 5 -58 15 -4 FLOORING
The following statement returns some unexpected values if you don't realize COS expects A to be in radians. A 3.1415 -45 5 -57.667 15 -7.2 COS(A) -1 .52532199 .28366219 .437183 -.7596879 .60835131
EXP EXP enables you to raise e (e is a mathematical constant used in various formulas) to a power.
SELECT A, EXP(A) FROM NUMBERS; The Result-Set is: A 3.1415 -45 5 -57.667 15 -7.2
LN and LOG These two functions center on logarithms. LN returns the natural logarithm of its argument.
SELECT A, LN(A) FROM NUMBERS; ERROR: ORA-01428: argument '-45' is out of range Did we neglect to mention that the argument had to be positive? SELECT A, LN(ABS(A)) FROM NUMBERS; The Result-Set is: A 3.1415 -45 5 -57.667 15 -7.2
LOG The other logarith-mic function, LOG, takes two arguments, returning the logarithm of the first argument in the base of the second. The following query returns the logarithms of column B in base
SELECT B, LOG(B, 10) FROM NUMBERS; B 4 .707 9 42 55 5.3 1.660964 -6.640962 1.0479516 .61604832 .57459287 1.3806894
10.
MOD The ANSI standard for the modulo operator % is sometimes implemented as the function MOD. Here's a query that returns a table showing the remainder of A divided by B
NUMBERS A 3.1415 -45 5 -57.667 15 -3.2 SELECT A, B, MOD(A,B) FROM NUMBERS; The Result-Set is: A 3.1415 4 -45 .707 5 9 -57.667 42 15 55 -3.2 5.3
B 4 .707 9 42 55 5.3
POWER
SIGN
SQRT
CHARACTER FUNCTIONS Many implementations of SQL provide functions to manipulate characters and strings of characters. This section covers the most common character functions.
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
CHR CONCAT INITCAP LOWER & UPPER LPAD & RPAD LTRIM & RTRIM REPLACE SUBSTR TRANSLATE INSTR LENGTH
CHR CHR returns the character equivalent of the number it uses as an argument. The character it returns depends on the character set of the database. For this example the database is set to ASCII. The column CODE includes numbers.
M A J C M A G
CODE 22 67 65 87 77 52
CHR(CODE) C A W M 4
SELECT CONCAT(FIRST_NAME, LAST_NAME) "FIRST AND LAST NAMES" FROM CHARACTERS; The Result-Set is: FIRST AND LAST NAMES KELLY PURVIS CHUCK TAYLOR LAURA CHRISTINE FESTER ADAMS ARMANDO COSTALES MAJOR KONG SELECT FIRST_NAME BEFORE, INITCAP(FIRST_NAME) AFTER FROM CHARACTERS; The Result-Set is: BEFORE PURVIS TAYLOR CHRISTINE ADAMS COSTALES KONG
IINITCAP INITCAP capitalizes the first letter of a word and makes all other characters lowercase.
LOWER and UPPER LOWER changes all the characters to lowercase; UPPER does just the reverse.
SELECT FIRST_NAME, UPPER(FIRST_NAME), LOWER(FIRST_NAME) FROM CHARACTERS; The Result-Set is: LAST_NAME KELLY CHUCK LAURA FESTER ARMANDO MAJOR
LPAD and RPAD take a minimum of two and a maximum of three arguments. The first argument is the character string to be operated on. The second is the number of characters to pad it with, and the optional third argument is the character to pad it with. The third argument defaults to a blank, or it can be a single character or a character string. The following statement adds five pad characters, assuming that the field LASTNAME is defined as a 15-character field: SELECT LAST_NAME, LPAD(LAST_NAME,20,'*') FROM CHARACTERS; The Result-Set is: LAST_NAME PURVIS TAYLOR CHRISTINE ADAMS COSTALES KONG
SELECT LAST_NAME, RPAD(LAST_NAME,20,'*') FROM CHARACTERS; LAST_NAME PURVIS TAYLOR CHRISTINE ADAMS COSTALES KONG RPAD(LAST_NAME,20,'*') PURVIS*************** TAYLOR*************** CHRISTINE*************** ADAMS*************** COSTALES************ KONG****************
LTRIM and RTRIM take at least one and at most two arguments. The first argument, like LPAD and RPAD, is a character string. The optional second element is either a character or character string or defaults to a blank. If you use a second argument that is not a blank, these trim functions will trim that character. SELECT LAST_NAME, RTRIM(LAST_NAME, 0) FROM CHARACTERS; The Result-Set is: LAST_NAME PURVIS00 TAYLOR000 CHRISTINE ADAMS000 COSTALES KONG
To make sure that the characters have been trimmed with the following statement: SELECT LAST_NAME, RPAD(RTRIM(LAST_NAME),20,'*') FROM CHARACTERS; LAST_NAME PURVIS TAYLOR CHRISTINE ADAMS COSTALES KONG RPAD(RTRIM(LAST_NAME), 20, * ) PURVIS************** TAYLOR************** CHRISTINE*********** ADAMS*************** COSTALES************ KONG****************
REPLACE
REPLACE does just that. Of its three arguments, the first is the string to be searched. The second is the search key. The last is the optional replacement string. If the third argument is left out or NULL, each occurrence of the search key on the string to be searched is removed and is not replaced with anything.
SELECT LAST_NAME, REPLACE(LAST_NAME, 'A') REPLACEMENT FROM CHARACTERS; The Result-Set is: LAST_NAME PURVIS TAYLOR CHRISTINE ADAMS COSTALES KONG
If you have a third argument, it is substituted for each occurrence of the search key in the target string. SELECT LAST_NAME, REPLACE(LAST_NAME, 'A', C) REPLACEMENT FROM CHARACTERS; The Result-Set is: LAST_NAME REPLACEMENT PURVIS PURVIS TAYLOR TCYLOR CHRISTINE CHRISTINE ADAMS CDCMS COSTALES COSTCLES KONG KONG If the second argument is NULL, the target string is returned with no changes The Result-Set is: LAST_NAME PURVIS TAYLOR CHRISTINE ADAMS COSTALES KONG
SUBSTR
This three-argument function enables you to take a piece out of a target string. The first argument is the target string. The second argument is the position of the first character to be output. The third argument is the number of characters to show.
SELECT FIRSTNAME, SUBSTR(FIRSTNAME,2,3) FROM CHARACTERS; The result-Set is: FIRST_NAME KELLY CHUCK LAURA FESTER ARMANDO MAJOR
If you use a negative number as the second argument, the starting point is determined by counting backwards from the end, like this: SELECT FIRST_NAME, SUBSTR(FIRST_NAME,-13,2) FROM CHARACTERS; The result-Set is: FIRST_NAME KELLY CHUCK LAURA FESTER ARMANDO MAJOR
SUBSTR(FIRSTNAME, -3, 2) LL UC UR TE DO JO
If you don't have a third argument, use the following statement instead: SELECT FIRST_NAME, SUBSTR(FIRST_NAME,3) FROM CHARACTERS; The result-Set is: FIRST_NAME KELLY CHUCK LAURA FESTER ARMANDO MAJOR
TRANSLATE
The function TRANSLATE takes three arguments: the target string, the FROM string, and the TO string. Elements of the target string that occur in the FROM string are translated to the corresponding element in the TO string. SELECT FIRST_NAME, TRANSLATE(FIRST_NAME '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 'NNNNNNNNNNAAAAAAAAAAAAAAAAAAAAAAAAAA) FROM CHARACTERS; The Result-Set is:
INSTR
To find out where in a string a particular pattern occurs, use INSTR. Its first argument is the target string. The second argument is the pattern to match. The third and fourth are numbers representing where to start looking and which match to report. This example returns a number representing the first occurrence of O starting with the second character. SELECT LAST_NAME, INSTR(LAST_NAME, 'O', 2, 1) FROM CHARACTERS; The Result-Set is: LAST_NAME PURVIS TAYLOR CHRISTINE ADAMS COSTALES KONG
INSTR(LAST_NAME, 'O', 2, 1) 0 5 0 0 2 2
The default for the third and fourth arguments is 1. If the third argument is negative, the search starts at a position determined from the end of the string, instead of from the beginning.
LENGTH
LENGTH returns the length of its lone character argument. For example SELECT FIRST_NAME, LENGTH(RTRIM(FIRST_NAME)) FROM CHARACTERS; The Result-Set is: LAST_NAME PURVIS TAYLOR CHRISTINE ADAMS COSTALES KONG
LENGTH(RTRIM(FIRST_NAME)) 6 6 9 5 8 4
Note the use of the RTRIM function. Otherwise, LENGTH would return 15 for every value.
CONVERSION FUNCTIONS
These three conversion functions provide a handy way of converting one type of data to another. These examples use the table CONVERSIONS. 1. TO_CHAR 2. TO_NUMBER NAME 40 12 74 TESTNUM 95 23 65
TO_CHAR
The difference between TO CHAR and the CHR function discussed earlier. CHR would have turned this number into a character or a symbol, depending on the character set.
Not very exciting, or convincing. Here's how to verify that the function returned a character string: SELECT TESTNUM, LENGTH(TO_CHAR(TESTNUM)) FROM CONVERT; TESTNUM 95 23 65 LENGTH(TO_CHAR(TE STNUM) ) 2 2 2
TO_NUMBER
CLAUSES IN SQL
1. 2. 3. 4. 5.
STARTING WITH STARTING WITH is an addition to the WHERE clause that works exactly like LIKE (<exp>%).