You are on page 1of 6

asmaka

SQL Quick Reference Technologies
Oracle SQL Reference with Examples for Software Developers and Published By
Business Analysts. Asmaka Technologies
Release 1.0 December 2010 Hyderabad, India. Support@asmaka.com

U p d a t e S t a t e me n t
SQL BASIC REFERENCE UPDATE <table_name>
SET <column> = <value>, ..
Basic SQL Statements (DML Statements) WHERE <condition>;
updates the entire column of that table
S e l e c t S t a t e me n t UPDATE customer SET state='CA';
Simple Select updates the specific record of the table eg:
SELECT * UPDATE customer SET name='Joe' WHERE customer_id=10;
FROM Namibia WHERE col1 = 'value1' AND col2 = 'value2'
Delete Statement
DELETE FROM <table_name>
Querying with Select.
[WHERE <conditon>]
Project and Join. SELECT emp_table.emp_id,
DELETE FROM members WHERE name LIKE 'Sharon%';
SELECT <columns> FROM emp_table.dept_no,
<table> dept_table.description Basic DDL Statements
WHERE <criterion>; FROM employee_db.emp_table,
employee_db.dept_table Create & Delete Tables
WHERE emp_table.dept_no = CREATE TABLE <table name> CREATE TABLE part
dept_table.dept_no; (<column definition (part_number CHAR(4),
Sorting. SELECT * list>, part_name VARCHAR(25),
SELECT .<clauses> FROM emp (<column name>)); PRIMARY_KEY(part_number));
ORDER BY <column ORDER BY empid DESC; -or- SELECT CREATE TABLE <table name> CREATE TABLE department
[DESC|ASC],..>; empid, lastname ( <colum_definition (department_number CHAR(4)
FROM emp [ <constraint > ], .. ); CONSTRAINT prim_dept
ORDER BY 2; PRIMARY_KEY,
Grouping. SELECT dept, AVG(salary) department_name
SELECT FROM emp VARCHAR2(10));
<select_clauses> GROUP BY dept DROP TABLE <table_name>; Delete table from database.
GROUP BY <column HAVING avg(salary)>80000 DROP TABLE suppliers;
[DESC|ASC]..> ORDER BY avg(salary) DESC; Modifying Tables
HAVING <criterion>; ALTER TABLE<table_name> Creates a primary key constraint for a
Column concatenation - SELECT firstname||','||lastname ADD(CONSTRAINT column.
formatting. full_name <constriant_name>
SELECT <column>|| FROM team; PRIMARY_KEY
<string>||<column> (<column_names>));
<column_alias>... ... ALTER TABLE <table_name> ALTER TABLE employee
; ADD(<colmn_definition>); ADD (department_number
On the fly calculations. SELECT 7 * 9 VARCHAR(12));
SELECT <expression> FROM DUAL; ALTER TABLE <table_name> Creates a foreign key constraint for a
FROM DUAL; ADD (CONSTRAINT column, mapping to a column on
Column aliasing. SELECT name, <constraint_name> another table. Optional ON DELETE
SELECT <column> NVL(spouse,'unmarried') FOREIGN_KEY(<colum_name>) CASCADE maintains referential
AS <alias_column>..; AS spouse REFERENECES integrity by deleting rows in table when
FROM emp_db,emp_table; foriegn_table_name(<foreig row in foreign table is deleted.
Subqueries. SELECT empid, dept, salary n_column_name>) [ON DELETE
SELECT ... FROM emp CASCADE]);
WHERE column = WHERE dept = ( ALTER TABLE Relax constraint.
(<subquery>);, SELECT dept DISABLE CONSTRAINT name;
FROM emp ALTER_TABLE Delete constraint forever.
WHERE empid = 78483); DROP
Joins CONSTRAINT<constraint_name
Equi Joins >;
select
emp.empno,emp.ename,emp.sal,emp.deptno,dept.dname,dept.city SQL Operators
from emp,dept where emp.deptno=dept.deptno; Arithmetic Operators
Non Equi Joins Operato Example
select e.empno, e.ename, e.sal, s.grade from emp e, r
salgrade s where e.sal between s.lowsal and s.hisal
+ (unary) SELECT +3 FROM DUAL;
Self Join
Select e.empno, e.ename, m.ename “Manager” from emp e, - (unary) SELECT -4 FROM DUAL;
emp m where e.mgrid=m.empno / SELECT SAL / 10 FROM EMP;
Outer Join * SELECT SAL * 5 FROM EMP;
select e.empno,e.ename,e.sal,e.deptno,d.dname,d.city from + SELECT SAL + 200 FROM EMP;
emp e, dept d where e.deptno(+)=d.deptno; - SELECT SAL - 100 FROM EMP;
I n s e r t S t a t e me n t Character Operators
INSERT INTO<table_name> Operato Example
(<colum_name, ..>) VALUES (<value, ..>); r
INSERT INTO table_name VALUES ( Value1, Value2, ... );
|| SELECT 'The Name of the employee is: ' ||
INSERT INTO table_name( Column1, Column2, ... ) VALUES
ENAME FROM EMP;
( Value1, Value2, ... );
INSERT INTO table_name( SELECT Value1, Value2, ... from Comparison Operators
table_name ); Operato Example
r
= SELECT ENAME "Employee" FROM EMP WHERE SAL =
1500;

