You are on page 1of 60

Data Definition Language

A Data Definition Language or Data Description Language (DDL) is a computer language for defining data structures. The term DDL was first introduced in relation to the Codasyl database model, where the schema of the database was written in a Data Description Language describing the records, fields, and "sets" making up the user Data Model. Later it was used to refer to a subset of SQL, but is now used in a generic sense to refer to any formal language for describing data or information structures, like XML schemas.

CREATE statements
Create - To make a new database, table, index, or stored query. A CREATE statement in SQL creates an object inside of a relational database management system (RDBMS). The types of objects that can be created depends on which RDBMS is being used, but most support the creation of tables, indexes, users, synonyms and databases. Some systems (such as PostgreSQL) allow CREATE, and other DDL commands, inside of a transaction and thus they may be rolled back.

CREATE TABLE statement


Perhaps the most common CREATE command is the CREATE The typical usage is:
parameters]. TABLE

command.

CREATE [TEMPORARY] TABLE [table name] ( [column definitions] ) [table

Column Definitions: A comma-separated list consisting of any of the following

Column definition: [column name] [data type] {NULL | NOT NULL} {column options} Primary key definition: PRIMARY KEY ( [comma separated column list] ) CONSTRAINTS: {CONSTRAINT} [constraint definition] RDBMS specific functionality

For example, the command to create a table named employees with a few sample columns would be: CREATE TABLE employees ( id INTEGER PRIMARY KEY, first_name CHAR(50) NULL, last_name CHAR(75) NOT NULL, dateofbirth DATE NULL );

DROP statements
Drop - To destroy an existing database, table, index, or view. A DROP statement in SQL removes an object from a relational database management system (RDBMS). The types of objects that can be dropped depends on which RDBMS is being used, but most support the dropping of tables, users, and databases. Some systems (such asPostgreSQL) allow DROP and other DDL commands to occur inside of a transaction and thus be rolled back. The typical usage is simply:

DROP objecttype objectname.


For example, the command to drop a table named employees would be: DROP TABLE employees; The DROP statement is distinct from the DELETE and TRUNCATE statements, in that they do not remove the table itself. For example, aDELETE statement might delete some (or all) data from a table while leaving the table itself in the database, whereas a DROP statement would remove the entire table from the database.

ALTER statements

Alter - To modify an existing database object. An ALTER statement in SQL changes the properties of an object inside of a relational database

management system (RDBMS). The types of objects that can be altered depends on which RDBMS is being used. The typical usage is:
ALTER objecttype objectname parameters.

For example, the command to add (then remove) a column named bubbles for an existing table named sink would be: ALTER TABLE sink ADD bubbles INTEGER; ALTER TABLE sink DROP COLUMN bubbles;
Referential integrity statements

Finally, other kind of DDL sentence in SQL are the statements to define referential integrity relationships, usually implemented as primary key and foreign key tags in some columns of the tables. These two statements can be included inside a CREATE TABLE or an ALTER TABLE sentence.

Data Manipulation Language


1. DML Commands Editing Data 2. DML Commands
o

Editing Commands

Insert Update Delete Review Command Select

3. Insert
o

Insert is used to add a new row to a table or view View is similar to a query in Access, a predefined select statement Can add one or more rows

Syntax varies depending on number of rows

4. Insert Syntax For One Row


o o

INSERT INTO tablename[(field list)] VALUES(value list) Field list is optional If field list is omitted, values expected for all columns (except IDENTITY)

5. Insert Single Row Examples


o o o

INSERT INTO Students(StudentID) VALUES(875001234) INSERT INTO Courses(Department, CourseNumber) VALUES(CIS,182) INSERT INTO Courses

VALUES(CIS,282,SQL Projects,5,Using SQL for application back-end)

6. Using Default Values


o

A default value can be entered by Including field in field list and using DEFAULT key word in Values list Omit field from field list and value from Values list Assume Department defaults to CIS:

INSERT INTO Courses(Department, CourseNumber) VALUES(DEFAULT,145) INSERT INTO Courses(CourseNumber) VALUES(145)

7. Assigning Null Values


o o o

If Null is acceptable for a column Omit field from field list; Or Use NULL in Value list Assume Course description is optional: INSERT INTO Courses

VALUES(CIS,282,SQL Projects,5,Null) VALUES(CIS,282,SQL Projects,5)

INSERT INTO Courses(Department, CourseNumber, Title, Credits)

8. Update
o o

Update is used to change an existing row Can change one, some or all rows in a table or view

A WHERE clause is used to specify specific rows to change WHERE represents a true/false description of a row Multiple conditions require a logical operator

9. Update Syntax
o o o

UPDATE tablename SET field1 = value1, field2 = value2 [WHERE condition ] Each field to change is listed with the value to store in that field Comma separates each field/value pair WHERE condition is same as criteria in Access Update Examples Assign value to zip code for 2 nd publisher: UPDATE publishers

10.
o o

SET pub_zip = 20006 WHERE pub_id = 0877 Change publisher name to add Ltd. for any Massachusetts publisher: UPDATE publishers SET pub_name = pub_name + Ltd. WHERE pub_state = ma Delete Delete removes one or more rows from the table

11.
o

No field list is included May specify which rows to remove by adding WHERE clause Delete Syntax DELETE FROM tablename

12.
o o

[WHERE condition ] Not including a where clause removes all rows from a table Delete Examples DELETE FROM Publishers WHERE pub_state <>ca DELETE FROM Publishers

13.
o o o

WHERE pub_zip IS NULL OR pub_state = wa DELETE FROM Publishers

OPERATORS :
ARITHMETIC OPERATORS: SQL mathematical operations are performed using mathematical operators (+, -, *, /, and %). We can use SQL like a calculator to get a feel for how these operators work. SELECT ID ,NAME,SAL+11/12 FROM YASARAKESH; SELECT ID ,NAME,SAL+11/12*11-2 FROM YASARAKESH;

LOGICAL OPERATORS :
There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at a time to determine whether a row can be selected for the output. When retrieving data using a SELECT statement, you can use logical operators in the WHERE clause, which allows you to combine more than one condition.

SELECT * FROM YASARAKESH WHERE ID=1112 AND NAME='RAKESH'; SELECT * FROM YASARAKESH WHERE ID=1111 OR NAME='RAKESH'; SELECT * FROM YASARAKESH WHERE ID NOT IN(1111,1115);

RELATIONAL OPERATORS :
SELECT * FROM YASARAKESH WHERE SAL<=10000; SELECT * FROM YASARAKESH WHERE SAL=10000; SELECT * FROM YASARAKESH WHERE SAL>=10000; SELECT * FROM YASARAKESH WHERE SAL>10000; SELECT * FROM YASARAKESH WHERE SAL =10000; SELECT * FROM YASARAKESH WHERE NAME='RAKESH'; SELECT * FROM YASARAKESH WHERE SAL>=10000;

SPECIAL OPERATORS:
SELECT * FROM YASARAKESH WHERE ID NOT IN(1111,1115);

SELECT * FROM YASARAKESH WHERE ID IN(1111,1115,1110); SELECT * FROM YASARAKESH WHERE NAME NOT LIKE '%H'; SELECT * FROM YASARAKESH WHERE NAME LIKE '%R%';O SELECT ID,NAME ,SAL FROM YASARAKESH WHERE LOC LIKE'%K%'; SELECT *FROM YASARAKESH WHERE ID LIKE '11%';

constraint
Use a constraint to define an integrity constraint--a rule that restricts the values in a database. Oracle Database lets you create six types of constraints and lets you declare them in two ways.

six type:
NOT NULL constraint: prohibits a database value from being
null. unique constraint: prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null. CREATE TABLE RRR( ID NUMBER(5), NAME VARCHAR2(12), CONSTRAINT RRR_NAME_UK UNIQUE(NAME));

primary key constraint: combines a NOT NULL constraint


and a unique constraint in a single declaration. That is, it

prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null. CREATE TABLE YASA (ID NUMBER(7) NOT NULL, NAME VARCHAR(10), SAL NUMBER(12), ADDRESS VARCHAR(20),

PHONE_NO NUMBER(15) NOT NULL, CONSTRAINT YASA_ID_PK PRIMARY KEY(ID));


foreign key constraint : requires values in one table to
match values in another table. CREATE TABLE YYYYY (YYYYY_ID NUMBER(10), YYYYY_NAME VARCHAR(12), YYYYY_LOC VARCHAR(20), XXX_ID NUMBER(5), CONSTRAINTS YYYYY_XXX_ID_FK FOREIGN KEY (XXX_ID) REFERENCES XXX(XXX_ID));

Check constraint:

A check constraint allows you to specify a condition on each row in a table. Note:

A check constraint can NOT be defined on a VIEW. The check constraint defined on a table must refer to only columns in that table. It can not refer to columns in other tables. A check constraint can NOT include a SUBQUERY.

A check constraint can be defined in either a CREATE TABLE statement or an ALTER TABLE statement. syntax CREATE TABLE table_name (column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE] ); The DISABLE keyword is optional. If you create a check constraint using the DISABLE keyword, the constraint will be created, but the condition will not be enforced.

