Oracle 1Z0-007: Single-Row Functions

Valid XHTML 1.0!

Single-Row Functions

Describe various types of functions available in SQL

  • Aggregate - Operate against a collection of values, but return a single, summarizing value.
    • AVG(expression) - Computes the average value of a column by the expression.
      SELECT type, AVG( ytd_sales ) AS "average_ytd_sales"
          FROM titles
          GROUP BY type;

      /*another example using HAVING*/

      SELECT type 'Category', AVG( price ) 'Average Price'
          FROM titles
          GROUP BY type
          HAVING AVG(price) > 15
    • COUNT(expression) - Counts the rows defined by the expression.
      SELECT COUNT(DISTINCT country) "Count of Countries"
          FROM publishers
    • COUNT(*) - Counts all rows in the specified table or view.
      SELECT COUNT(*) FROM publishers;
    • MIN(expression) - Finds the minimum value in a column by the expression.
      SELECT 'MIN' = MIN(ytd_sales), 'MAX' = MAX(ytd_sales)
          FROM titles;
    • MAX(expression) - Finds the maximum value in a column by the expression
      SELECT 'MAX' = MAX(ytd_sales) FROM titles;
    • SUM(expression) - Computes the sum of column values by the expression.
      SELECT type, SUM( ytd_sales )
          FROM titles
          GROUP BY type;
  • Scalar - Operate against a single value, and return a single value based on the input value. Some scalar functions, CURRENT_TIME (SQL function) for example, do not require any arguments.
    • Character Function
      • Oracle
        • CHR - Returns the character value given character number.
          select CHR(37) a, CHR(100) b, CHR(110) c from dual;
          /*RETURNS:
          A B C
          - - -
          % d n*/
        • CONCAT - Returns string1 concatenated with string2.
          select CONCAT('monkey','boy') from dual;
          /*RETURNS:
          monkeyboy*/
        • INITCAP - Returns the string with the first character in every word capatilzed and the rest lowercase.
          select INITCAP('i am the walrus') "animal" from dual;
          /*RETURNS:
          animal
          ---------------
          I Am The Walrus */
        • LOWER - Returns the string in all lowercase
          select LOWER ('SHOUT IT SHOUT IT OUT LOUD') "lyric" from song;
          /*RETURNS:
          lyric
          ---------------
          shout it shout it out load
        • LPAD - In Oracle/PLSQL, the lpad function pads the left-side of a string with a specific set of characters.
          select lpad ('tech', 7) from foo; /*would return ' tech'*/

          select lpad ('tech', 2) from foo; /*would return 'te'*/

          select lpad ('tech', 8, '0') from foo; /*would return '0000tech'*/

          select lpad ('tech on the net', 15, 'z') from foo; /*would return 'tech on the net'*/

          select lpad ('tech on the net', 16, 'z') from foo; /*would return 'ztech on the net'*/
        • LTRIM - removes character from the left side of the string
          select ltrim (' foo') from foo; /*would return 'foo'*/

          select ltrim (' foo', ' ') from foo; /*would return 'foo'*/

          select ltrim ('000123', '0') from foo; /*would return '123'*/

          select ltrim ('123123foo', '123') from foo; /*would return 'foo'*/

          select ltrim ('123123foo123', '123') from foo; /*would return 'foo123'*/
        • NLS_INITCAP - sets initial letter to capital
          select nls_initcap('JOE GAKENHEIMER', 'nls_sort = XGerman') from person;
          /*returns 'Joe gakenheimer'*/
        • NLS_LOWER - sets initial character to lower case
          select nls_initlower('JOE GAKENHEIMER', 'nls_sort = XGerman')
              from person;
          /*returns 'jOE GAKENHEIMER'*/
        • NLS_UPPER - sets enter string to upper case
          select nls_initupper('joE GakenHeimer', 'nls_sort = XGerman')
              from person;
          /*returns 'JOE GAKENHEIMER'*/
        • REPLACE - the replace functions allows you to replace all occurences of one string with another.
          replace ('This is a test', 'is', 'was') /*would return 'This was a test'*/

          replace ('This is a test', 'i', 'a')
          /*would replace all occurences of 'i' characters with 's' characters*/
        • RPAD - the rpad function pads the right-side of a string with a specific set of characters
          rpad ('foo', 5);
          /*would return 'foo '*/

          rpad ('foo', 2);
          /*would return 'fo'*/

          rpad ('foo', 8, '0');
          /*would return 'foo00000'*/

          rpad ('foo is good', 10, 'a');
          /*would return 'foo is good'*/

          rpad ('foo is good', 11, 'a');
          /*would return 'foo is gooda'*/
        • RTRIM - removes character from the right side of the string
          rtrim ('foo '); /*would return 'foo'*/

          rtrim ('foo', 'f'); /*would return 'oo'*/

          rtrim ('foo', '0'); /*would return 'foo'*/

          rtrim ('foo is good', 'd'); /*would return 'foo is goo'*/

          rtrim ('foo is good', 'foo'); /*would return 'is good'*/
        • SOUNDEX - the soundex function returns a phonetic representation (the way it sounds) of a string.
          soundex ('apples');
          /*would return 'A142'*/

          soundex ('apples pie');
          /*would return 'A142'*/
        • SUBSTR - the substr functions allows you to extract a substring from a string.
          substr (string, start_position, [length])
          soundex ('apples');
          /*would return 'A142'*/

          soundex ('apples pie');
          /*would return 'A142'*/
        • SUBSTRB - the substrb functions allows you to extract a substring from bytes.
          , so it is just like substr but extracts bytes instead of character strings
        • TRANSLATE - the translate function replaces a sequence of characters in a string with another set of characters; it replaces a single character, one at a time; i.e. it will replace the 1st character in the "string to replace" with the 1st character in the "replacement string", then it will replace the 2nd character in the "string to replace" with the 2nd character in the "replacement string" ect...
          syntax: translate (string1, string_to_replace, replacement_string )
          string1 is the string to replace a sequence of characters with another set of characters.
          string_to_replace is the string that will be searched for in string1.
          replacement_string - All characters in the string_to_replace will be replaced with the corresponding character in the replacement_string.


          translate ('12pizza3', '123', '456);
          /*would return '45pizza6'*/

          translate ('footy, 'foo', 'git');
          /*would return 'gitty'*/
        • UPPER - converts all letters in the specified string to uppercase
          upper('i am shouting')/*returns: 'I AM SHOUTING'*/
        • ASCII - gets the ascii value of a charater
          select ascii('A') from foo;
        • ASCIISTR - Converts An ASCII String To An ASCII String In The Database's Character Set
          select asciistr(chr(128) || 'Hello' || chr(255)) from person;
        • INSTR - returns the location of a substring in a string
          instr ('Hang the DJ', 'a');
          /*would return 2;the first occurrence of 'a'*/

          instr ('Hand in Glove', 'n', 1, 2);
          /*would return 7; the second occurrence of 'n'*/
        • INSTRB - returns the location of a string of bytes within a substring
        • LENGTH - the length of a given substring
        • LENGTHB - returns the length of a string of bytes with in a substring
        • NLSSORT - returns the string of bytes used to sort a string
          CREATE TABLE person (name VARCHAR2(15));
          INSERT INTO person VALUES ('Smith');
          INSERT INTO person VALUES ('Smith');
          INSERT INTO person VALUES ('Smith');
          COMMIT;

          SELECT * FROM person ORDER BY name;
          SELECT * FROM person
          ORDER BY NLSSORT(person, 'NLS_SORT = XDanish');
      • SQL basics (most db's)
        • BIT_LENGTH(expression) - Returns an integer value representing the number of bits in an expression.
        • CHAR_LENGTH(expression) - Returns an integer value representing the number of characters in an expression.
        • EXTRACT(datetime_expression datepart FROM expression) - Allows the datepart to be extracted (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_HOUR, or TIMEZONE_MINUTE ) from an expression.
        • OCTET_LENGTH(expression) - Returns an integer value representing the number of octets in an expression. This value is the same as BIT_LENGTH/8.
        • POSITION(starting_string IN search_string) - Returns an integer value representing the starting position of a string within the search string.
    • Date Function
      • ADD_MONTHS - Returns the date plus x months specified.
        select ADD_MONTHS('1999-12-2',12) from dual;
      • LAST_DAY - Returns The Last Date Of A Month
        SELECT * FROM t;

        SELECT LAST_DAY(datecol1) FROM t;
      • MONTHS_BETWEEN -
        MONTHS_BETWEEN(<latest_date>, <earliest_date>)
        select months_between(sysdate+365, sysdate-365) from foo;

        select months_between(sysdate-365, sysdate+365) from foo;
      • NEW_TIME - returns the date and time in time zone zone2 when date and time in time zone zone1 are date
      • NEXT_DAY - date of next specified date following a date
        Options are SUN, MON, TUE, WED, THU, FRI, and SAT
      • ROUND - returns date rounded to the unit specified by the format model. If you omit the format, the date is rounded to the nearest day
        ROUND(<date_value>, <format>)
        select round(to_date ('21-jun-05'),'year') new_year from place
      • SYSDATE - returns the current system date and time
        select sysdate from dual;

        select sysdate into v_date from dual;

        select supplier_id, sysdate from suppliers where supplier_id > 5000;

        select supplier_id, to_char(sysdate, 'yyyy/mm/dd') where supplier_id > 5000;
      • TRUNC - returns a number truncated to a certain number of decimal places
        trunc (123.456)
        /*returns: 123*/

        trunc (123.456, 0)
        /*returns: 123*/

        trunc (123.456, 1)
        /*returns: 123.4*/

        trunc (123.456, 2)
        /*returns: 123.45*/
    • Number Function
      • ABS - Returns the absolute value of a number.
        select ABS(-24),ABS(-414),ABS(24) from dual;
        /*RETURNS:
        ABS(-24) ABS(-414) ABS(24)
        ---------- ---------- ----------
        24 414 24*/
      • FLOOR - Returns the largest integer equal to or less than the number.
        select FLOOR(-131.7), FLOOR(23.5) from dual;
        /*RETURNS:
        FLOOR(-131.7) FLOOR(23.5)
        ------------- -----------
        -132 23*/
      • ROUND - Returns the left number rounded to right number places of the decimal point.
        select ROUND(1.57),ROUND(1.57,1),ROUND(20.87,2) from dual;
        /*RETURNS:
        ROUND(1.57) ROUND(1.57,1) ROUND(20.87,2)
        ------- ------------- ---
        2 1.6 20.87
      • ACOS - returns the arc cosine of a number
        acos (number)
        acos (0.2)
        /*returns 1.36943840600457*/
      • ASIN - returns the arc sine of a number
        asin (number)
        asin (0.2)
        /*returns 0.201357920790331*/
      • ATAN - returns the arc tangent of a number
        atan (number)
        atan (0.2)
        /*returns 0.197395559849881*/
      • ATAN2 - returns the arc tangent of n and m
        atan2 (n, m)
        atan2 (0.2, 0.3)
        /* returns 0.588002603547568*/
      • CEIL - returns the smallest integer value that is greater than or equal to a number
        ceil (44.4)
        /* returns 45*/
      • COS - returns cosine
        cos(number)
      • COSH - returns the hyperbolic cosine of a numbercosh(number)
      • EXP - returns e raised to the nth power, where e = 2.71828183
        exp (3) /*returns 20.0855369231877

        exp (3.1) /*returns 22.1979512814416

        exp (-3) /*returns 0.0497870683678639
      • LN - returns the natural logarithm of a numberln(number)
      • LOG - returns the logarithm of n base mlog(m, n)
      • MOD - returns the remainder of m divided by n mod(m, n)
      • POWER - returns m raised to the nth power power(m, n)
      • SIGN - returns a value indicating the sign of a number
        sign(4)/*returns 1*/

        sign(-20)/*returns -1*/
      • SIN - returns the sin of n sin(n)
      • SINH - returns the hyperbolic sine of nsinh(n)
      • SQRT - returns the square root of nsqrt(n)
      • TAN - returns the tangent of ntan(n)
      • TANH - returns the hyperbolic tangent of ntanh(n)
    • Built-in - SQLServer Only, Oracle doesn't have
      • CURRENT_DATE - Identifies the current date.
      • CURRENT_TIME - Identifies the current time.
      • CURRENT_TIMESTAMP - Identifies the current date and time.
      • CURRENT_USER - Identifies the currently active user within the database server.
      • SESSION_USER - Identifies the currently active Authorization ID, if it differs from the user.
      • SYSTEM_USER - Identifies the currently active user within the host operating system.

Use conversion functions

These are mostly used within PL/SQL in order to coerce a datatype to explicitly be converted into another type,the most commonly user conversion functions.

  • TO_DATE - converts a string to a date
    to_date (string1, [format_mask], [nls_language])
    to_date ('2003/07/09', 'yyyy/mm/dd');
    /*July 9, 2003*/

    to_date ('070903', 'MMDDYY');
    /*July 9, 2003*/

    to_date ('20020315', 'yyyymmdd');
    /*Mar 15, 2002*/
  • TO_CHAR - converts a number or date to a string
  • CHARTOROWID - converts a value from CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to ROWID datatype
    CHARTOROWID(<char>);
    SELECT last_name
    FROM employees
    WHERE ROWID = CHARTOROWID('AAAFd1AAFAAAABSAA/');
  • CONVERT - converts a character string from one character set to another
    CONVERT(<char>, <dest_char_set>, <source_char_set>)
    SELECT CONVERT('A E I O O A B C D E ', 'US7ASCII', 'WE8ISO8859P1')
    FROM dual;
  • HEXTORAW - converts char containing hexadecimal digits in the CHAR, VARCHAR2, NCHAR, or NVARCHAR2 character set to a raw value
    HEXTORAW(<hex_value>>
    CREATE TABLE test (raw_col RAW(10));

    desc test;

    INSERT INTO test VALUES (HEXTORAW('7D'));
    SELECT * FROM test;
  • RAWTOHEX - converts raw to an NVARCHAR2 character value containing its hexadecimal equivalent
    RAWTOHEX(<raw_value>)
    SELECT RAWTONHEX(raw_col) HEXVAL, dump(raw_col)
    FROM test;
  • ROWIDTOCHAR - converts the ROWID to a char; similar to the CHARTOROWID
  • TO_LABEL - enables you to convert a label from its internal binary format to an external character format. To convert a label from character format to binary format in Trusted Oracle, you use the TO_CHAR function
  • TO_MULTI_BYTE - returns a character value with all of the single-byte characters converted to multibyte characters
    TO_MULTI_BYTE(char)
    select to_multi_byte ('Death of a Disco Dancer')from song;
  • TO_NUMBER - converts a string to a number
    to_number(string1, [format_mask], [nls_language])
    to_number ('444.58', '11100.02')/* returns 444.58*/

    to_number ('222', '888')/* returns 222*/

    to_number ('14', '22')/* returns 14*/
  • TO_SINGLE_BYTE - returns a character value with all of the multibyte characters converted to single-byte characters
    to_single_byte(char)
    select to_single_byte ('data boy')from foo;




Updated: July 30, 2005; Joe Gakenheimer