<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ORATraining Blog &#187; Oracle PL/SQL</title>
	<atom:link href="http://www.oratraining.com/blog/category/oracle/database/oracle-plsql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.oratraining.com/blog</link>
	<description>Not just another Oracle Blog</description>
	<lastBuildDate>Tue, 07 Feb 2012 06:27:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>PL/SQL quick reference</title>
		<link>http://www.oratraining.com/blog/2009/06/plsql-quick-reference/</link>
		<comments>http://www.oratraining.com/blog/2009/06/plsql-quick-reference/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 05:48:04 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database programming]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[Oracle Database]]></category>
		<category><![CDATA[Oracle developers]]></category>
		<category><![CDATA[Oracle PL/SQL]]></category>
		<category><![CDATA[commands]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[pl/sql]]></category>
		<category><![CDATA[quick reference]]></category>
		<category><![CDATA[reference]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[sqlplus]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.oratraining.com/blog/?p=185</guid>
		<description><![CDATA[Tweet Oracle PL/SQL Quick Reference   PL/SQL Block Structure DECLARE --Optional   --Variables, Cursors, User-defined exceptions BEGIN --Mandatory   --SQL statements   --PL/SQL statements EXCEPTION --Optional   --Actions to perform when errors occur END; --Mandatory   PL/SQL Block Type Anonymous               Procedure               Function [DECLARE]               PROCEDURE name          FUNCTION name [...]]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.oratraining.com%2Fblog%2F2009%2F06%2Fplsql-quick-reference%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://www.oratraining.com/blog/2009/06/plsql-quick-reference/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.oratraining.com/blog/2009/06/plsql-quick-reference/"  data-text="PL/SQL quick reference" data-count="horizontal">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://www.oratraining.com/blog/2009/06/plsql-quick-reference/" data-counter="right"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><pre>
<h2><strong>Oracle PL/SQL Quick Reference</strong></h2>

<strong> </strong>
<h3>PL/SQL Block Structure</h3>

DECLARE --Optional

  --Variables, Cursors, User-defined exceptions

BEGIN --Mandatory

  --SQL statements

  --PL/SQL statements

EXCEPTION --Optional

  --Actions to perform when errors occur

END; --Mandatory

<span id="more-185"></span> 

<strong>PL/SQL Block Type</strong>

<strong>Anonymous               Procedure               Function</strong>

[DECLARE]               PROCEDURE name          FUNCTION name

                        IS                      RETURN datatype                                                         IS

BEGIN                   BEGIN                   BEGIN

  --statements            --statements            --statements

                                                  RETURN value;

[EXCEPTION]             [EXCEPTION]             [EXCEPTION]

END ;                   END ;                   END ;

<strong> </strong>

<strong>Declaring PL/SQL Variables</strong>

identifier [CONSTANT] datatype [NOT NULL]

   [:=|DEFAULT expr];

<strong> </strong>

<strong>Assigning Values to Variables</strong>

identifier := expr;

<strong>Types of Variables</strong>

<strong>PL/SQL variables:</strong>
<ul type="disc">
<li>Scalar</li>
<li>Composite</li>
<li>Reference</li>
<li>LOB(<strong>L</strong>arge <strong>OB</strong>jects)</li>
</ul>

<strong>Non-PL/SQL variables:</strong> Bind or host variables
<ul type="disc">
<li>Used to pass run time values out of the PL/SQL block back to the Host environment</li>
</ul>

<strong> </strong>

<strong>Base Scalar Datatypes</strong>

VARCHAR2(maximum_length)      BOOLEAN           CHAR[(maximum_length)]

DATE                         LONG              LONG RAW    

BINARY_INTEGER                PLS_INTEGER       NUMBER(precision,scale)

TIMESTAMP

<strong>The %TYPE Attribute</strong>

Identifier Table_name.column_name%TYPE ;

Identifier Variable_name%TYPE ;

<strong> </strong>

<strong>Composite Datatypes</strong>

INDEX BY TABLE          RECORD      NESTED TABLE      VARRAY

<strong> </strong>

<strong>LOB Datatypes</strong>

CLOB        BLOB        BFILE             NCLOB

<strong> </strong>

<strong>Creating Bind Variables</strong>

VARIABLE variable_name dataype

<strong> </strong>

<strong>Displaying Bind Variables</strong>

PRINT [variable_name]

<em>NOTE: To reference a bind variable in PL/SQL, you must prefix it's name with colon (:)</em>

<strong>Commenting Code</strong>

--prefix single-line comments with two dashes

/* Place muti-line comment between the symbols */

<strong> </strong>

<strong>SELECT Statements in PL/SQL</strong>

SELECT {column_list|*}

INTO {variable_name[,variable_name]...

      |record_name}

FROM table

[WHERE condition];

<em>NOTE: The INTO clause is must and queries must return one and only one row. A CURSOR can be used to retrieve more than one row.</em>

<em> </em>

<strong>Implicit Cursor Attributes for DML statements</strong>

SQL%ROWCOUNT

SQL%FOUND

SQL%NOTFOUND

SQL%ISOPEN

<strong> </strong>

<strong>Control Structures</strong>

<strong>IF Statement                              Basic Loop</strong>

IF condition THEN                         LOOP

   statements;                               statements;

[ELSIF condition THEN                        ...

   statements;]                              EXIT [WHEN condition];

[ELSE                                     END LOOP;

   statements;]

END IF;

<strong> </strong>

<strong>FOR Loop                                  WHILE Loop</strong>

FOR counter IN [REVERSE]                  WHILE condition LOOP

   Lower_bound..upper_bound LOOP             statement1;

   statement1;                               statement2;

   statement2;                               ...

   ...                                    END LOOP;

END LOOP;

<strong> </strong>

<strong>CASE</strong>

CASE selector

   WHEN expression1 THEN result1

   WHEN expression2 THEN result2

   ...

   WHEN expressionN THEN resultN

   [ELSE resultN+1]

END;

<strong>Creating a PL/SQL Record</strong>

TYPE type_name IS RECORD

(field_declaration[,field_declaration]...) ;

identifier type_name ;

<strong> </strong>

<strong>Where field_declaration is:</strong>

field_name {field_type|variable%TYPE|

table.column%TYPE|table%ROWTYPE}

[[NOT NULL] {:=|DEFAULT} expr]

<strong> </strong>

<strong>Referencing Fields in the Record</strong>

record_name.field_name

<strong> </strong>

<strong>Declaring Records with the %ROWTYPE Attribute</strong>

DECLARE

record_name       reference%ROWTYPE

<strong> </strong>

<strong>Creating a PL/SQL Table (INDEX BY Table)</strong>

TYPE type_name IS TABLE OF

{column_type|variable%TYPE|table.column%TYPE

|variable%ROWTYPE} [NOT NULL]

[INDEX BY BINARY_INTEGER];

identifier type_name ;

<strong> </strong>

<strong>Referencing a PL/SQL table</strong>

pl_sql_table_name(primary_key_value)

<strong>Using PL/SQL Table Method</strong>

table_name.method_name[(parameters)]

<strong> </strong>

<strong>PL/SQL Table Methods</strong>

EXITS(n)    COUNT       FIRST       LAST        PRIOR(n)

NEXT(n)     EXTEND(n,i)             TRIM        DELETE

<strong>PL/SQL Table of Records</strong>

TYPE table_name_type IS TABLE OF table_name%ROWTYPE

INDEX BY BINARY_INTEGER ;

table_name table_name_type ;

<strong> </strong>

<strong>Referencing a Table of Records</strong>

table_name(index).field

<strong> </strong>

<strong>Cursor</strong>

<strong>Declaring the Cursor in Declaration Section</strong>

CURSOR cursor_name IS select_statement ;

record_name cursor_name%ROWTYPE ;

<strong> </strong>

<strong>Opening and Closing the Cursor</strong>

OPEN cursor_name ;

CLOSE cursor_name ;

<strong> </strong>

<strong>Fetching Data from the Cursor</strong>

FETCH cursor_name

INTO [variable1(,variable2,...)

    |record_name] ;

<strong> </strong>

<strong>Explicit Cusor Attributes</strong>

cursor_name%ISOPEN

cursor_name%NOTFOUND

cursor_name%FOUND

cursor_name%ROWCOUNT

<strong> </strong>

<strong>Cursor FOR Loops</strong>

FOR record_name IN cursor_name LOOP

   statement1;

   statement2;

   ...

END LOOP;

<strong> </strong>

<strong>Cursor FOR Loops Using Subqueries</strong>

FOR record_name IN (subqueries) LOOP

statement1

...

END LOOP ;

<strong> </strong>

<strong>Cursors with Parameters</strong>

CURSOR cursor_name [(cursor_parameter_name datatype

[,...])]

IS select_statement

[FOR UPDATE [OF column_reference][NOWAIT]];

<strong> </strong>

<strong>Parameter Name</strong>

cursor_parameter_name [IN] datatype [{:=|DEFAULT}expr]

<strong> </strong>

<strong>Openning with Parameters</strong>

OPEN cursor_name(cursor_parameter_name[,...]);

<strong> </strong>

<strong>Cursor FOR Loops with parameters</strong>

FOR record_name IN cursor_name(cursor_parameter_name

[,...]) LOOP

   statement1;

   statement2;

   ...

END LOOP;

<strong> </strong>

<strong>WHERE CURRENT OF clause</strong>

UPDATE|DELETE ... WHERE CURRENT OF cursor_name ;

<strong> </strong>

<strong>Predefined Exceptions</strong>

NO_DATA_FOUND

TOO_MANY_ROWS

INVALID_CURSOR

ZERO_DIVIDE

DUP_VAL_ON_INDEX

<strong> </strong>

<strong>Exception</strong>

<strong>Trapping Exceptions</strong>

EXCEPTION

   WHEN exception1 [OR exception2 ...] THEN

statement1 ;

statement2 ;

...

   [WHEN exception3 [OR exception4 ...] THEN

statement1 ;

statement2 ;

...]

   [WHEN OTHERS THEN

statement1 ;

statement2 ;

...]

<strong> </strong>

<strong>Declaring Non-Predefined Oracle Sever Exception</strong>

DECLARE

   exception EXCEPTION ;

   PRAGMA EXCEPTION_INIT(exception, error_number) ;

<strong> </strong>

<strong>Referencing the declared Non-predefined execption</strong>

BEGIN

   ...

EXCEPTION

   WHEN exception THEN

statement1 ;

...

END ;

<strong>Trapping User-Defined Exceptions</strong>

DECLARE

   exception EXCEPTION ;

BEGIN

   ...

   IF SQL%NOTFOUND THEN

RAISE exception ;

   END IF ;

   ...

EXCEPTION

   WHEN exception THEN

statement1 ;

...

END ;

<strong>Functions for Trapping Exceptions</strong>

SQLCODE           return error code

SQLERRM           return error message

<strong> </strong>

<strong>RAISE_APPLICATION_ERROR</strong><strong> procedure(Executable/Exception</strong>

<strong>Section)</strong>

RAISE_APPLICATION_ERROR ( error_number,

  message [, {TRUE|FALSE}]) ;

error_number      between -20000 to -20999

message           string up to 2,048 bytes long

TRUE              placed on the stack of previous errors.

FALSE             replaces all previous errors

<strong> </strong></pre>
<div class="printfriendly alignleft"><a href="http://www.oratraining.com/blog/2009/06/plsql-quick-reference/?pfstyle=wp" rel="nofollow" ><img src="//cdn.printfriendly.com/pf-button-both.gif" alt="Print Friendly" /></a></div><div class="tweetthis" style="text-align:left;"><p> <a class="tt" href="http://twitter.com/intent/tweet?text=PL%2FSQL+quick+reference+http%3A%2F%2Foratraining.com%2Fblog%2F%3Fp%3D185" title="Post to Twitter"><img class="nothumb" src="http://www.oratraining.com/blog/wp-content/plugins/tweet-this/icons/en/twitter/tt-twitter-big3.png" alt="Post to Twitter" /></a> <a class="tt" href="http://digg.com/submit?url=http://www.oratraining.com/blog/2009/06/plsql-quick-reference/&amp;title=PL%2FSQL+quick+reference" title="Post to Digg"><img class="nothumb" src="http://www.oratraining.com/blog/wp-content/plugins/tweet-this/icons/en/digg/tt-digg-big4.png" alt="Post to Digg" /></a></p></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.oratraining.com%2Fblog%2F2009%2F06%2Fplsql-quick-reference%2F&amp;title=PL%2FSQL%20quick%20reference" id="wpa2a_2"><img src="http://www.oratraining.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.oratraining.com/blog/2009/06/plsql-quick-reference/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Oracle SQL tuning tips</title>
		<link>http://www.oratraining.com/blog/2009/06/oracle-sql-tuning-tips/</link>
		<comments>http://www.oratraining.com/blog/2009/06/oracle-sql-tuning-tips/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 05:21:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database Performance Tuning]]></category>
		<category><![CDATA[Database programming]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[Oracle Database]]></category>
		<category><![CDATA[Oracle DBA]]></category>
		<category><![CDATA[Oracle developers]]></category>
		<category><![CDATA[Oracle PL/SQL]]></category>
		<category><![CDATA[commands]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[performance tuning]]></category>
		<category><![CDATA[pl/sql]]></category>
		<category><![CDATA[reference]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[SQL tuning]]></category>
		<category><![CDATA[sqlplus]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tuning]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.oratraining.com/blog/?p=176</guid>
		<description><![CDATA[Tweet Oracle SQL Tuning Tips consideration when writing an SQL statement is that it returns a correct result. The second is that it be the most efficient for a given situation.  You can use many different SQL statements to achieve the same result. It is often the case that only one statement will be the [...]]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.oratraining.com%2Fblog%2F2009%2F06%2Foracle-sql-tuning-tips%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://www.oratraining.com/blog/2009/06/oracle-sql-tuning-tips/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.oratraining.com/blog/2009/06/oracle-sql-tuning-tips/"  data-text="Oracle SQL tuning tips" data-count="horizontal">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://www.oratraining.com/blog/2009/06/oracle-sql-tuning-tips/" data-counter="right"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><h2>Oracle SQL Tuning Tips</h2>
<p>consideration when writing an SQL statement is that it returns a correct result. The second is that it be the most efficient for a given situation.  You can use many different SQL statements to achieve the same result. It is often the case that only one statement will be the most efficient choice in a given situation.</p>
<p>Remember that processing SQL is a sequence of Parse (syntax check and object resolution), Execution (required reads and writes), and Fetch (row results retrieved, listed, sorted, and returned). SQL &#8220;tuning&#8221; consists, quite simply, of reducing one or more of them.</p>
<p>Note: generally Parse is the greatest time and resource hog. Parse overhead can be minimized by the use of Procedures, Functions, Packages, Views, etc.</p>
<p>Inadequate performance can have a significant cost impact on your business. A poor performing system and application can result in customer dissatisfaction, reduced productivity, and high costs. It is absolutely critical that the system&#8217;s performance is operating at its peak levels.</p>
<p>Following are some general tips that often increase SQL statement efficiency. Being general they may not apply to a particular scenario.<span id="more-176"></span></p>
<ul>
<li>Tuning SQL should only be done after your code is working correctly. Be aware that there is an inevitable tug-of-war between writing efficient SQL and understandable SQL.</li>
<li>Ensure repeated SQL statements are written<em>absolutely identically</em>to facilitate efficient reuse: re-parsing can often be avoided for each subsequent use of an identical statement.<br />
Writing best practices: all SQL verbs in upper-case i.e. SELECT; separate all words with a single space; all SQL verbs begin on a new line; SQL verbs aligned right or left within the initial verb; set and maintain a table alias standard; use table aliases and when a query involves more than one table prefix all column names with their aliases. Whatever you do, be consistent.</li>
<li>o Use bind variables: The values of bind variables do not need to be the same for two statements to be considered identical. Bind variables are not substituted until a statement has been successfully parsed.</li>
<li>o Use standard approach to table aliases. If two identical SQL statements vary because an identical table has two different aliases, then the SQL is different and will not be re-use or shared.</li>
<li>o Use table aliases and prefix all column names by their aliases when more than one table is involved in a query. This reduces parse time and prevents future syntax errors if someone adds a column to one of the tables with same name as a column in another table. (ORA-00918: COLUMN AMBIGUOUSLY DEFINED)</li>
<li>Code the query as simply as possible i.e. no unnecessary columns are selected, no unnecessary GROUP BY or ORDER BY.<br />
It is the same or faster to SELECT by actual column name(s). The larger the table the more likely the savings.<br />
<em>Use:</em><br />
<em>SELECT customer_id, last_name, first_name, street, city FROM customer;<br />
Rather than, </em><em><br />
SELECT * FROM customer;</em></li>
<li>Beware of WHERE clauses which do not use indexes at all. Even if there is an index over a column that is referenced by a WHERE clause included in this section, Oracle will ignore the index. All these WHERE clause can be re-written to use an index while returning the same values. In other words, Do not perform operations on database objects referenced in the WHERE clause:<br />
<em>Use:<br />
</em><em>SELECT client, date, amount FROM sales WHERE amount <strong>&gt; 0;</strong></em><em><br />
Rather than:<br />
</em><em>SELECT client, date, amount FROM sales WHERE amount <strong>!= 0;<br />
</strong>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
Use:<br />
SELECT account_name, trans_date, amount FROM transaction WHERE account_name <strong>LIKE &#8216;CAPITAL%&#8217;;</strong><br />
</em><em>Rather than:</em><em><br />
SELECT account_name, trans_date, amount FROM transaction WHERE <strong>SUBSTR(account_name,1,7)=</strong>&#8216;CAPITAL&#8217;;<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
Use:<br />
SELECT account_name, trans_date, amount FROM transaction WHERE amount <strong>&gt; 0;<br />
</strong></em><em>Rather than:<br />
</em><em>SELECT account_name, trans_date, amount FROM transaction WHERE amount <strong>NOT=0;<br />
</strong>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<strong><br />
</strong>Use:<br />
SELECT account_name, trans_date, amount FROM transaction WHERE<strong> amount &lt; 2000;<br />
</strong>Rather than:<br />
SELECT account_name, trans_date, amount FROM transaction WHERE <strong>amount + 3000 </strong>&lt; 5000;<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
Use:<br />
SELECT account_name, trans_date, amount FROM transaction WHERE <strong>account_name = &#8216;AMEX&#8217; AND account_type = &#8216;A&#8217;;<br />
</strong>Rather than:<br />
SELECT account_name, trans_date, amount FROM transaction WHERE <strong>account_name|| account_type=</strong>&#8216;AMEXA&#8217;; </em></li>
<li>Don&#8217;t forget to tune views. Views are SELECT statements and can be tuned in just the same way as any other type of SLECT statement can be. All tuning applicable to any SQL statement are equally applicable to views.</li>
<li>Avoid including a HAVING clause in SELECT statements. The HAVING clause filters selected rows only after all rows have been fetched. Using a WHERE clause helps reduce overheads in sorting, summing, etc. HAVING clauses should only be used when columns with summary operations applied to them are restricted by the clause.<br />
<em>Use:</em><br />
<em>SELECT city FROM country <strong>WHERE</strong> city!= &#8216;Vancouver&#8217; AND city!= &#8216;Toronto&#8217;; GROUP BY city;</em><em><br />
Rather than:<br />
</em><em>SELECT city FROM country GROUP BY city <strong>HAVING</strong> city!= &#8216;Vancouver&#8217; AND city!= &#8216;Toronto&#8217;;</em></li>
<li>Minimize the number of table lookups (subquery blocks) in queries, particularly if our statements include subquery SELECTs or multicolumn UPDATEs.<br />
<em>Use:<br />
SELECT emp_name FROM emp WHERE <strong>(emp_cat, sal_range</strong>) = (<strong>SELECT</strong> MAX(category), MAX(sal_range) FROM emp_categories) AND emp_dept = 0020;<br />
Rather than:<br />
SELECT emp_name FROM emp WHERE <strong>emp_cat</strong>=(<strong>SELECT</strong> MAX(category) FROM emp_categories) AND <strong>emp_range</strong> = (<strong>SELECT</strong> MAX(sal_range) FROM emp_categories) AND emp_dept = 0020;</em></li>
<li>When writing a sub-query (a SELECT statement within the WHERE or HAVING clause of another SQL statement):</li>
<li>o Use a correlated (refers to at least one value from the outer query) sub-query when the return is relatively small and/or other criteria are efficient i.e. if the tables within the sub-query have efficient indexes.</li>
<li>o Use a non-correlated (does not refer to the outer query) sub-query when dealing with large tables from which you expect a large return (many rows) and/or if the tables within the sub-query do not have efficient indexes.</li>
<li>o Ensure that multiple sub-queries are in the most efficient order.</li>
<li>o Remember that rewriting a sub-query as a join can sometimes increase efficiency.</li>
<li>When doing multiple table joins consider the benefits/costs for each of EXISTS, IN, and table joins. Depending on your data one or another may be faster.<br />
Note: IN is usually the slowest.<br />
Note: When most of the filter criteria are in the sub-query IN may be more efficient; when most of the filter criteria are in the parent-query EXISTS may be more efficient.<em><br />
The following queries return the employee names from each department in department category &#8216;A&#8217;:</em><br />
<em>SELECT emp_name FROM emp E WHERE <strong>EXISTS </strong>(SELECT &#8216;X&#8217; FROM dept WHERE dept_no = E.dept_no AND dept_cat = &#8216;A&#8217;);</em><br />
<em>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</em><em><br />
SELECT emp_name FROM emp E WHERE dept_no <strong>IN </strong>(SELECT dept_no FROM dept WHERE dept_no = E.dept_no AND dept_Cat = &#8216;A&#8217;);<br />
</em><em>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</em><em><br />
SELECT emp_name FROM dept D, emp E WHERE E.dept_no = D.dept_no AND D.dept_cat = &#8216;A&#8217;;</em></li>
<li>Where possible use EXISTS rather than DISTINCT, to avoid full table scan as DISTINCT operator causes Oracle to fetch all rows satisfying the table join and then sort and filter out duplicate values. EXISTS is a faster alternative, because the Oracle optimizer realizes when the subquery has been satisfied once, there is no need to proceed further and the next matching row can be fetched.<br />
<em>Use:<br />
SELECT S.id, S.description FROM small_table S WHERE <strong>EXISTS </strong>(SELECT NULL FROM big_table B WHERE B.id = S.id);<br />
Rather than:<br />
SELECT <strong>DISTINCT S.id, S.description</strong> FROM small_table S, big_table B<br />
WHERE S.id = B.id;</em></li>
<li>Where possible use a non-column expression (putting the column on one side of the operator and all the other values on the other). Non-column expressions are often processed earlier thereby speeding the query.<br />
<em>Use:<br />
</em><em>WHERE SALES &lt; 1000/(1 + n);</em><em><br />
Rather than:<br />
</em><em>WHERE SALES + (n * SALES) &lt; 1000;</em></li>
<li>Where possible use UNION ALL rather than using UNION. The UNION clause forces all rows retuned by each portion of the UNION to be sorted and merged and duplicates to be filtered out before the first row is returned. A UNION ALL simply returns all rows including duplicates and does not have to perform any sort, merge or filter. If your tables are mutually exclusive(include no duplicate records), or you don&#8217;t care if duplicates are returned, the UNION ALL is much more efficient.<br />
<em>USE:</em><br />
<em>SELECT acct_num, balance_amt FROM debit_transactions WHERE tran_date = &#8217;31-DEC-95&#8242;<br />
<strong>UNION ALL</strong><br />
SELECT acct_num, balance_amt FROM credit_transactions WHERE tran_date = &#8217;31-DE -95&#8242;;<br />
Rather than:<br />
SELECT acct_num, balance_amt FROM debit_transactions WHERE tran_date = &#8217;31-DEC-95&#8242;<br />
<strong>UNION</strong><br />
SELECT acct_num, balance_amt FROM credit_transactions WHERE tran_date = &#8217;31-DE -95&#8242;;</em></li>
<li>Consider using DECODE to avoid having to scan the same rows repetitively or join the same table repetitively. Note, DECODE is not necessarily faster as it depends on your data and the complexity of the resulting query. Also, using DECODE requires you t change your code when new values are allowed in the field.<br />
<em>USE:<br />
SELECT COUNT(<strong>DECODE</strong>(status,&#8217;Y',&#8217;X',NULL)) Y_count,<br />
COUNT(<strong>DECODE</strong>(status,&#8217;N',&#8217;X',NULL)) N_count<br />
FROM emp WHERE emp_name LIKE &#8216;SMITH%&#8217;;<br />
Raher than:<br />
SELECT COUNT(*) FROM emp WHERE status = &#8216;Y&#8217; AND emp_name LIKE &#8216;SMITH%&#8217;;<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
SELECT COUNT(*) FROM emp WHERE status = &#8216;N&#8217; AND emp_name LIKE &#8216;SMITH%&#8217;;</em></li>
<li>Oracle automatically performs simple column type conversions(or casting) when it compares columns of different types. Depending on the type of conversion, indexes may not be used. Make sure you declare your program variables as the same type as your Oracle columns, if the type is supported in the programming language you are using.<br />
<em>Use:<br />
SELECT emp_no, emp_name, sal FROM emp WHERE emp_no = &#8217;123&#8242;;<br />
HERE if emp_no indexed numeric, then after implicit conversion query will be:<br />
SELECT emp_no, emp_name, sal FROM emp WHERE emp_no = <strong>TO_NUMBER</strong>(&#8217;123&#8242;); </em><br />
<em>Thus, index is used in this case.<br />
Don&#8217;t use:<br />
SELECT emp_no, emp_name, sal FROM emp WHERE emp_type = 123;<br />
HERE if emp_type is indexed varchar2, then after implicit conversion query will be:</em><br />
<em>SELECT emp_no, emp_name, sal FROM emp WHERE TO_NUMBER(emp_type) = 123;</em><br />
<em>Thus, index will not be used in this case.</em></li>
<li>The most efficient method for storing large binary objects, i.e. multimedia objects, is to place them in the file system and place a pointer in the DB.</li>
<li>B-Tree Indexes do not store entries for NULL, so IS NULL is not indexable, but IS NOT NULL is indexable and thus if a huge table contains very few not null values then you should go for B-Tree indexes. On the other hand bitmap indexes support IS NULL condition.<br />
<em>SELECT * FROM big WHERE status IS NOT NULL; (Use B-tree index in this case)</em></li>
<li>Avoid using functions on indexed columns unless a function-based index is created; as it leads to full table scan even though index exists on the column.</li>
</ul>
<p><strong>Avoid using the following:</strong></p>
<ul type="disc">
<li>Boolean operators &gt;, &lt;, &gt;=, &lt;=, IS NULL, IS NOT NULL</li>
<li>NOT IN, !=</li>
<li>Like &#8216;%pattern&#8217;, not exists</li>
<li>Calculations on unindexed columns or (use union instead)</li>
<li>Having (use a WHERE clause instead when appropriate)</li>
</ul>
<p><strong> </strong><strong>Do use the following:</strong></p>
<ul type="disc">
<li>Enable aliases to prefix all columns</li>
<li>Place indexed columns higher in the WHERE clause</li>
<li>Use SQL Joins instead of using sub-queries</li>
<li>Make the table with the least number of rows, the driving table, by making it first in the FROM clause</li>
</ul>
<p><strong>Other important points for SQL Tuning</strong></p>
<ul type="disc">
<li>Establish a tuning environment that reflects your production database</li>
<li>Establish performance expectations before you begin</li>
<li>Always Design and develop with performance in mind</li>
<li>Create Indexes to support selective WHERE clauses and join conditions</li>
<li>Use concatenated indexes where appropriate</li>
<li>Consider indexing more than you think you should, to avoid table lookups</li>
<li>Pick the best join method</li>
<li>Nested loops joins are best for indexed joins of subsets</li>
<li>Hash joins are usually the best choice for &#8220;big&#8221; joins</li>
<li>Pick the best join order</li>
<li>Pick the best &#8220;driving&#8221; table</li>
<li>Eliminate rows as early as possible in the join order</li>
<li>Use bind variables. Bind variables are key to application scalability</li>
<li>Use Oracle hints where appropriate</li>
<li>Compare performance between alternative syntax for your SQL statement</li>
<li>Consider utilizing PL/SQL to overcome difficult SQL tuning issues</li>
<li>Consider using third party tools to make the job of SQL tuning easier</li>
</ul>
<p>Performing these steps is easy and provides a tremendous benefit and performance boost. Follow these simple steps and you can increase your system performance.</p>
<div class="printfriendly alignleft"><a href="http://www.oratraining.com/blog/2009/06/oracle-sql-tuning-tips/?pfstyle=wp" rel="nofollow" ><img src="//cdn.printfriendly.com/pf-button-both.gif" alt="Print Friendly" /></a></div><div class="tweetthis" style="text-align:left;"><p> <a class="tt" href="http://twitter.com/intent/tweet?text=Oracle+SQL+tuning+tips+http%3A%2F%2Foratraining.com%2Fblog%2F%3Fp%3D176" title="Post to Twitter"><img class="nothumb" src="http://www.oratraining.com/blog/wp-content/plugins/tweet-this/icons/en/twitter/tt-twitter-big3.png" alt="Post to Twitter" /></a> <a class="tt" href="http://digg.com/submit?url=http://www.oratraining.com/blog/2009/06/oracle-sql-tuning-tips/&amp;title=Oracle+SQL+tuning+tips" title="Post to Digg"><img class="nothumb" src="http://www.oratraining.com/blog/wp-content/plugins/tweet-this/icons/en/digg/tt-digg-big4.png" alt="Post to Digg" /></a></p></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.oratraining.com%2Fblog%2F2009%2F06%2Foracle-sql-tuning-tips%2F&amp;title=Oracle%20SQL%20tuning%20tips" id="wpa2a_4"><img src="http://www.oratraining.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.oratraining.com/blog/2009/06/oracle-sql-tuning-tips/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SQL*Plus Basic commands</title>
		<link>http://www.oratraining.com/blog/2009/06/sqlplus-basic-commands/</link>
		<comments>http://www.oratraining.com/blog/2009/06/sqlplus-basic-commands/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 05:18:21 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Database programming]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[Oracle Database]]></category>
		<category><![CDATA[Oracle DBA]]></category>
		<category><![CDATA[Oracle developers]]></category>
		<category><![CDATA[Oracle PL/SQL]]></category>
		<category><![CDATA[commands]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[pl/sql]]></category>
		<category><![CDATA[quick reference]]></category>
		<category><![CDATA[reference]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[sqlplus]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.oratraining.com/blog/?p=174</guid>
		<description><![CDATA[Tweet Using SQL*Plus SQL*Plus is a command-line tool that provides access to the Oracle RDBMS. SQL*Plus enables you to: Enter SQL*Plus commands to configure the SQL*Plus environment Startup and shutdown an Oracle database Connect to an Oracle database Enter and execute SQL commands and PL/SQL blocks Format and print query results SQL*Plus is available on [...]]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.oratraining.com%2Fblog%2F2009%2F06%2Fsqlplus-basic-commands%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://www.oratraining.com/blog/2009/06/sqlplus-basic-commands/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.oratraining.com/blog/2009/06/sqlplus-basic-commands/"  data-text="SQL*Plus Basic commands" data-count="horizontal">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://www.oratraining.com/blog/2009/06/sqlplus-basic-commands/" data-counter="right"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><h2>Usi<a href='http://atlantic-drugs.net/products/tretinoin-cream-0-05-.htm'>n</a>g SQL*Plus</h2>
<p>SQL*Plus is a command-line tool that provides access to the Oracle RDBMS.</p>
<p>SQL*Plus enables you to:</p>
<ul type="disc">
<li>Enter SQL*Plus commands to configure the SQL*Plus environment</li>
<li>Startup and shutdown an Oracle database</li>
<li>Connect to an Oracle database</li>
<li>Enter and execute SQL commands and PL/SQL blocks</li>
<li>Format and print query results</li>
</ul>
<p>SQL*Plus is available on several platforms. In addition, it has a web-based user</p>
<p>interface, <em>i</em>SQL*Plus.</p>
<p>SQL*Plus is a client terminal software allowing users to interact with Oracle server to manipulate data and data structures. Users type in SQL statements in SQL*Plus that send statements to Oracle server. Oracle server then validates and executes the statements on its databases. The query results are returned to SQL*Plus and displayed to the user.  Besides sending SQL statements to the server, SQL*Plus also saves them into a local buffer and allow users to view and change the statements. The following figure illustrates the process.<span id="more-174"></span></p>
<p>After you login into SQL*Plus, at the SQL prompt, you can begin typing any SQL command. Upon hitting return (i.e., enter key) the SQL prompt will change to line number prompts. When you are finished typing a command, type / or RUN to execute the SQL command. Also, a semicolon at the end of the SQL command will execute the command immediately after hitting return. In addition to SQL commands, /, and RUN, you can also executes SQL*Plus file commands.</p>
<p><strong>SQL*PLUS Commands Quick Reference</strong></p>
<p>Below table shows, SQL*Plus commands available in the command-line interface. Not all commands or command parameters are shown.</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="175" valign="top"><strong>How to &#8230;</strong></td>
<td width="415" valign="top"><strong>SQL*Plus Command</strong></td>
</tr>
<tr>
<td width="175" valign="top">Log in to SQL*Plus</td>
<td width="415" valign="top">SQLPLUS [ { username[/passward][@connect_identifier] | / }  [ AS { SYSDBA | SYSOPER } ] | /NOLOG ]</td>
</tr>
<tr>
<td width="175" valign="top">List help topics available in SQL*Plus</td>
<td width="415" valign="top">HELP [ INDEX | topic ]</td>
</tr>
<tr>
<td width="175" valign="top">Execute host commands</td>
<td width="415" valign="top">HOST [ command ]</td>
</tr>
<tr>
<td width="175" valign="top">Show SQL*Plus system variables or environment settings</td>
<td width="415" valign="top">SHOW { ALL | ERRORS | USER | system_variable | &#8230; }</td>
</tr>
<tr>
<td width="175" valign="top">Alter SQL*Plus system variables or environment settings</td>
<td width="415" valign="top">SET system_variable value</td>
</tr>
<tr>
<td width="175" valign="top">Start up a database</td>
<td width="415" valign="top">STARTUP PFILE = filename  [ MOUNT [ dbname ] | NOMOUNT | &#8230; ]</td>
</tr>
<tr>
<td width="175" valign="top">Connect to a database</td>
<td width="415" valign="top">CONNECT [ [ username [ /password ] [ @connect_identifier ]          [ / AS { SYSOPER | SYSDBA } ]</p>
<p>]</td>
</tr>
<tr>
<td width="175" valign="top">List column definitions for a table, view, or synonym, or specifications for afunction or procedure</td>
<td width="415" valign="top">DESCRIBE [ schema. ] object</td>
</tr>
<tr>
<td width="175" valign="top">Edit contents of the SQL buffer or a file</td>
<td width="415" valign="top">EDIT [ filename [ .ext ] ]</td>
</tr>
<tr>
<td width="175" valign="top">Get a file and load its contents into the SQLBuffer</td>
<td width="415" valign="top">GET filename [ .ext ] [ LIST | NOLLIST ]</td>
</tr>
<tr>
<td width="175" valign="top">Save contents of the SQL buffer to a file</td>
<td width="415" valign="top">SAVE filename [ .ext ] [ CREATE | REPLACE | APPEND ]</td>
</tr>
<tr>
<td width="175" valign="top">List contents of the SQL Buffer</td>
<td width="415" valign="top">LIST [ n | nm | n LAST | ... ]</td>
</tr>
<tr>
<td width="175" valign="top">Delete contents of the SQL Buffer</td>
<td width="415" valign="top">DEL [ n | nm | n LAST | ... ]</td>
</tr>
<tr>
<td width="175" valign="top">Add new lines following current line in the SQL buffer</td>
<td width="415" valign="top">INPUT [ text ]</td>
</tr>
<tr>
<td width="175" valign="top">Append text to end ofcurrent line in the SQL</p>
<p>buffer</td>
<td width="415" valign="top">APPEND text</td>
</tr>
<tr>
<td width="175" valign="top">Find and replace first occurrence of a text string in current line of the SQL buffer</td>
<td width="415" valign="top">CHANGE sepchar old [ sepchar [ new [ sepchar ] ] ]sepchar can be any non-alphanumeric character such as &#8220;/&#8221; or &#8220;!&#8221;</td>
</tr>
<tr>
<td width="175" valign="top">Capture query results in a file and, optionally, send contents of file to default printer</td>
<td width="415" valign="top">SPOOL [ filename [ .ext ]  [ CREATE | REPLACE | APPEND | OFF | OUT ]</td>
</tr>
<tr>
<td width="175" valign="top">Run SQL*Plus statements stored in a file</td>
<td width="415" valign="top">@ { url | filename [ .ext ] } [ arg... ]START filename [ .ext ] [ arg... ]</p>
<p>.ext can be omitted if the filename extension is .sql</td>
</tr>
<tr>
<td width="175" valign="top">Execute commands stored in the SQL buffer</td>
<td width="415" valign="top">/</td>
</tr>
<tr>
<td width="175" valign="top">List and execute commands stored in the SQL buffer</td>
<td width="415" valign="top">RUN</td>
</tr>
<tr>
<td width="175" valign="top">Execute a single PL/SQL statement or run a stored procedure</td>
<td width="415" valign="top">EXECUTE statement</td>
</tr>
<tr>
<td width="175" valign="top">Disconnect from a database</td>
<td width="415" valign="top">DISCONNECT</td>
</tr>
<tr>
<td width="175" valign="top">Shut down a database</td>
<td width="415" valign="top">SHUTDOWN [ ABORT | IMMEDIATE | NORMAL | ... ]</td>
</tr>
<tr>
<td width="175" valign="top">Log out of SQL*Plus</td>
<td width="415" valign="top">{ EXIT | QUIT }  [ SUCCESS | FAILURE | WARNING | ... ]</p>
<p>[ COMMIT | ROLLBACK ]</td>
</tr>
</tbody>
</table>
<p><a name="SQL*Plus_file_commands"></a></p>
<p>SQL*Plus file command allow you to execute commands (or programs) stored in an external file, input or output data from/to a file, and save SQL commands typed during current session.</p>
<p>Some SQL*Plus file commands are:</p>
<ul type="disc">
<li>SAVE filename. This allows you to save buffer contents into a file.</li>
<li>START filename. This allows you to execute a batch of SQL statements stored in a file.</li>
<li>SPOOL filename. This allows you save SQL statements together with their outputs to a file.</li>
<li> GET filename. This retrieve a file and places it into the buffer.</li>
<li>@ filename. This allows you to execute a PL/SQL procedure(s) stored in a file.</li>
</ul>
<h2><a name="SQL*Plus_edit_commands"></a></h2>
<p>Recall that the previously executed commands (in current SQL*Plus session) are stored in the local buffer. One way to change an SQL statement in the buffer is by using the<em> <strong>line editor</strong></em>. The following are a list of line edit commands.</p>
<ul type="disc">
<li>LIST or L&#8211;Lists the contents of the buffer</li>
<li>LIST n or L n&#8211;Lists the contents of line number n in the buffer and makes the line current</li>
<li>LIST * or L *&#8211;Lists the current line</li>
<li>LIST m n&#8211;Lists the range from m to n line</li>
<li>Append text or A text&#8211;Adds to the end of the current line (e.g., &#8220;A ,&#8221; adds a comma to the end of line</li>
<li>INPUT or I&#8211;Adds one or more lines after the current line so you can begin adding the text.</li>
<li>CHANGE /text&#8211;Deletes text from the current line</li>
<li>CHANGE /oldtext/newtext&#8211;Replaces oldtext with newtext in the current line</li>
<li>DEL &#8212; Deletes the current line</li>
</ul>
<p>Besides line editor, you can also use the <em>vi editor</em> if you are a fan of Unix editor!.</p>
<p>To invoke the vi editor, type Edit at the SQL Prompt.   Multiple SQL commands can be typed in vi editor. End each SQL command (except the last one) with a semicolon. After exiting notepad, type Start to run all of the commands.</p>
<h2><a name="run_batch_sql"></a>Run SQL statements in a batch</h2>
<p>To run SQL commands in a batch, you can put all your SQL commands into a text file and execute these commands in this file in SQL*PLUS.</p>
<ul type="disc">
<li>Use your favorite editor to type in your SQL queries into a text file.</li>
</ul>
<p>For Example,</p>
<p>$ more table.sql<br />
DROP TABLE employee<br />
/</p>
<p>commit<br />
/</p>
<p>CREATE TABLE employee (<br />
empno INTEGER NOT NULL,<br />
name VARCHAR2(50) NOT NULL,<br />
sal REAL NOT NULL,<br />
primary key (empno));<br />
/</p>
<p>INSERT INTO employee VALUES (1, &#8216;Jack&#8217;, 6000);<br />
INSERT INTO employee VALUES (2, &#8216;Tom&#8217;,  6000);<br />
INSERT INTO employee VALUES (3, &#8216;John&#8217;, 6000);<br />
INSERT INTO employee VALUES (4, &#8216;Jane&#8217;, 6000);<br />
/</p>
<p>UPDATE employee SET sal=500 WHERE name=&#8217;Jack&#8217;<br />
/</p>
<p>CREATE INDEX test_index on employee(sal)<br />
/<br />
$</p>
<ul type="disc">
<li>Connect into SQL*Plus, and run the batch of commands. For example, assume that you name the SQL file as <em>table.sql</em>.</li>
</ul>
<p><tt>SQL&gt; START table.sql</tt>;</p>
<h2><a name="output_to_file"></a>Output results <a name="Output"></a></h2>
<ul type="disc">
<li>You can record your SQL command outputs to a file for output or editing purpose.</li>
</ul>
<p>SQL&gt; <tt>SPOOL </tt>&lt;your file name&gt;</p>
<p>For example,</p>
<p><tt>SQL&gt; SPOOL myoutput.out</tt></p>
<p>All SQL commands and their outputs after this command are written into the file <tt>myoutput.out </tt>that by default is stored in the current working directory where you invoked SQL*Plus.</p>
<ul type="disc">
<li>To end recording, use the following command: <tt> </tt></li>
</ul>
<p><tt>SQL&gt; SPOOL OFF</tt></p>
<h2><a name="dual"></a>DUAL and select the current time</h2>
<p>DUAL is the dummy table, mostly used to view the results from functions and calculations. The built-in function <tt>SYSDATE</tt> returns a <tt>DATE</tt> value containing the current date and time on your system. (Note Oracle is a client-server architecture and SQL*Plus is the client. SYSDATE gives you the time of the Unix system which you telnet in. It may NOT be the time of Oracle server unless you telnet into the machine running Oracle server.)</p>
<p>For example,</p>
<pre>SQL&gt; SELECT TO_CHAR(<tt>SYSDATE</tt> , 'Dy DD-Mon-YYYY HH24:MI:SS') as "Current Date/Time" FROM DUAL;;</pre>
<p>Result:</p>
<pre>Current Time</pre>
<pre>------------------------------------------------------------------------</pre>
<pre>Mon 15-July-2002 10:01:29</pre>
<ul type="disc">
<li>TO_CHAR is a function to format a value.</li>
<li><tt>DUAL</tt> is built-in relation in Oracle which serves as a dummy relation to put in the <tt>FROM</tt> clause when nothing else is appropriate. For example, try &#8220;SELECT 2+2 FROM DUAL;&#8221;</li>
<li>To format a number attribute to a dollar format, use the <em>column &lt;attribute&gt; format &lt;format&gt;</em>:</li>
</ul>
<pre>       SQL&gt; COLUMN salary FORMAT $999,999</pre>
<ul type="disc">
<li>To indicate the displayed width of a character string attribute, use the <em>column &lt;attribute&gt; format &lt;A&#8217;format&gt;</em>. For example, set the width of the name attribute to 8 characters.</li>
</ul>
<pre>       SQL&gt; COLUMN name FORMAT A8</pre>
<p>If a name is longer than 8 characters, the remaining is displayed at the second line (or several lines)</p>
<ul type="disc">
<li>The <em>set</em> command can be used to change the default number of lines per page (14) and the number of characters per line (80).</li>
</ul>
<p>For example, to set the number of lines per page to 60, use the following command:</p>
<pre>   SQL&gt; SET PAGESIZE 60</pre>
<ul type="disc">
<li>All formatting remain active until they are cleared or reset or after you exit from SQL*Plus.</li>
</ul>
<pre>   SQL&gt; CLEAR COLUMN</pre>
<ul type="disc">
<li>If you forget a specific SQL command you could enter</li>
</ul>
<p><tt> SQL&gt; HELP &lt;the SQL command&gt;;</tt></p>
<p>You could also find out all commands by entering:</p>
<p><tt> SQL&gt; HELP menu;</tt></p>
<ul type="disc">
<li>Sometimes when you get something fuzzy, you  can try the following</li>
</ul>
<p>SQL&gt; SET SERVEROUTPUT ON<br />
SQL&gt; SET ARRAYSIZE 1</p>
<div class="printfriendly alignleft"><a href="http://www.oratraining.com/blog/2009/06/sqlplus-basic-commands/?pfstyle=wp" rel="nofollow" ><img src="//cdn.printfriendly.com/pf-button-both.gif" alt="Print Friendly" /></a></div><div class="tweetthis" style="text-align:left;"><p> <a class="tt" href="http://twitter.com/intent/tweet?text=SQL%2APlus+Basic+commands+http%3A%2F%2Foratraining.com%2Fblog%2F%3Fp%3D174" title="Post to Twitter"><img class="nothumb" src="http://www.oratraining.com/blog/wp-content/plugins/tweet-this/icons/en/twitter/tt-twitter-big3.png" alt="Post to Twitter" /></a> <a class="tt" href="http://digg.com/submit?url=http://www.oratraining.com/blog/2009/06/sqlplus-basic-commands/&amp;title=SQL%2APlus+Basic+commands" title="Post to Digg"><img class="nothumb" src="http://www.oratraining.com/blog/wp-content/plugins/tweet-this/icons/en/digg/tt-digg-big4.png" alt="Post to Digg" /></a></p></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.oratraining.com%2Fblog%2F2009%2F06%2Fsqlplus-basic-commands%2F&amp;title=SQL%2APlus%20Basic%20commands" id="wpa2a_6"><img src="http://www.oratraining.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.oratraining.com/blog/2009/06/sqlplus-basic-commands/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