Example: CREATE TABLE BON111 ( ID NUMBER(5),NAME VARCHAR(10),SAL NUMBER(12) , CONSTRAINT BONDAM_NAME_KKU CHECK (NAME LIKE'R_____'));

Using an ALTER TABLE statement:


ALTER TABLE table_name add CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]; ALTER TABLE suppliers add CONSTRAINT check_supplier_name CHECK (supplier_name IN ('IBM', 'Microsoft', 'NVIDIA'));

Drop a Check Constraint


ALTER TABLE table_name drop CONSTRAINT constraint_name;

For example: ALTER TABLE suppliers drop CONSTRAINT check_supplier_id; \ Enable a Check Constraint The syntax for enabling a check constraint is: ALTER TABLE table_name enable CONSTRAINT constraint_name;

For example:
ALTER TABLE suppliers enable CONSTRAINT check_supplier_id; In this example, we're enabling a check constraint on the suppliers table called check_supplier_id.

Disable a Check Constraint The syntax for disabling a check constraint is: ALTER TABLE table_name disable CONSTRAINT constraint_name;

For example: ALTER TABLE suppliers disable CONSTRAINT check_supplier_id; In this example, we're disabling a check constraint on the suppliers table called check_supplier_id.
NULLIF :

In Oracle/PLSQL, the NULLIF function compares expr1 and expr2. If expr1 and expr2 are equal, the NULLIF function returns NULL. Otherwise, it returns expr1. The syntax for the NULLIF function is: NULLIF( expr1, expr2 ) SELECT EMP_NAME, LENGTH(EMP_NAME) NAME , EMP_ID, LENGTH(EMP_ID) ID, NULLIF ( LENGTH(EMP_NAME),LENGTH(EMP_ID)) FROM RAKESH; CASE:

Starting in Oracle 9i, you can use the case statement within an SQL statement. It has the functionality of an IF-THEN-ELSE statement. The syntax for the case statement is: CASE [ expression ] WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ... WHEN condition_n THEN result_n ELSE result END SELECT EMP_NAME ,EMP_SAL ASA ,EMP_ID , CASE EMP_ID WHEN 125 THEN 20*EMP_SAL WHEN 123 THEN 3* EMP_SAL

