With SQL built-in functions you can manipulate character, numeric, and date data in SQL statements. You can also perform operations on a collection of data with the aggregate functions.
Pseudocolumns are built-in values that provide specific information with a query and are similar to functions without arguments. However, functions without arguments typically return the same value for every row in the result set, whereas pseudocolumns typically return a different value for each row.
This topic includes the following topics:
|
See Also:
|
A pseudocolumns is similar to a table column, but is not actually stored in a table. A pseudocolumn returns a value so it is similar to a function without argument. Oracle Database provides several pseudocolumns, such as the ROWNUM, SYSDATE, and USER. The ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row in a query. SYSDATE returns the current date and time set for the operating system on which the database resides. USER returns the name of the user name that is currently logged in.
Example: Using Pseudocolumns show the use of the ROWNUM, SYSDATE, and USER pseudocolumns. Note the use of the table DUAL, which is automatically created by Oracle Database for use as a dummy table in SQL statements.
Using Pseudocolumns
-- the following statement displays the SYSDATE, which is the current system date -- NOW is a column alias for display purposes -- DUAL is a dummy table with one row simply used to complete the SELECT statement SELECT SYSDATE "NOW" FROM DUAL; -- display the name of the current user, the user name should be HR SELECT USER FROM DUAL; -- using ROWNUM < 10 limits the number of rows returned to less than 10 SELECT employee_id, hire_date, SYSDATE FROM employees WHERE ROWNUM < 10;
See Example: Using Date Functions for another example of the use of SYSDATE.
A sequence is a database object similar to a pseudocolumn that generates unique sequential values, often used for primary and unique keys. You can refer to sequence values in SQL statements with the CURRVAL and NEXTVAL pseudocolumns.
To generate a sequence number, you call the sequence using the CURRVAL or NEXTVAL keywords. You must qualify CURRVAL and NEXTVAL with the name of the sequence, such as employees_seq.CURRVAL or employees_seq.NEXTVAL. Before you use CURRVAL for a sequence in your session, you must first initialize the sequence with NEXTVAL.
Example: Using Sequences shows an example of the use of the employees_seq sequence with the employee_id of the employees table. The employees_seq sequence is part of the HR schema and had been created for use with the employees table. When a sequence is intended to be used with a specific table, it is a good practice to include the name of the table in the sequence name.
Using Sequences
-- first initialize the employees_seq sequence with NEXTVAL SELECT employees_seq.NEXTVAL FROM DUAL; -- after initializing the sequence, use CURRVAL as the next value in the sequence INSERT INTO employees VALUES (employees_seq.CURRVAL, 'Belinda', 'Vernal', 'belinda.vernal', '555.111.2342', '15-AUG-05', 'ST_CLERK', 6000, NULL, 124, 50); -- query the employees table to check the current value of the sequence -- which was inserted used as employee_id in the previous INSERT statement SELECT employee_id, last_name FROM employees WHERE last_name = 'Vernal';
Oracle Database provides a set of character functions that you can use in your SQL statements to customize the character values. With character functions, you can perform operations that upper case, lower case, trim blanks from, and concatenate character data.
Example: Using Character Functions shows how to use character functions on character data.
Using Character Functions
-- you can use the UPPER function to display uppercase data, LOWER for lowercase
SELECT employee_id, UPPER(last_name), LOWER(first_name) FROM employees;
-- you can use CONCAT function to concatenate character data
SELECT CONCAT('Last name: ', last_name) FROM employees;
-- you can use RTRIM and LTRIM to remove spaces from the beginning or end of
-- character data. Note the use of concatenation operator ||
SELECT employee_id, RTRIM(first_name) || ' ' || LTRIM(last_name) FROM employees;
-- you can TRIM to remove spaces from both the beginning and end
SELECT employee_id, TRIM(last_name) || ', ' || TRIM(first_name) FROM employees;
-- you can format the system date (SYSDATE) as a character string
-- with various format masks and then display
-- the following displays September 21 2005
SELECT TO_CHAR(SYSDATE, 'fmMonth DD YYYY') "Today" FROM DUAL;
-- the following displays 21-SEP-2005 AD
SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY AD') "Today" FROM DUAL;
You can use arithmetic operators to create expressions for calculations on data in tables. The arithmetic operators include:
+ for addition
- for subtraction
* for multiplication
/ for divide
In an arithmetic expression, multiplication and division are evaluated first, then addition and subtraction. When operators have equal precedence, the expression is evaluated left to right. It is best to include parentheses to explicitly determine the order of operators and provide clarity in the expression.
Example: Using Arithmetic Operators shows the use of arithmetic operators in expressions with the data in the employees table. Note the use of a column alias to provide a more useful heading for the displayed output.
Using Arithmetic Operators
-- in the following query the commission is displayed as a percentate instead -- of the decimal that is stored in the database SELECT employee_id, (commission_pct * 100) "Commission %" FROM employees; -- in the following query, the proposed new annual salary is calculated -- for employees who report to the manager with Id 145 SELECT employee_id, ((salary + 100) * 12) "Proposed new annual salary" FROM employees WHERE manager_id = 145;
Oracle Database provides a set of numeric functions that you can use in your SQL statements to manipulate the numeric values. With numeric functions, you can perform operations that upper case, lower case, trim blanks from, and concatenate character data.
Example: Using Numeric Functions shows how to use numeric functions on numeric data in the employees table.
Using Numeric Functions
-- you can use the ROUND function to round off numeric data, in this case to -- two decimal places SELECT employee_id, ROUND(salary/30, 2) "Salary per day" FROM employees; -- you can use the TRUNC function to truncate numeric data, in this case to -- 0 decimal places; 0 is the default so TRUNC(salary/30) would be same SELECT employee_id, TRUNC(salary/30, 0) "Salary per day" FROM employees;
Oracle Database provides various functions for calculating and converting datetime data.
|
See Also: Oracle Database SQL Language Reference for details about the date functions |
Performing Date Arithmetic
Oracle Database provides a number of features to help with date arithmetic, so that you do not need to perform your own calculations on the number of seconds in a day, the number of days in each month, and so on. Some useful features include the following:
ADD_MONTHS function, which returns the date plus the specified number of months.
MONTHS_BETWEEN function, which returns the number of months between two dates.
SYSDATE function, which returns the current date and time set for the operating system on which the database resides.
SYSTIMESTAMP function, which returns the system date, including fractional seconds and time zone, of the system on which the database resides.
TRUNC function, which when applied to a DATE value, trims off the time portion so that it represents the very beginning of the day (the stroke of midnight). By truncating two DATE values and comparing them, you can determine whether they refer to the same day. You can also use TRUNC along with a GROUP BY clause to produce daily totals.
Arithmetic operators such as + and -. For example, SYSDATE-7 refers to 7 days before the current system date.
INTERVAL data types, which enable you to represent constants when performing date arithmetic rather than performing your own calculations. For example, you can add or subtract INTERVAL constants from DATE values or subtract two DATE values and compare the result to an INTERVAL.
Comparison operators such as >, <, =, and BETWEEN.
Converting Between Datetime Types
Oracle Database provides several useful functions that enable you to convert to a from datetime data types. Some useful functions include:
EXTRACT, which extracts and returns the value of a specified datetime field from a datetime or interval value expression
NUMTODSINTERVAL, which converts a NUMBER or expression that can be implicitly converted to a NUMBER value to an INTERVAL DAY TO SECOND literal
NUMTOYMINTERVAL, which converts a NUMBER or expression that can be implicitly converted to a NUMBER value to an INTERVAL YEAR TO MONTH literal
TO_DATE, which converts character data to a DATE data type
TO_CHAR, which converts DATE data to character data
TO_DSINTERVAL, which converts a character string to an INTERVAL DAY TO SECOND value
TO_TIMESTAMP, which converts character data to a value of TIMESTAMP data type
TO_TIMESTAMP_TZ, which converts character data to a value of TIMESTAMP WITH TIME ZONE data type
TO_YMINTERVAL, which converts a character string to an INTERVAL YEAR TO MONTH type
Example: Using Date Functions shows how to use date functions on date data.
Using Date Functions
-- in the following statement you can use MONTHS_BETWEEN to compute months -- employed for employees and then truncate the results to the whole month -- note the use of the label (alias) "Months Employed" for the computed column SELECT employee_id, TRUNC(MONTHS_BETWEEN(SYSDATE, HIRE_DATE)) "Months Employed" FROM employees; -- the following displays the year hired for each employee id SELECT employee_id, EXTRACT(YEAR FROM hire_date) "Year Hired" FROM employees;
Example: Using Date Functions With Format Masks shows how to use date functions with format masks.
Using Date Functions With Format Masks
-- use TO_DATE with a format mask to display or enter dates differently than the
-- current default date format
-- the following displays 1998 with the 'DD-MON-RR' format mask
SELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL;
-- note that 'YY' in a format mask denotes the year in the current century
-- the following displays 2098 with the 'DD-MON-YY' format mask
SELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-YY') ,'YYYY') "Year" FROM DUAL;
-- the following displays the date and time with a datetime format mask
SELECT TO_TIMESTAMP ('10-Sep-05 14:10:10.123000', 'DD-Mon-RR HH24:MI:SS.FF')
FROM DUAL;
-- the following displays the system date and time with a format mask
SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Now" FROM DUAL;
Group functions operate on sets of rows to give one result per group. These sets may comprise the entire table or the table split into groups.
Example: Using Date Functions shows how to use aggregate functions on collections of data in the database. Aggregate functions include COUNT, MAX, MIN, and SUM. The GROUP BY clause is used to select groups of rows by a specified expression and returns one row of summary information for each group.
Using Aggregate Functions
-- you can use COUNT to count the employees with manager 122 -- note the use of a column alias Employee Count SELECT COUNT(*) "Employee Count" FROM employees WHERE manager_id = 122; -- count the employees grouped by manager, also sort the groups SELECT COUNT(*) "Employee Count", manager_id FROM employees GROUP BY manager_id ORDER BY manager_id; -- you can use MIN to find the minimum salary for employees with manager 122 SELECT MIN(salary) FROM employees WHERE manager_id = 122; -- this computes the minimum and maximum salary by job_id groups -- the job_ids groups are sorted in alphabetical order SELECT MIN(salary), MAX(salary), job_id FROM employees GROUP BY job_id ORDER BY job_id;