tgt.. INSERT [(<column>. Increment a sequence by a certain amount: ANY/ SELECT * FROM DEPT WHERE LOC = SOME ('NEW ALTER SEQUENCE <sequence_name> INCREMENT BY <integer>. SELECT * FROM EMP WHERE NOT (sal BETWEEN 1000 Create a Function-Based Index AND 2000) In Oracle. SELECT ENAME FROM EMP WHERE SAL ^= 5000. r CREATE INDEX customer_idx NOT SELECT * FROM EMP WHERE NOT (job IS NULL) ON customer (customer_name). For example: >= SELECT * FROM PRICE WHERE MINPRICE >= 20. AND deptno=10 CREATE [UNIQUE] INDEX index_name ON table_name (function1. tgt. deptno=10 CREATE INDEX customer_idx Set Operators ON customer (UPPER(customer_name)). column2. N x and y Configure the sequence to cache a value: SELECT * FROM EMP WHERE EXISTS (SELECT ENAME ALTER SEQUENCE <sequence_name> CACHE <integer> | NOCACHE. (SELECT ENAME FROM EMP WHERE JOB = 'CLERK' ALTER INDEX customer_id RENAME TO new_customer_id.object_name 6 AND logical operator . src. Set the sequence to cycle or not cycle: [NOT] SELECT ENAME. ALTER SEQUENCE seq_inc_by_ten INCREMENT BY 10. ALTER INDEX index_name REBUILD COMPUTE STATISTICS. function2. ALTER SEQUENCE seq_maxval MAXVALUE 10. IS [NOT] SELECT * FROM EMP WHERE COMM IS NOT NULL AND Create an Index NULL SAL > 1500.object_name = src. create B-tree indexes. ALTER SEQUENCE seq_cycle NOCYCLE. JOB FROM EMP WHERE SAL BETWEEN ALTER SEQUENCE <sequence_name> <CYCLE | NOCYCLE>. you are not restricted to creating indexes on only columns. Operato Example Example: MERGE r INTO target_table tgt (+) SELECT ENAME. ^=..object_type Level WHEN NOT MATCHED 1 Unary + .)] VALUES (<expression> | Other Operators DEFAULT. DEPT WHERE USING source_table src DEPT. UNION SELECT * FROM ALTER INDEX customer_idx REBUILD COMPUTE STATISTICS. ALL SELECT * FROM emp WHERE sal >= ALL (1400.. ALTER SEQUENCE seq_order NOORDER. MERGE INTO [<qualifier>. || character operators . INTERSE SELECT * FROM orders_list1 Merge Statement CT and INTERSECT MERGE statement that could be thought of as a combination of INSERT and INTERSE SELECT * FROM orders_list2 UPDATE. ALL (SELECT SAL FROM EMP WHERE JOB = 'CLERK' Drop an Index UNION DROP INDEX customer_idx. PRIOR operator THEN 2 * / arithmetic operators INSERT ( tgt. JOB "Title" FROM EMP CREATE SEQUENCE sequence_name MINVALUE value MAXVALUE value WHERE SAL > 3000.object_id 3 Binary + . SELECT SAL FROM EMP WHERE JOB = 'ANALYST').DEPTNO (+). ALTER SEQUENCE <sequence_name> MAXVALUE <integer>..object_type ) 4 All comparison operators VALUES ( src. DNAME FROM EMP.]<table_name2> ON (<condition>) MINUS SELECT * FROM (SELECT SAL FROM EMP WHERE JOB = WHEN MATCHED THEN 'PRESIDENT' UPDATE SET {<column> = {<expression> | DEFAULT}. SOME YORK'. CREATE SEQUENCE supplier_seq SELECT ENAME FROM EMP WHERE SAL <= 1500.. 3000). 7 OR logical operator TRUNCATE statement TRUNCATE TABLE <table_name> This example illustrates the use of TRUNCATE statement using Oracle: . < SELECT * FROM PRICE WHERE MINPRICE < 30.. CREATE [UNIQUE] INDEX index_name Logical Operators ON table_name (column1.). z] Oracle will. src. IN SELECT * FROM EMP WHERE ENAME IN ('SMITH'. x [NOT] SELECT * FROM EMP WHERE ENAME LIKE '%E%'. An [ESCAPE index creates an entry for each value that appears in the indexed columns. function_n) OR SELECT * FROM emp WHERE job='CLERK' OR [ COMPUTE STATISTICS ].'DALLAS'). MINVALUE 1 MAXVALUE 999999999999999999999999999 <= START WITH 1 INCREMENT BY 1 CACHE 20. You can SELECT * FROM EMP WHERE job='CLERK' AND create function-based indexes. .object_id 5 NOT logical operator .object_name .object_type = src.object_id = tgt.object_name nce . START WITH value INCREMENT BY value CACHE value. . by default..} MINUS WHEN NOT MATCHED THEN SELECT SAL FROM EMP WHERE JOB = 'MANAGER'). column_n) Operato Example [ COMPUTE STATISTICS ].]<table_name1> CT ALL USING [<qualifier>.object_id ) PRIOR WHEN MATCHED THEN Levels of Precedence of the Oracle SQL Operators UPDATE Precede SQL Operator SET tgt. tgt. 'DALLAS').DEPTNO = EMP. Alter Sequence 'WARD').object_type ). Create Sequence <> The syntax for a sequence is: > SELECT ENAME "Employee". ALTER SEQUENCE <sequence_name> <ORDER | NOORDER>.. EXISTS FROM ALTER SEQUENCE seq_cache NOCACHE. Operato Example Rename an Index r The syntax for renaming an index is: UNION SELECT * FROM ALTER INDEX index_name RENAME TO new_index_name. Operato Example Other Concepts r Sequences !=. BETWEE 3000 AND 5000. NOT IN SELECT * FROM DEPT WHERE LOC NOT IN ('NEW Change the maximum value of a sequence: YORK'.arithmetic operators.arithmetic operators. UNION The syntax for collecting statistics on an index is: SELECT ENAME FROM EMP WHERE JOB = 'ANALYST'). Indexes LIKE y An index is a method by which records are retreived with greater efficiency. Set whether or not the values are to be returned in order EMP WHERE MGR IS NULL). ON ( src..

GREATEST(expression.quantity.-. orders.'recruitment') Example: CREATE VIEW sup_orders AS INITCAP(char) String with Initial Capitals SELECT suppliers. Rollback least one row restore the state of the EXP(n) Exponential (e to 'n'th power) database to the last EXTRACT Extract part of a DATE commit point.'Monday' will return the CONCAT(s1.s2) Concatenate string1 and string2 eek) next Mon after 12 Oct CONVERT(char_to_conver Convert a string from one character set NLS_CHARSET_DECL_LEN Returns the declaration width (no of t.start. new_char..n) log of n.’Sami’.supplier_name = 'IBM'. (10. NEW_TIME(date..supplier_id LAST_DAY(date) Returns the last day of month in Date and suppliers.Day.'marketing'. INSTRB (str.. SELECT columns IS NULL Check for NULL (empty) values (Select FROM table * from demo Where x IS NULL.remove leading spaces AVG([DISTINCT]n) Averge value of 'n' ignoring NULLs [or char set] BETWEEN value AND Where 'x' between 25 AND 100 MAKE_REF(table. PadChars] ATAN2(n. commit. (bytecount.by foreign key FK_ORDLINE_PRODUCT SQL> TRUNCATE TABLE PRODUCT. orders NULL.s[. orders. MIN([DISTINCT] expr) Minimum value returned by expr MOD(x. n[. MONTHS_BETWEEN(end_ Number of months between the 2 dates CEIL(n) Round n up to next whole number. chars[.len Convert to dec/hex/oct and display char done in a transaction (empno..y) Remainder of x divided by y CASE Group the data into sub-sets.supplier_id.) WHERE predicates. char LENGTHB(char) Returns the number of bytes in char SQL Functions (use for double-byte char sets) Function Description LIKE wildcard/value Wildcards are [% = any chars] [ _ = any ABS(n) Absolute value of number one char] Where 'x' LIKE 'smith%' [will ACOS(n) arc cosine of n find 'Smithson'] Where 'x' LIKE 'smith_' [will find 'Smithy'] ADD_MONTHS(date.2300).supplier_name = 'Microsoft'.’Hyd’). LPAD(char.] i.PadChar]) Left Pad char with n spaces [or ATAN(n) arc tangent of n.supplier_id = orders.m) arc tangent of n and m.) WHERE suppliers. Convert between GMT and US time CHR(n) Character with value n zone2) zones (but not CET) NEXT_DAY(date.. orders 'str' Starting at position 's' n and s WHERE suppliers. Creating Views IN (list of comma Effectively a shorthand for ['x' = y OR The syntax for creating a VIEW is: separated values) 'x' = z.TRUNCATE fails because PRODUCT is referenced Function Description -. orders. Commit To make the changes insert into emp DUMP(expr.ename. number. later you can roll back. LEAST(expression. /* empty a column or variable) give rollback undo the changes */ EXISTS Return TRUE if a subquery returns at statement.. start_date) (integer) CHARTOROWID(char) Converts a Char into a rowid value. savepoint a.s[. Where 'x' IN CREATE VIEW view_name AS SELECT columns FROM table WHERE predicates. chars[.price (Select * from demo Where x IS NOT FROM suppliers. COUNT([DISTINCT] expr) Count the no of rows returned by expr Transaction Control SYSDATE Transaction control statements manage changes made by DML statements. EMPTY_BLOB Return an empty LOB locator (use to COMMIT statement. The DECODE IF x THEN return y ELSE return z transaction control statements are: DENSE_RANK Calculate the rank of a value in a group Stateme Description Example DEREF(e) Return the object reference of nt argument e. LENGTH(char) Returns the number of characters in DROP VIEW sup_orders. zone1.quantity.) expressions DROP VIEW view_name. ('sales'.'fil Get the BFILE locator associated with a MAX([DISTINCT] expr) Maximum value returned by expr ename') physical LOB binary file. except that 's' and Changing a View the return value are expressed in CREATE OR REPLACE VIEW view_name AS bytes.supplier_id. Returns the largest in a list of insert into dept values expression.sal) values FLOOR(n) Round n down to the next whole t transaction to which (109. date.n]]) The same as INSTR.charset) chars) of an NCHAR column COS(n) Cosine of number NLS_CHARSET_ID(varcha Returns the char set ID given a charset COSH(n) Hyperbolic Cosine of number rs) name COUNT(*) Count the no of rows returned NLS_CHARSET_NAME(cha Returns the char set name given a . GROUPING Grouping for superaggregate rollback to a. base b LOWER(char) Returns character string in lowercase ASIN(n) arc sine of n. rows=NULL HEXTORAW(char) Convert char containing hex digits to a Views raw value.num_ Returns date + num_months months) LN(n) Natural Log of n.use for double-byte char sets.ename.price INSTR(str.Month.’Sales’.) expressions. EMPTY_CLOB Return an empty LOB locator (use to done in a transaction rollback. Returns the smallest in a list of Dropping View expression.sal) values gth]) set permanent issue the (101. where n>0 ASCII(char) Converts char into a decimal ascii code LOG(b.fmt[. old_char) to another. (Year.set]) Left Trim char . empty a column or variable) Rollback To rollback the changes delete from emp.3000).supplier_id = orders. LTRIM(char[.day_of_w '12-OCT-01'. Example: CREATE or REPLACE VIEW sup_orders AS IS NOT NULL Check for items that contain a value SELECT suppliers.key) Create a REF to a row of an OBJECT value view/table BFILENAME('directory'.n]]) Find the 'n'th occurence of 'chars' in FROM suppliers. orders.Second.’Abid’.e.supplier_id default to 1 and suppliers.etc) Savepoin Specify a point in a insert into emp (empno.

INSTANCE. For example.d) n rounded to d decimal places (d either the input or output datatype is defaults to 0) NCHAR or NVARCHAR2. ANSI alternative to decode() Replace NULL search_str[.l]) A substring of char. returns value_if_null) value_if_null. using an NLS sort_sequence either TO_DATE Convert to date value the session default or specified directly NLS_UPPER(char[. using an TAN(n) Tangent of n in Radians SORT = sort_sequence']) NLS sort_sequence either the session TANH(n) Hyperbolic tangent of n in Radians default or specified directly TO_BLOB(Raw_col) Convert LONG RAW and RAW values to NLS_LOWER(char[. CLIENT_INFO sound of the words. numeric(6.remove trailing spaces TRUNC(date. s[. T = sort_sequence']) char. starting at VSIZE(expr) Value Size. TRANSLATE('char'.'IP_ADDRESS' n ) float float(p) Where p is a precision value. NLS_SORT. replace_str defaults to null. length l. Type SUM([DISTINCT] n) Sum of values of n. USERENV('option') Can return any of the options: ENTRYID. char returns expression.'replace_str') with replace_str unlike REPLACE() if value containing its hex equivalent.n) m raised to the nth power TO_NUMBER Convert to numeric format RANK Calculate the rank of a value in a group TO_SINGLE_BYTE(char) Convert multi-byte char to single-byte character.'NLS_ Returns char in Initial Caps. ignoring NULLs integer integer SYS_CONTEXT('namespa Examine the package associated with smallint smallint ce'.'search Replace every occurrence of search_str REFTOHEX(ref) Convert ref (object type) to a char _str'. If expression is null.fmt) date rounded to fmt TRIM(LEADING|TRAILING| Return trim_source as a VARCHAR2 ROWIDTOCHAR(rowid) Convert a rowid value to VARCHAR2 BOTH trim_char FROM with leading/trailing items removed ROW_NUMBER Assign a unique number to each row of trim) trim_char defaults to a space ' ' but results. CURRENT_USER scale value. [or char set] UID User id (a unique number) SIGN(n) positive = 1.SESSION_USERID. SOUNDEX(char) Returns a char value representing the ISDBA. using an TO_LOB(long) Convert LONG values to CLOB or NCLOB values or convert LONG RAW ORT = sort_sequence']) NLS sort_sequence either the session default or specified directly values to BLOB values TO_MULTI_BYTE(char) Convert single-byte char to multi-byte NVL(expression. USER Return the current Username SINH(n) Hyperbolic Sine of n in Radians. replace_str]) every occurrence of search_str with TRANSLATE (text USING Convert text into a specific character replace_str. used by each row of expr. zero = 0. SESSIONID. ROUND(date.The arguments can TO_NCHAR(expr) Convert a TEXT expression.s) Where p is a precision value. or have any datatype (Oracle will perform number to NTEXT in a specified format. date. scale value. implicit conversion where needed).2) NLS_CURRENCY.set]) Right Trim char . 'l' and the Data Types return value are expressed in bytes.PadChar]) Right Pad char with n spaces [or TRUNC(i. ignoring NULLs SUBSTR(char.'NLS_S Returns char in lower case. using an BLOB ORT = sort_sequence']) NLS sort_sequence either the session TO_CHAR Convert to a character String default or specified directly TO_CLOB Convert character or NCLOB values to NLSSORT(char[. LANGUAGE. charset) set Use this instead of CONVERT() if ROUND(n.'NLS_SOR Return the string of bytes used to sort the database character set. if expression is not null.fmt) Truncate Date to nearest fmt. s is a attributes are: NLS_TERRITORY.) TO_TIMESTAMP Convert to timestamp The table alias (correlation variable) is TO_TIMESTAMP_TZ associated with one row of an object TO_YMINTERVAL Convert a character string to an table or an object view in an SQL INTERVAL YEAR TO MONTH type statement.Function Description Function Description rset_id) charset id SYSDATE The current system date & time NLS_INITCAP(char[.'NLS_S Returns char in UPPER case.'attribute_name') the context namespace Possible numeric numeric(p.l]) A substring of char. This data type is space padded . real real Single-precision floating point number CURRENT_USERID.s) Where p is a precision value. POWER(m. Mostly used to format output data. CURRENT SCHEMAID. s[. LANG. negative = -1 UPPER(char) Return characters in uppercase SIN(n) Sine of n in Radians.d) Truncate i to d decimal places (d PadChars] defaults to 0) RTRIM(char[. CURRENT_SCHEMA double double Double-precision floating point number SYS_CONTEXT precisio precision ('USERENV'. decimal and 2 digits after the decimal. n[. RAWTOHEX(raw) Convert raw to a character value TO_TIME Convert to time value containing its hex equivalent REF(table_alias) Returns a REF value for an object TO_TIME_TZ Convert to time zone instance (bound to the variable or row. PERCENT_RANK Calculate the percent rank of a value in TO_NCLOB Convert any character string (including a group. returns the number of bytes character s. decimal decimal(p. VARIANCE([DISTINCT] n) Variance of n. except that 's'. SYS_GUID() Returns a globally unique identifier (16 byte RAW value) charact char(x) Where x is the number of characters to er store. replace_str is NULL the function returns REPLACE(char. length l The same as SUBSTR. LOBs) to the national character set. may be numeric or char 'A' RPAD(char. starting at character s. VALUE(correlation_variab Return the object instance for a row of SQRT(n) Square Root (returns NULL for negative le) an object table as associated with the no's) correlation_variable (table alias) STDDEV([DISTINCT] n) Standard deviation of n. SUBSTRB(char. s is a SESSION_USER. TERMINAL. NLS_CALENDAR is a number that has 4 digits before the NLS_DATE_FORMAT. Data Syntax Explanation (if applicable) use for double-byte char sets. NLS_DATE_LANGUAGE.

and second values. mp and second values. Contains a day value. but also with zone stores an offset from UTC of the time time specified. time time with time Exactly the same as time. bit bit(x) Where x is the number of bits to store. hour. day. an hour value. This data type does NOT space varying pad. zone year. date date Stores year. month or both. charact varchar2(x) Where x is the number of characters to er store. minute. varying The length can vary up to x. zone timesta timestamp Exactly the same as timestamp. and day values. time time Stores the hour. month. month. and/or a second value. to fill the number of characters specified. bit bit varying(x) Where x is the number of bits to store. interval day. but mp with with time zone also stores an offset from UTC of the time time specified. timesta timestamp Stores year. minute. Contains a year value. a time minute value. interval . a month value.

-------------End of the Document------------ .