ELSE (EMP_SAL) END RAKEE FROM RAKESH; DECODE: In Oracle/PLSQL, the decode function has the functionality of an IF-THEN-ELSE statement. The syntax for the decode function is: decode( expression , search , result [, search , result]... [, default] ) expression is the value to compare. search is the value that is compared against expression. result is the value returned, if expression is equal to search. default is optional. If no matches are found, the decode will return default. If default is omitted, then the decode statement will return null (if no matches are found).

SELECT EMP_NAME ,EMP_SAL ASA ,EMP_ID , DECODE EMP_ID 125 , 20*EMP_SAL 123 , 3* EMP_SAL

ELSE (EMP_SAL) END RAKEE FROM RAKESH; ORDER BY: SINGLE COLUMN:SELECT <column_name> FROM <table_name> ORDER BY <column_name>; MULTIPLE COLUMN:SELECT <column_name>, <column_name FROM <table_name> ORDER BY <column_name>, <column_name> GROUP BY: SELECT EMP_NAME,AVG(EMP_SAL) RRRR FROM RAKESH GROUP BY EMP_NAME ;

NVL:IN Oracle/PLSQL, the NVL function lets you


substitute a value when a null value is encountered. SYNTAX:
NVL( ARG1 , ARG2);
ARG1 is the string to test for a null value. ARG2 IS replace_with is the value returned if ARG1 is null.

EXAMPLE: SELECT nvl(SAL*10,0) FROM ANNI WHERE ID=126; RESULT IS : nvl(SAL*10,0)


0

HERE INTAILLY SAL IS NULL

EXAMPLE: SELECT nvl(SAL*10,123) FROM ANNI WHERE ID=126; RESULT IS: nvl(SAL*10,0)
123

Functions
SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. Do not confuse SQL functions with user-defined functions written in PL/SQL. If you call a SQL function with an argument of a datatype other than the datatype expected by the SQL function, then Oracle attempts to convert the argument to the expected datatype before performing the SQL function. If you call a SQL function with a null argument, then the SQL function automatically returns null. The only SQL

functions that do not necessarily follow this behavior are CONCAT, NVL, and REPLACE.
function::=

Single-Row Functions
Single-row functions return a single result row for every row of a queried table or view. These functions can appear in select lists, WHERE clauses, START WITH andCONNECT B Y clauses, and HAVING clauses.

single_row_function::=

Numeric Functions
Numeric functions accept numeric input and return numeric values. Most numeric functions that return NUMBER values that are accurate to 38 decimal digits. The transcendental functions COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and TANH are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN,ATAN, and ATAN2 are accurate to 30 decimal digits. The numeric functions are:

Character Functions Returning Character Values Character functions that return character values return values of the same datatype as the input argument. The length of the value returned by the function is limited by the maximum length of the datatype returned.

For functions that return CHAR or VARCHAR2, if the length of the return value exceeds the limit, then Oracle Database truncates it and returns the result without an error message. For functions that return CLOB values, if the length of the return values exceeds the limit, then Oracle raises an error and returns no data.

The character functions that return character values are:


1.CHR 2.CONCAT 3.INITCAP 4.LOWER 5.LPAD 6.LTRIM 7.NLS_INITCAP 8.NLS_LOWER 9.NLSSORT 10.NLS_UPPER 11.REGEXP_REPLACE 12.REGEXP_SUBSTR 13.REPLACE 14.RPAD 15.RTRIM 16.SOUNDEX 17.SUBSTR

18.TRANSLATE 19.TREAT 20.TRIM 21.UPPER

1.CHR
Syntax chr::=

Purpose CHR returns the character having the binary equivalent to n as a VARCHAR2 value in either the database character set or, if you specify USING NCHAR_CS, the national character set. For single-byte character sets, if n > 256, then Oracle Database returns the binary equivalent of n mod 256. For multibyte character sets, n must resolve to one entire code point. Invalid code points are not validated, and the result of specifying invalid code points is indeterminate. This function takes as an argument a NUMBER value, or any value that can be implicitly converted to NUMBER, and returns a character.

2.CONCAT

Syntax concat::=

Purpose
CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is in the same character set as char1. Its datatype depends on the datatypes of the arguments. In concatenations of two different datatypes, Oracle Database returns the datatype that results in a lossless conversion. Therefore, if one of the arguments is a LOB, then the returned value is a LOB. If one of the arguments is a national datatype, then the returned value is a national datatype. For example:

CONCAT(CLOB, NCLOB) returns NCLOB CONCAT(NCLOB, NCHAR) returns NCLOB CONCAT(NCLOB, CHAR) returns NCLOB CONCAT(NCHAR, CLOB) returns NCLOB

This function is equivalent to the concatenation operator (||). The function is useful when there are spaces in the values to be concatenated. The concatenation operator does not permit spaces.

INITCAP
Syntax initcap::=

Purpose INITCAP returns char, with the first letter of each word in uppercase, all other letters in lowercase. Words are delimited by white space or characters that are not alphanumeric. char can be of any of the datatypes CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The return value is the same datatype as char. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion.

LPAD:
Syntax

lpad::=

Purpose LPAD returns expr1, left-padded to length n characters with the sequence of characters in expr2. This function is useful for formatting the output of a query. Both expr1 and expr2 can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CL OB, or NCLOB. The string returned is of VARCHAR2 datatype and is in the same character set as expr1. The argument n must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer. If you do not specify expr2, then the default is a single blank. If expr1 is longer than n, then this function returns the portion of expr1 that fits in n. The argument n is the total length of the return value as it is displayed on your terminal screen. In most character sets, this is also the number of characters in the return value. However, in some multibyte character sets, the

display length of a character string can differ from the number of characters in the string. Examples The following example left-pads a string with the asterisk (*) and period (.) characters: SELECT LPAD('Page 1',15,'*.') "LPAD example" FROM DUAL; LPAD example --------------*.*.*.*.*Page 1

LTRIM
Syntax ltrim::=

Purpose LTRIM removes from the left end of char all of the characters contained in set. If you do not specify set, it defaults to a single blank. If char is a character literal, then you must enclose it in single quotes. Oracle Database begins scanning char from its first character and removes all characters that appear in set until reaching a character not in set and then returns the result. Both char and set can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 datatype and is in the same character set as char. Examples The following example trims all of the left-most x's and y's from a string: SELECT LTRIM('xyxXxyLAST WORD','xy') "LTRIM example" FROM DUAL; LTRIM example -----------XxyLAST WORD

REPLACE
Syntax replace::=

REPLACE returns char with every occurrence of search_string replaced with replacement_string. If replacement_string is omitted or null, then all occurrences of search_string are removed. If search_string is null, then char is returned. Both search_string and replacement_string, as well as char, can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is in the same character set as char. The function returns VARCHAR2 if the first argument is not a LOB and returns CLOB if the first argument is a LOB. REPLACE provides functionality related to that provided by the TRANSLATE function. TRANSLATE provides singlecharacter, one-to-one substitution. REPLACE lets you substitute one string for another as well as to remove character strings.

Examples

The following example replaces occurrences of J with BL: SELECT REPLACE('JACK and JUE','J','BL') "Changes" FROM DUAL; Changes -------------BLACK and BLUE

RPAD
Syntax rpad::=

RPAD returns expr1, right-padded to length n characters with expr2, replicated as many times as necessary. This function is useful for formatting the output of a query. Both expr1 and expr2 can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 datatype and is in the same character set as expr1. The argument n must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer.

If you do not specify expr2, then it defaults to a single blank. If expr1 is longer than n, then this function returns the portion of expr1 that fits in n. The argument n is the total length of the return value as it is displayed on your terminal screen. In most character sets, this is also the number of characters in the return value. However, in some multibyte character sets, the display length of a character string can differ from the number of characters in the string. Examples The following example creates a simple chart of salary amounts by padding a null string with asterisks: SELECT last_name, RPAD(' ', salary/1000/1, '*') "Salary" FROM employees WHERE department_id = 80 ORDER BY last_name; LAST_NAME Salary ------------------------- --------------Abel ********** Ande ***** Banda ***** Bates ****** Bernstein ******** Bloom ********* Cambrault ********** Cambrault ******

Doran Errazuriz Fox Greene Hall Hutton Johnson King . . .

****** *********** ******** ******** ******** ******* ***** *********

RTRIM
Syntax rtrim::=

RTRIM removes from the right end of char all of the characters that appear in set. This function is useful for formatting the output of a query. If you do not specify set, then it defaults to a single blank. If char is a character literal, then you must enclose it in single quotes. RTRIM works similarly to LTRIM. Both char and set can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB,

or NCLOB. The string returned is of VARCHAR2 datatype and is in the same character set as char.

Examples The following example trims all the right-most occurrences of period, slash, and equal sign from a string: SELECT RTRIM('BROWNING: ./=./=./=./=./=.=','/=.') "RTRIM example" FROM DUAL; RTRIM exam ---------BROWNING:

SUBSTR
Syntax substr::=

The SUBSTR functions return a portion of string, beginning at character position, substring_length characters long. SUBSTR calculates lengths using characters as defined by the input character set. SUBSTRB uses bytes instead of characters. SUBSTRC uses Unicode complete characters. SUBSTR2 uses UCS2 code points. SUBSTR4 uses UCS4 code points.

If position is 0, then it is treated as 1. If position is positive, then Oracle Database counts from the beginning of string to find the first character. If position is negative, then Oracle counts backward from the end of string. If substring_length is omitted, then Oracle returns all characters to the end of string. If substring_length is less than 1, then Oracle returns null.

string can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. Both position and substring_length must be of datatypeNUMBER, or any datatype that can be implicitly converted to NUMBER, and must resolve to an integer. The return value is the same datatype as string. Floating-point numbers passed as arguments to SUBSTR are automatically converted to integers. Examples

The following example returns several specified substrings of "ABCDEFG": SELECT SUBSTR('ABCDEFG',3,4) "Substring" FROM DUAL; Substring --------CDEF SELECT SUBSTR('ABCDEFG',-5,4) "Substring" FROM DUAL; Substring --------CDEF Assume a double-byte database character set: SELECT SUBSTRB('ABCDEFG',5,4.2) "Substring with bytes" FROM DUAL; Substring with bytes -------------------CD

Conversion Functions:

Whenever PL/SQL performs an operation involving one or more values, it must first convert the data to be the right datatype for the operation. As Chapter 4, Variables and Program Data , describes, there are two kinds of conversion: implicit and explicit. An implicit conversion is performed by PL/SQL as needed to execute a statement. An explicit conversion takes place when you use a built-in conversion function to force the conversion of a value from one datatype to another. This chapter describes each of these functions. If you do not use a conversion function to explicitly convert your data, or if you do use those functions and additional conversion is still needed, PL/SQL attempts to convert the data implicitly to the datatypes needed to perform the operation. I recommend that you avoid allowing either the SQL or PL/SQL languages to perform implicit conversions on your behalf. Whenever possible, use a conversion function to guarantee that the right kind of conversion takes place. Implicit conversion has a number of drawbacks, summarized in Section 4.2.8.2, "Implicit data conversions" in Chapter 4 . Explicit conversions help you to avoid unpleasant surprises, maximize performance, and make your code more self-documenting. When you perform an explicit conversion involving dates or numbers (using TO_CHAR, TO_DATE, or TO_NUMBER), you can specify a conversion format mask. PL/SQL uses this mask to either interpret the input value or format the output value. Table 14.1 summarizes the PL/SQL conversion functions described in this chapter.

Table 14.1: The Built-In Conversion Functions Name Description

CHARTOROWID Converts a string to a ROWID.

Table 14.1: The Built-In Conversion Functions Name CONVERT HEXTORAW RAWTOHEX Description Converts a string from one character set to another. Converts from hexadecimal to raw format. Converts from raw value to hexadecimal.

ROWIDTOCHAR Converts a binary ROWID value to a character string. TO_CHAR TO_DATE TO_NUMBER Converts a number or date to a string. Converts a string to a date. Converts a string to a number.

14.1 Conversion Formats Several of the conversion functions (TO_CHAR, TO_DATE, and TO_NUMBER) use format models to determine the format of the converted data. Format models convert between strings and dates, and strings and numbers. This section discusses these format models, which are then put to use in the function descriptions. 14.1.1 Date Format Models In Versions 6 and earlier of the Oracle RDBMS, the default format for dates as character values was DD-MON-YY, a cause of consternation for many developers and users. While this format is common in many parts of the world, very few people use it in the United States. With Oracle7 you can specify your own default date format (which takes effect on the initialization or startup of the RDBMS instance) with the NLS_DATE_FORMAT[ 1 ] parameter as follows: [1] NLS is an abbreviation for National Language Support.

NLS_DATE_FORMAT = `MM/DD/YYYY' The default date format is also set implicitly with another initialization parameter, NLS_TERRITORY. When you specify an NLS_TERRITORY value, you set conventions for date format, date language, numeric formats, currency symbols, and week start day. Even with this flexibility, the database still supports only a single default date format in a given instance. Both developers and users must be aware of this format when working with dates. Later sections of this chapter explore approaches in PL/SQL that give the user much more flexibility when entering dates in their applications. As you can see, format masks (such as MMDDYY and Month DD, YYYY) play an important role in the conversion of date and character data. Table 14.2 provides the full set of date format masks and explains how to use them in all their variations. You can use the format elements in any combination, in any order. You can even use the same format element more than once in your format mask. Following the table are examples showing these variations.

Table 14.2: Date Format Model Elements Mask SCC or CC SYYYY or YYYY IYYY YYY or YY or Y Description The century. If the SCC format is used, any B.C. dates are prefaced with a hyphen ( - ). The four-digit year. If the SYYYY format is used, any B.C. dates are prefaced with a hyphen ( - ). The four-digit ISO standard year. The last three, two, or one digits of the year. The current century is the default.

Table 14.2: Date Format Model Elements Mask Description

IYY or IY or The last three, two, or one digits of the ISO standard I year. The current century is the default. Y,YYY SYEAR or YEAR or SYear or Year RR The four-digit year with a comma. The year spelled out. The S prefix places a negative sign in front of B.C. dates.

The last two digits of the year. This format is used to display years in centuries other than our own. SeeSection 14.3.3, "RR: Changing Millenia" . The B.C. or A.D. indicator, without periods. The quarter of the year, from 1 through 4. January through March are in the first quarter, April through June in second quarter, etc. The number of the month in the year, from 01 through 12. January is month number 01, September is 09, etc. The Roman numeral representation of the month number, from I through XII. January is I, September is IX, etc. The name of the month, either in upper- or mixed-case format. The abbreviated name of the month, as in JAN for January. The week in the year, from 1 through 53. The week in the year, from 1 through 52 or 1 through 53, based on the ISO standard.

BC or AD Q

B.C. or A.D. The B.C. or A.D. indicator, with periods.

MM RM MONTH or Month MON or Mon WW IW

Table 14.2: Date Format Model Elements Mask W DDD DD D Description The week in the month, from 1 through 5. Week 1 starts on the first day of the month and ends on the seventh. The day in the year, from 1 through 366. The day in the month, from 1 through 31. The day in the week, from 1 through 7. The day of the week that is decreed the first day is specified implicitly by the NLS_TERRITORY initialization parameter for the database instance. The abbreviated name of the day, as in TUE for Tuesday. The Julian day format of the date (counted as the number of days since January 1, 4712 B.C., the earliest date supported by the Oracle RDBMS). The meridian indicator (morning or evening) without periods.

DAY or Day The name of the day in upper- or mixed-case format. DY J

AM or PM

A.M. or P.M. The meridian indicator (morning or evening) with periods. HH or HH12 The hour in the day, from 1 through 12. HH24 MI SS SSSSS The hour in the day, from 0 through 23. The minutes component of the date's time, from 0 through 59. The seconds component of the date's time, from 0 through 59. The number of seconds since midnight of the time component. Values range from 1 through 86399, with

Table 14.2: Date Format Model Elements Mask TH Description each hour comprising 3600 seconds. Suffix which converts a number to its ordinal format; for example, 4 becomes 4th and 1 becomes 1st. This element can appear only at the end of the entire format mask. The return value is always in English, regardless of the date language. Suffix which converts a number to its spelled format; for example, 4 becomes FOUR, 1 becomes ONE, and 221 becomes TWO HUNDRED TWENTY-ONE. This element can appear only at the end of the entire format mask. The return value is always in English, regardless of the date language. Suffix which converts a number to its spelled and ordinal format; for example, 4 becomes FOURTH and 1 becomes FIRST. This element can appear only at the end of the entire format mask. The return value is always in English, regardless of the date language. Element which requires exact pattern matching between data and format model. (FX stands for Format eXact.) Element which toggles suppression of blanks in output from conversion. (FM stands for Fill Mode.) Any punctuation, such as a comma ( , ) or slash ( / ) or hyphen ( - ), will be reproduced in the formatted output of the conversion. You can also include text within double quotes ( " ) and this text will then be represented as entered in the converted value. See examples in TO_CHAR for an illustration of this element.

SP

SPTH

FX FM Other text

Note that whenever a date format returns a spelled value (words rather than numbers, as with MONTH, MON, DAY, DY, AM, and PM), the language used to spell these words is determined by the National Language Support parameters, NLS_DATE_LANGUAGE and NLS_LANGUAGE, or by the optional date language argument you can pass to both TO_CHAR and TO_DATE. Here are some examples of date format masks composed of the above format elements: 'Month DD, YYYY' 'MM/DD/YY Day A.M.' 'Year Month Day HH24:MI:SS' 'J' 'SSSSS-YYYY-MM-DD' '"A beautiful summer morning on the" DDth" day of "Month' See the description of the TO_CHAR and TO_DATE functions for more examples of the use and resulting values of these masks. 14.1.2 Number Format Models The number formats are used in both TO_CHAR and TO_NUMBER. The number format in TO_CHAR translates a numeric value to a VARCHAR2 datatype. The number format in TO_NUMBER translates a VARCHAR2 value to a numeric datatype. A number format mask can comprise one or more elements from Table 14.3 . The resulting format of the character string (or the converted numeric value) will reflect the combination of the format elements. You will find examples of different applications of the format models in the descriptions of both the TO_CHAR and TO_NUMBER functions. Format elements with a description starting with "Prefix:" can be used only at the beginning of the complete format mask. Format elements with a description starting with "Suffix:" can be used only at the end of the complete format mask.

Table 14.3: Number Format Model Elements Format Description Elements 9 0 $ B MI Each 9 represents a significant digit to be returned. Leading zeros in a number are displayed or treated as blanks. Each represents a significant digit to be returned. Leading zeros in a number are displayed or treated as zeros. Prefix: puts a dollar sign in front of the number. Prefix: returns a zero value as blanks, even if the format element was used to show a leading zero. Suffix: places a minus sign ( - ) after the number if it is negative. For positive values it returns a trailing space, which is different from NULL. Prefix: places a plus sign ( + ) in front of a positive number and a minus sign ( - ) before a negative number. Suffix: places angle brackets ( < and > ) around a negative value. For positive values it places leading and trailing spaces around the number. Specifies the location of the decimal point in the returned value. All format elements to the left of the D will format the integer component of the value. All format elements to the right of the D will format the fractional part of the value. The character used for the decimal character is determined by the database initialization parameter NLS_NUMERIC_CHARACTERS. Specifies the location of the group separator (for example, a comma to separate thousands as in 6,734) in the returned

S PR

Table 14.3: Number Format Model Elements Format Description Elements value. The character used for the group separator is determined by the database initialization parameter NLS_NUMERIC_CHARACTERS. C L Specifies the location of the ISO currency symbol in the returned value. Specifies the location of the local currency symbol (such as $) in the returned value.

, (comma) Specifies that a comma be returned in that location in the return value. . (period) V Specifies that a period be returned in that location in the return value. Multiplies the number to the left of the V in the format model by 10 raised to the n th power, where n is the number of 9s found after the V in the format model. Suffix: specifies that the value be returned in scientific notation. Specifies that the return value be converted to upper- or lowercase Roman numerals. The range of valid numbers for conversion to Roman numerals is between 1 and 3999. The value must be an integer.

EEEE RN or rn

Here are some examples of numeric format masks built from these elements: 9.999EEEE 00V99 S9,999,999 00009MI 999D99 9G999G999 L999.99

SYSDATE() is, perhaps, the most commonly used Oracle date function provided by SQL*Plus. The Oracle date function SYSDATE() returns the current date and time in the default Oracle date format. The default format for the date returned is MM-DD-YY Its very common to use the Oracle date function SYSDATE() in conjunction withto_char(). For example, to_char (SYSDATE, 'MM-DD-YYYY HH:MI:SS'); This Oracle date function returns a string containing not only the current date, but also the current time down to the second. The most common uses of SYSDATE() dont use a date format model: dStartDate := SYSDATE; Other Oracle Date Functions Oracle date function - months_between (l,e) This Oracle date function returns the months between two dates. If I wanted to know how many months an employee has worked for the company, I can use this Oracle date function. There is an emp_hire_date in the emp table.

Notice that this Oracle date function returns the fraction of a month. You could use trunc or round to make the results more readable.

Oracle date function - add_months (d,n) The add_months Oracle date function gives you the same day, n number of months away. The n can be positive or negative.

Oracle date function - last_day (d) The last_day Oracle date function returns the last day of the month of the date d. If you want to find the first day of the next month, simply add one to the last_day results.

Oracle date function - next_day (d, day_of_week) The next_day Oracle date function returns the date of the day_of_week after date d. day_of_week can be the full name or abbreviation. Below, we get the date for next Monday, next Friday, and the first Tuesday of next month.

Genaral functions:
NVL(column_name, m) - Returns m if column_name value is NULL Expand|Select|Wrap|Line Numbers

1.

SELECT NVL(empno,0) FROM emp --

returns 0 if empno is NULL 2.

NVL2(column_name,c1,c2) - Returns c1 if column_name IS NOT NULL and c2 if column_name IS NULL Expand|Select|Wrap|Line Numbers
1. SELECT NVL2(empno,empno,'NO EID') from dual --

returns empno if empno IS NOT NULL else returns 'NO EI D' 2.

NULLIF(column_name,value) - Returns NULL, IF column_name = value Expand|Select|Wrap|Line Numbers


1. SELECT NULLIF(empno,1) FROM emp --

returns NULL IF empno = 1 2.

COALESCE(column1,column2,column3,column4) - Returns columns2 if column1 IS NULL, else returns column3 if column2 is also NULL and so on. All the columns should be of same data type Expand|Select|Wrap|Line Numbers
1. SELECT COALESCE(ename,first_name,last_name,'NO NAM E') from emp -returns first_name IF ename IS NULL, IF first_name IS also NULL, then returns last_name, IF last_name IS also NULL, then returns 'NO NAME' 2.

DECODE(column_name,val1,ret_val,val2,ret_val2,ret_ val3) - Returns ret_val1 IF column_name = val1 ELSE Returns ret_Val2 IF column_name = val2 ELSE Returns ret_val3 Expand|Select|Wrap|Line Numbers
1. SELECT DECODE(empno,1,'PM',2,'BM','EMP') FROM emp

-returns 'PM' if empno = 1 ELSE IF empno = 2 then retur ns 'BM' ELSE returns 'EMP' 2.

CASE(column_name) - CASE can be used in PLSQL as well as SQL statement.


Expand|Select|Wrap|Line Numbers 1. 2. 3. 4. 5. 6. SELECT empno,ename, (CASE WHEN (empno = 1) THEN 'PM' WHEN (empno = 2) THEN 'BM' ELSE 'EMP' END) Position FROM emp

ORDER BY:
Sometimes it is necessary that the rows returned from your query to be in a specific order. For example, I might want scores from high to low or names in alphabetical order. By default, the database will sort data ascending, smallest to largest. Words are sorted alphabetically. NULLs cannot be sorted, they will be listed as found at the bottom of the results. To sort the results set, we use the ORDER BY clause.

select author_last_name from author order by author_last_name; The Oracle ORDER BY clause must be used if you require that the rows be sorted. The Oracle database, by default, will not sort the results set, nor does it store rows in a table in a specific order. The Oracle ORDER BY clause is important because internally, the Oracle database uses a HEAP organized table as its default table. A HEAP table stores new data in the first available slot. Once you start adding and deleting rows in your table, the row order becomes random. Different queries (and for that matter, the same query run at different times) will use different execution plans to retrieve the requested data. Thus, the results can be ordered differently if you do not use the Oracle ORDER BYclause. Lets look at the AUTHOR table.

GROUP BY:
Question: When you use a GROUP BY clause with one or more columns, will the results be in the sorted order of GROUP BY columns (by default) or shall we use ORDER BY clause?

Answer: You may get lucky and find that your result set is sorted in the order of the GROUP BY columns, but we recommend always using the ORDER BY clause whenever sorting is required. Example #1 SELECT department, depart_head, SUM(sales) as "Total sales" FROM order_details GROUP BY department, depart_head ORDER BY department;

This example would sort your results by department, in ascending order.

Example #2 SELECT department, depart_head, SUM(sales) as "Total sales" FROM order_details GROUP BY department, depart_head ORDER BY department desc, depart_head; This example would first sort your results by department in descending order, then depart_head in ascending order.

Learn more about the ORDER BY Clause.

HAVING Clause:
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a SELECT statement to filter the records that a GROUP BY returns. The syntax for the HAVING clause is: SELECT column1, column2, ... column_n, aggregate_function (expression) FROM tables WHERE predicates GROUP BY column1, column2, ... column_n HAVING condition1 ... condition_n; aggregate_function can be a function such as SUM, COUNT, MIN, or MAX.

Example using the SUM function For example, you could also use the SUM function to return the name of the department and the total sales (in the associated department). The HAVING clause will filter the results so that only departments with sales greater than $1000 will be returned.

SELECT department, SUM(sales) as "Total sales" FROM order_details GROUP BY department HAVING SUM(sales) > 1000;

Example using the COUNT function For example, you could use the COUNT function to return the name of the department and the number of employees (in the associated department) that make over $25,000 / year. The HAVING clause will filter the results so that only departments with more than 10 employees will be returned. SELECT department, COUNT(*) as "Number of employees" FROM employees WHERE salary > 25000 GROUP BY department HAVING COUNT(*) > 10;

Example using the MIN function For example, you could also use the MIN function to return the name of each department and the minimum salary in the department. The HAVING clause will return only those departments where the starting salary is $35,000. SELECT department, MIN(salary) as "Lowest salary" FROM employees GROUP BY department HAVING MIN(salary) = 35000;

Example using the MAX function For example, you could also use the MAX function to return the name of each department and the maximum salary in the department. The HAVING clause will return only those departments whose maximum salary is less than $50,000. SELECT department, MAX(salary) as "Highest salary" FROM employees

GROUP BY department HAVING MAX(salary) < 50000;

Subqueries:
A subquery is a query within a query. In Oracle, you can create subqueries within your SQL statements. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.

WHERE clause:
Most often, the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries.

For example:
select * from all_tables tabs where (select tabs.table_name in cols.table_name from all_tab_columns cols where cols.column_name = 'SUPPLIER_ID');

Limitations:

Oracle allows up to 255 levels of subqueries in the WHERE clause.

FROM clause:
A subquery can also be found in the FROM clause. These are called inline views.

For example:
select suppliers.name, subquery1.total_amt from suppliers, (select supplier_id, Sum(orders.amount) as total_amt from orders group by supplier_id) subquery1, where subquery1.supplier_id = suppliers.supplier_id; In this example, we've created a subquery in the FROM clause as follows: (select supplier_id, Sum(orders.amount) as total_amt from orders group by supplier_id) subquery1 This subquery has been aliased with the name subquery1. This will be the name used to reference this subquery or any of its fields.

Limitations:
Oracle allows an unlimited number of subqueries in the FROM clause.

SELECT clause
A subquery can also be found in the SELECT clause.

For example: select tbls.owner, tbls.table_name, (select count(column_name) as total_columns from all_tab A subquery can also be found in the SELECT clause. _columns cols where cols.owner = tbls.owner and cols.table_name = tbls.table_name) subquery2 from all_tables tbls; In this example, we've created a subquery in the SELECT clause as follows: (select count(column_name) as total_columns from all_tab_columns cols where cols.owner = tbls.owner and cols.table_name = tbls.table_name) subquery2 The subquery has been aliased with the name subquery2. This will be the name used to reference this subquery or any of its fields. The trick to placing a subquery in the select clause is that the subquery must return a single value. This is why an aggregate function such asSUM, COUNT, MIN, or MAX is commonly used in the subquery.

VIEWS: A View in Oracle and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used CREATE VIEW RAKEE31 AS SELECT EMP_ID,EMP_NAME FROM RAKESH WHERE DEPT_ID IN (11,13); SELECT * FROM RAKEE31; SELECT * FROM USER_VIEWS WHERE VIEW_NAME LIKE '%RAKEE31%'; CREATE OR REPLACE VIEW YSHU31 AS SELECT EMP_ID,EMP_NAME,EMP_SAL FROM RAKESH WHERE dept_id=14; SELECT * FROM YSHU31; CREATE OR REPLACE FORCE VIEW VENKI AS SELECT * FROM RAKESH WHERE dept_id IN (11,12,13,14); CREATE OR REPLACE VIEW YSHU31 AS SELECT EMP_ID,EMP_NAME,EMP_SAL FROM RAKESH WHERE dept_id=14; SELECT * FROM VENKI;

Benefits of using Views Commonality of code being used. Since a view is based on one common set of SQL, this means that when it is called its less likely to require parsing.

Security. Views have long been used to hide the tables that actually contain the data you are querying. Also, views can be used to restrict the columns that a given user has access to. Predicate pushing

Sequences:
In Oracle, you can create an autonumber field by using sequences. A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key. The syntax for a sequence is: CREATE SEQUENCE sequence_name MINVALUE value MAXVALUE value START WITH value INCREMENT BY value CACHE value; For example: CREATE SEQUENCE supplier_seq MINVALUE 1 MAXVALUE 999999999999999999999999999 START WITH 1 INCREMENT BY 1 CACHE 20; This would create a sequence object called supplier_seq. The first sequence number that it would use is 1 and each subsequent number would increment by 1 (ie: 2,3,4,...}. It will cache up to 20 values for performance. If you omit the MAXVALUE option, your sequence will automatically default to: MAXVALUE 999999999999999999999999999 So you can simplify your CREATE SEQUENCE command as follows:

CREATE SEQUENCE supplier_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 20; Now that you've created a sequence object to simulate an autonumber field, we'll cover how to retrieve a value from this sequence object. To retrieve the next value in the sequence order, you need to use nextval. For example: supplier_seq.nextval This would retrieve the next value from supplier_seq. The nextval statement needs to be used in an SQL statement. For example: INSERT INTO suppliers (supplier_id, supplier_name) VALUES (supplier_seq.nextval, 'Kraft Foods'); This insert statement would insert a new record into the suppliers table. The supplier_id field would be assigned the next number from thesupplier_seq sequence. The supplier_name field would be set to Kraft Foods. Question: While creating a sequence, what does cache and nocache options mean? For example, you could create a sequence with a cache of 20 as follows: CREATE SEQUENCE supplier_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 20;

Or you could create the same sequence with the nocache option: CREATE SEQUENCE supplier_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 NOCACHE;

Answer: With respect to a sequence, the cache option specifies how many sequence values will be stored in memory for faster access. The downside of creating a sequence with a cache is that if a system failure occurs, all cached sequence values that have not be used, will be "lost". This results in a "gap" in the assigned sequence values. When the system comes back up, Oracle will cache new numbers from where it left off in the sequence, ignoring the so called "lost" sequence values. Note: To recover the lost sequence values, you can always execute an ALTER SEQUENCE command to reset the counter to the correct value. Nocache means that none of the sequence values are stored in memory. This option may sacrifice some performance, however, you should not encounter a gap in the assigned sequence values.

Question: How do we set the LASTVALUE value in an Oracle Sequence? Answer: You can change the LASTVALUE for an Oracle sequence, by executing an ALTER SEQUENCE command. For example, if the last value used by the Oracle sequence was 100 and you would like to reset the sequence to serve 225 as the next value. You would execute the following commands. alter sequence seq_name increment by 124; select seq_name.nextval from dual; alter sequence seq_name increment by 1; Now, the next value to be served by the sequence will be 225.

Synonyms:
A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and other database objects.

Creating or replacing a synonym


The syntax for creating a synonym is: create [or replace] [public] synonym [schema .] synonym_name for [schema .] object_name [@ dblink]; The or replace phrase allows you to recreate the synonym (if it already exists) without having to issue a DROP synonym command. The public phrase means that the synonym is a public synonym and is accessible to all users. Remember though that the user must first have the appropriate privileges to the object to use the synonym. The schema phrase is the appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own schema. The object_name phrase is the name of the object for which you are creating the synonym. It can be one of the following: table view sequence stored procedure function package materialized view java class schema object user-defined object synonym

For example:

create public synonym suppliers for app.suppliers; This first example demonstrates how to create a synonym called suppliers. Now, users of other schemas can reference the table called supplierswithout having to prefix the table name with the schema named app. For example: select * from suppliers; If this synonym already existed and you wanted to redefine it, you could always use the or replace phrase as follows: create or replace public synonym suppliers for app.suppliers;

Dropping a synonym
It is also possible to drop a synonym. The syntax for dropping a synonym is: drop [public] synonym [schema .] synonym_name [force]; The public phrase allows you to drop a public synonym. If you have specified public, then you don't specify a schema. The force phrase will force Oracle to drop the synonym even if it has dependencies. It is probably not a good idea to use the force phrase as it can cause invalidation of Oracle objects.

For example: drop public synonym suppliers; This drop statement would drop the synonym called suppliers that we defined earlier.

You might also like