<?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>OracleTuts</title>
	<atom:link href="http://oracletuts.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://oracletuts.net</link>
	<description>Oracle Training, Tutorials, and Videos from Beginner to Advanced</description>
	<lastBuildDate>Thu, 16 May 2013 16:10:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Commenting in PLSQL &#8211; Who Cares</title>
		<link>http://oracletuts.net/articles/best-practices/commenting-in-plsql-who-cares/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=commenting-in-plsql-who-cares</link>
		<comments>http://oracletuts.net/articles/best-practices/commenting-in-plsql-who-cares/#comments</comments>
		<pubDate>Tue, 07 May 2013 03:52:56 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[newbie]]></category>
		<category><![CDATA[plsql]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=2908</guid>
		<description><![CDATA[<p>In this article I will be discussing commenting in PLSQL, and if we really need to care about commenting our code or not. During my years as a PL/SQL developer, I have seen many types of comments, both good and bad. I will speak about some of the ways to comment that I have experienced. Ok, ...</p><p>The post <a href="http://oracletuts.net/articles/best-practices/commenting-in-plsql-who-cares/">Commenting in PLSQL &#8211; Who Cares</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>In this article I will be discussing <strong>commenting in PLSQL</strong>, and if we really need to care about commenting our code or not. During my years as a PL/SQL developer, I have seen many types of comments, both good and bad. I will speak about some of the ways to comment that I have experienced.</p>
<p><span id="more-2908"></span>Ok, let us pretend that you have gotten the task of creating a <strong>PL/SQL package</strong> that is going to be used by your whole team. How would you comment the code you are putting together? Or, would you care about commenting at all&#8230;?</p>
<p>&#8220;Well, my code looks pretty good, and I don&#8217;t feel I really need to comment anything&#8221;. Let me tell you something, from my own experience: If you are getting &#8220;old&#8221; (well 46 at least) like me, and you did something about six months ago, and you have done hundreds of little things between then and now&#8230;.you would wish you had some comments. That is exactly why I try to comment a lot in my code, so that I can get up-to-speed as fast as possible, if I am asked to run something I did a long time ago.</p>
<h2>Introduction</h2>
<p>I classify comments in five different categories:</p>
<div class="checklist">
<ul>
<li><span style="line-height: 13px;">Object header comments</span></li>
<li>POCEDURE and FUNCTION header comments</li>
<li>In-line comments</li>
<li>Code change comments</li>
<li>Divider comments</li>
</ul>
</div>
<p>Before I go on, you might already know, but just in case you do not &#8211; there are two ways to comment in PL/SQL:</p>
<pre class="brush: sql; gutter: true">--	This is a comment, on one line

/*	This is a multi-line comment,
	and it can just go on, and on
    ...even on multiple line.
*/</pre>
<p>The one-line comment comments everything on one line, that comes after the double hyphens.  The multi-line comment, comments everything between the start of the comment (&#8220;<strong>/*</strong>&#8220;), and the end of the comment (&#8220;<strong>*/</strong>&#8220;). I have to admit that I sometimes use the multi-line version, even if the comment is only on one line. And, sometimes you are actually forced to if i.e. your comment is in the middle area of your line.</p>
<p>Ok, let&#8217;s move on.</p>
<h2>Object header comments</h2>
<p>This is a comment that describes the object that the code is for. The object could be a stored procedure or function. It could also be a package in PL/SQL, and so on. Here is a sample of how I do my object header comments:</p>
<pre class="brush: sql; gutter: true">CREATE OR REPLACE PACKAGE otuts_lib IS

    ------------------------------------------------------------------------------------------
    --	Name				:	otlib.sql
    --  Script/package name	: 	otuts_lib
    --	Author				:	TJ Abrahamsen
    --	Copyright			:	OracleTuts	
    --	
    --	Project				:	OTUTS library
    --	Purpose				:	Library package of OracleTuts&#039; common utilities
    --	
    -- 	WHEN		WHO			WHAT		
    -- 	-----------	--------	-------------------------------------------------------
    -- 	5/6/2007	TEAB		Created		
    ------------------------------------------------------------------------------------------</pre>
<p>There are a couple of things to remark, when it comes to this kind of comments:</p>
<ol>
<li><span style="line-height: 13px;"><strong>Placement in file:</strong> If you always keep your latest code in a file, you might feel that the most logical placement for this kind of comment is in the top of your file. It would to me. Just remember, if you are working with a package, your code is stored in two parts: <em>PACKAGE</em> and <em>PACKAGE BODY</em>. When you compile your file, and look at your package code, you will find your header comments in the <em>PACKAGE</em> part, and not in the <em>PACKAGE BODY PART</em>. You will do most of your work in the <em>PACKAGE BODY</em>. Just something to consider.</span></li>
<li><strong>Placement inside code block:</strong> If you look at the sample above, you will see that I have put the commented lines <span style="text-decoration: underline;">below</span> the start of the PACKAGE block. If you code in your file all the time, and then compile it&#8230;any comments above the start of the block will disappear when you compile your file. So, it will not be seen when you look at your code using your favorite PL/SQL editor (like TOAD, PL/SQL Developer, Oracle SQL Developer, etc).</li>
</ol>
<p>My recommendation is to describe the content in the object (procedure, function, package, etc.)  as well as possible. At least you should have a WHEN, WHO, and WHAT section in your header comment.</p>
<p>I am fully aware of that things might be a little bit changed today, since we have so many ways to store our files&#8230;like in so many different types of repositories. We can i.e. use SubVersion, or maybe a company based GIT repository. Then we can comment every time we do a &#8220;commit&#8221; of changes to the repository, and even see a log of comments between versions&#8230;and even do a diff between two file versions.</p>
<p>Call me old-fashioned, but I actually like to see the comments in the file itself so that I can see the reasons for the different changes there.</p>
<h2>PROCEDURE and FUNCTION header comments</h2>
<p>Here I am not speaking about single stored procedures or functions, but rather the different functions and procedures within a package. OR, for procedures or functions you choose to put <span style="text-decoration: underline;">inside</span> your stored procedure or function.</p>
<p>The purpose of this type of comments would be to describe the usage of this procedure, it&#8217;s parameters, etc.</p>
<p>Here is a sample:</p>
<pre class="brush: sql; gutter: true">    /*	*****************************************************************************************
    	Obcject:	printAlign
        Type:		procedure
        Purpose:	This procedure is a wrapper procedure for dbms_output.put_line, and prints out
        			a variable with a set of fill characters, either on the left or right side of
                    the variable.

		PARAMETERS:	                    
    		pName:			Name of variable to print out
            pValue:			Value of the the variable to print out
            pMaxLength:		Max length of the whole print string, including two first parameters, 
            				as well as extra formatting characters
            pFillChar:		Character to be filled into &quot;empty spaces&quot;
            pShowLength:	Variable saying if we want to show the length of the variable value 
            				or not
    ***************************************************************************************** */

    PROCEDURE printAlign(	pName IN VARCHAR2,
    						pValue IN VARCHAR2,
                        	pMaxLength IN NUMBER,
                        	pFillChar IN VARCHAR2 DEFAULT &#039;-&#039;,
                        	pShowLength IN BOOLEAN DEFAULT FALSE)
    IS
    	vPrintString	VARCHAR2(200);
    BEGIN
    	vPrintString := &#039;[&#039; || RPAD(pName || &#039;]&#039;, pMaxLength + 3, pFillChar) || &#039;&gt;{&#039; || pValue || &#039;}&#039;;

        IF (pShowLength) THEN
        	vPrintString := vPrintString || &#039;(.&#039; || TO_CHAR(LENGTH(pValue)) || &#039;.)&#039;;
        END IF;

		dbms_output.put_line(vPrintString);
    END printAlign;</pre>
<p>The above is just an example. I usually do not use this type of comments very much. I prefer <strong>in-line commenting</strong>.</p>
<h2>In-line commenting</h2>
<p>This is the type of comments I definitely do most of. What I am speaking about here are comments that you can find anywhere in the code, and the main purpose is to help the reader of the code to understand some logic, the reason for calling a procedure, etc.</p>
<p>I classify these types of comments into:</p>
<div class="checklist">
<ul>
<li><span style="line-height: 13px;">Declaration comments</span></li>
<li>Code-helping comments</li>
</ul>
</div>
<h3>Declaration comments</h3>
<p>These are comments where I want to group different types of declarations in my code. They are found towards the top in my PL/SQL packages. Here are some samples:</p>
<pre class="brush: sql; gutter: true">CREATE OR REPLACE PACKAGE BODY otuts_lib IS

	----------------------------------------------------------------------------
	--  Private variables
	----------------------------------------------------------------------------

	tToken_tab	typToken_tab;
    nPos		NUMBER;

	----------------------------------------------------------------------------
	--  Private procedures/functions
	----------------------------------------------------------------------------

	FUNCTION ....
        ...
    ...

	PROCEDURE ....
        ...
    ...

	----------------------------------------------------------------------------
	--  Private procedures/functions
	----------------------------------------------------------------------------

	FUNCTION strTokenListCre(pLine IN VARCHAR2, pDelimiter IN VARCHAR2) RETURN typToken_tab IS
		sLine	VARCHAR2(2000);
    	nPos	INTEGER;
    	nPosOld	INTEGER;</pre>
<h3>Code-helping comments</h3>
<p>The main purpose of these types of comments is to help the reader of the code to understand what is going on. I usually try to group my code into logical groups, like shown below:</p>
<pre class="brush: sql; gutter: true">CREATE OR REPLACE PACKAGE BODY xxxx IS

	...

	PROCEDURE gen_customer_stats( xxx) IS
    BEGIN

		--	----------------------------------------------
		--	Generate current week data
		--	----------------------------------------------

        /* ENROLLMENT */
        &lt; some code &gt;

        /* COMMISSION */
        &lt; some code &gt;

        /* SALES */
        &lt; some code &gt;

		--	----------------------------------------------
		--	Generate previous weeks data
		--	----------------------------------------------

        /* ENROLLMENT */
        &lt; some code &gt;

        /* COMMISSION */
        &lt; some code &gt;

        /* SALES */
        &lt; some code &gt;

    END gen_customer_stats;

	...</pre>
<p>As you can see, I use a header with hyphens around for my &#8220;groups&#8221;. Then, I use a multi-line type of commenting on the different parts of the &#8220;group&#8221;. There are many ways you can organize this, but this is how I have done it for a while. I some times just use hyphens in front of the code &#8220;part&#8221;.</p>
<h2>Code change comments</h2>
<p>When writing this I was going back-and-forth in my head, whether I should put this under the &#8220;In-line commenting&#8221; section, or if I should dedicate a separate section for it. I feel that this was worth it&#8217;s own section.</p>
<p>Ok, if you put all your comments in your source-control repository, like SubVersion, GIT, CVS, etc&#8230;this might not be interesting to you, but I feel it is worth to mention.</p>
<p>Back in the end of the 90&#8242;s I used to work as a consultant for a company with several hundred employees. It was an international company, with offices many places around the world. They had an R&amp;D (Research and Development) department that had set up guidelines on how to do code changes. Below is a sample on how they did the commenting (or something similar at least):</p>
<pre class="brush: sql; gutter: true">...

nPos := 0;
sToken := &#039;&#039;;
nLength := LENGTH(sLine);
nCnt := 0;

FOR nIndex IN 1..nLength LOOP
    IF (SUBSTR(sLine, nIndex, 1) = pDelimiter) THEN
        nPosOld := nPos;
        nPos := nIndex;
        nCnt := nCnt + 1;
        -- 20130506, teab, ticket # 1234 - BEFORE:
        --sToken := SUBSTR(sLine, nPosOld + 1, nPos - 1);
        -- 20130506, teab, ticket # 1234 - AFTER:
        sToken := SUBSTR(sLine, nPosOld + 1, nPos - nPosOld - 1);
        -- 20130506, teab, ticket # 1234 - END:

        tToken_tab(nCnt).token_name := sToken;
    END IF;

END LOOP;

...</pre>
<p>I personally find this way of commenting code a bit&#8230;too much. I had to do some code changes in some of the PL/SQL code for the accounting module for the company mentioned above, and the code just got really messy. This, since there were so many customizations compared to the core version for the project I worked on. There might be a bit more cleaner ways to do this, but in general&#8230;I almost never comment like this.</p>
<h2>Divider comments</h2>
<p>The last type of comments I want to mention, is what I just call <em>divider comments</em>. These are comments I use to i.e. divide the different procedures and functions in a package, or between the package&#8217;s variable declaration area and where the procedure and function declarations start:</p>
<pre class="brush: sql; gutter: true">	...

	-- ## -----------------------------------------------------------------## --

	FUNCTION cfill(pNbrOfFillChars IN NUMBER, pFillChar IN NUMBER) RETURN VARCHAR2 IS
		vString		VARCHAR2(100);
    BEGIN
    	vString := &#039;&#039;;
    	FOR indx IN 1..pNbrOfFillChars LOOP
        	vString := vString || CHR(pFillChar);
        END LOOP;

        RETURN vString;
    END cfill;

	-- ## -----------------------------------------------------------------## --

	PROCEDURE pval(pNbrOfFillChars IN NUMBER, pFillChar IN NUMBER, pString IN VARCHAR2) IS
    BEGIN
    	dbms_output.put_line(cfill(pNbrOfFillChars, pFillChar) || pString);
    END pval;

	-- ## -----------------------------------------------------------------## --

	...</pre>
<p>I try to make these dividers searchable. That is the reason I use &#8220;##&#8221; in the comment. Then I can easily search to the next declaration part in a large package.</p>
<h2>Conclusion</h2>
<p>Well, as you can see, there are many different ways to do commenting in PLSQL code. And, as mentioned in this article, there are also different reasons to comment.</p>
<p>I hope you comment in your PL/SQL (or any other programming language) code. To me it is all about readability. Even if you don&#8217;t feel that you need any comments here and now, you might wish you had commented your advanced arbitrage (i.e.) package three years ago.</p>
<p>I hope you have gotten some input about commenting your PL/SQL code. If you enjoyed the article, please share it on your favorite social media channel. And, if you have any other suggestions, or comments: Use the comment section below.</p>
<p>The post <a href="http://oracletuts.net/articles/best-practices/commenting-in-plsql-who-cares/">Commenting in PLSQL &#8211; Who Cares</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/articles/best-practices/commenting-in-plsql-who-cares/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Formatting SQL &#8211; Best Practices</title>
		<link>http://oracletuts.net/articles/best-practices/formatting-sql-best-practices/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=formatting-sql-best-practices</link>
		<comments>http://oracletuts.net/articles/best-practices/formatting-sql-best-practices/#comments</comments>
		<pubDate>Tue, 30 Apr 2013 06:19:55 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[newbie]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=2814</guid>
		<description><![CDATA[<p>Having worked with SQL for so many years, I have definitely made up my mind about formatting SQL. I am a strong-minded person, and I have my own opinions. Most of these opinions are based on experience, but some of them are..maybe&#8230;just traditions&#8230;sometimes driving colleagues nuts. In this post a I am going to let you ...</p><p>The post <a href="http://oracletuts.net/articles/best-practices/formatting-sql-best-practices/">Formatting SQL &#8211; Best Practices</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Having worked with SQL for so many years, I have definitely made up my mind about <strong>formatting SQL</strong>. I am a strong-minded person, and I have my own opinions. Most of these opinions are based on experience, but some of them are..maybe&#8230;just traditions&#8230;sometimes driving colleagues nuts. <img src='http://cdn4.oracletuts.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /><br />
<span id="more-2814"></span></p>
<p>In this post a I am going to let you know a little bit how I do most of my SQL queries. Know, that most of this are things I have found helpful as..should we say&#8230;&#8221;standards&#8221; for how I do my SQLs. But, if you are pretty new to Oracle SQL, or any other kind of SQL, there should be some nice pointers for you here.</p>
<p>So, let&#8217;s get started!</p>
<h2>Editor Setup</h2>
<p>Before we get into the SQL specific formatting, I feel it is important to mention a little bit about how I set up any of my editors. After all, most of the formatting you do is usually set up in your editor. During my workday I actually use several types of editors:</p>
<div class="checklist">
<ul>
<li><span style="line-height: 13px;">Notepad++</span></li>
<li>Adobe Flash Builder (for my Flex projects)</li>
<li>PL/SQL Developer</li>
<li>And sometimes some others</li>
</ul>
</div>
<p>But, the common thing about all my editors, is that they are all set up the same way, even to the same colors some times.</p>
<p>In my opinion, setting up your <strong>SQL editor</strong> is one of the most important things you do. The reason is that you would want the formatting of your SQL to look the same, no matter what editor you view it in. If you in one editor use the tab character, and in another editor use some sort of &#8220;fill with spaces&#8221; functionality when you press the tab key&#8230;you might end up with some messy formatting.</p>
<p>So, that is why I try to do my best to do the same everywhere. But, enough talking &#8211; here are some of the things I <span style="text-decoration: underline;">always</span> set up. To be blunt, if an editor does not handle these settings, I choose another editor.</p>
<div class="checklist">
<ul>
<li><strong>Tab character:</strong> I always use the tab character. I never use &#8220;tab as spaces&#8221;. I also try to turn off any &#8220;smart fill&#8221; or &#8220;smart tab&#8221; settings. This way I can do a backspace, and it will outdent correctly, according to my <strong>tab size</strong>. I usually set my <strong>tab size</strong> to <strong>4</strong>. With 2, it does not look like it is really indented some times&#8230;</li>
<li><strong>Syntax Highlighting: </strong>Yes, definitely. My eyes is a little bit sensitive to bright light, so a white background is usually not that pleasant for my eyes after a while. I usually choose an editor that handles more than one <em>syntax highlighting schema</em>, or at least let you customize the settings for the default one. It is nice to see different colors on the various types of elements in your SQL statement. It makes it a lot better to read.</li>
<li><strong>Use of Uppercase:</strong> When I do any kind of SQL coding, I always like to set my editor up to do all the SQL keywords as uppercase. Let me look around to see if I see anyone from Oracle&#8230;just a sec&#8230;nope.. <span style="text-decoration: underline;">One</span> of the reasons I do NOT use Oracle&#8217;s SQL Developer is the way it handles uppercase on keywords. It looks like the conversion of the keywords to uppercase is not done until you press enter to go to the next line. To me that is a bit annoying some times. I feel that <em>PL/SQL Developer</em> from <em>Allround Automations</em> does way better job in this, and many other areas. Just my honest opinion.</li>
</ul>
</div>
<p>Ok, so let us look at some of the other things that I consider.</p>
<h2>Indentation and element placement</h2>
<p>Ok, although I spoke about indentation under the editor setup, I also wanted to mention WHAT I usually indent. Also, where do I put what? They say that a picture is worth 1,000 words, so here is a sample of something I usually do:<img class="aligncenter" alt="Formatted SQL Statement" src="http://cdn4.oracletuts.net/assets/2013/04/formatted-sql-statement.jpg" width="550" height="278" /></p>
<ol>
<li><strong>Keywords:</strong> They are always set up in my editor to be UPPERCASE. This has been a standard for me since I started with Oracle SQL and PL/SQL. If the editor does not make the key word with the right case, I sometimes make it uppercase myself&#8230; Yes, I am that picky.</li>
<li><strong>Indentation:</strong> All the vertical lines you see on the image above, are actually from my Notepad++ editor. It shows each of the &#8220;tab&#8221; stops in the code. As you can see, I always go to the next tabstop. What I mean is, when I have written the word &#8220;SELECT&#8221; I push the <em>tab</em> button. I almost never use a space, unless it is between two keywords, like between &#8220;YEAR FROM&#8221; on the above image.</li>
<li><strong>Aliases:</strong> For me it is important to use aliases in a helpful way. If you alias your tables &#8220;A&#8221;, &#8220;B&#8221;, &#8220;C&#8221;, etc&#8230;you will find that you end up having to look back to what you called &#8220;A&#8221;. I find it much better to alias my tables &#8220;ord&#8221; for <em>orders</em>, &#8220;cus&#8221; for <em>customer</em>, &#8220;inv&#8221; for <em>invoice</em>, etc.But, in the sample in the image above, you see that I use &#8220;x&#8221;, and &#8220;y&#8221; as aliases. I use these letters sometimes when I have to wrap a query around another query, as seen above.</li>
<li><strong>Parenthesis:</strong> I have been a software developer for about 25 years, so I know a lot about logical expressions. I try to use parenthesis everywhere there is any type of calculation, or expression.</li>
<li><strong>Commas:</strong> Ok, this is a place where I differ from many&#8230; I like the comma to be on the left side. The reason is that it is a lot easier to comment each of the lines in the SQL then.</li>
</ol>
<h2>ANSI SQL</h2>
<p>I will probably start a war on this one, but it has to be said. In any of my SQL statements, you will NEVER see any use of ANSI type of SQL. I have always worked in Oracle shops, so for me there is no need to use any:</p>
<pre class="brush: sql; gutter: true">SELECT	*
FROM	a
LEFT OUTER JOIN b ON (a.type = b.key)</pre>
<p>I am a (+) kind of guy:</p>
<pre class="brush: sql; gutter: true">SELECT	*
FROM	a
	,b
WHERE	a.type(+) = b.key</pre>
<p>Although Oracle has supported ANSI SQL for a while, I have never liked it, and to me it looks really messy. But, that is just my opinion.</p>
<p>Together with a colleague I had to go through a humongous SQL query from a SQL Server database, using T-SQL. We almost gave up when there were LEFT OUTER JOIN ON A&#8230;LEFT OUTER JOIN ON C&#8230;.LEFT OUTER JOIN ON D, etc, etc.</p>
<p>Nope, it is not for me.</p>
<h2>Visualize the result</h2>
<p>In addition to my own projects, where I use a lot of PL/SQL and SQL, I am sometimes asked by my company&#8217;s Business Analysts to validate their SQL, or any other way help them to solve any SQL task or project.</p>
<p>Since I consider myself as a visual learner, it is important to me to somehow visualize what the outcome of the SQL query will be. Usually I write down the columns of a piece of paper, on my white-board, or sometimes I have the Business Analyst provide me with an Excel spreadsheet &#8220;mock-up&#8221;.</p>
<p>Sometimes it is easier to &#8220;see&#8221; how to attack your SQL, when you know what the outcome is supposed to look like. Some times you know that you will end up with a large and complicated SQL statement, and you have no clue where to start. Visualizing it helps me.</p>
<h2>Step-by-step</h2>
<p>When you know you that you might end up with a large SQL statement, you don&#8217;t start from the top, and then write the code line for line. You start from the &#8220;inside&#8221;. Here are some steps that I follow:</p>
<ol>
<li><span style="line-height: 13px;"><strong>Driving table:</strong> In a more complex SQL statement task, you need to establish what I call the driving table. Let us say that you are going to get the orders for last week, then you are going to check the payments for those orders, and then lastly add some information about the customers on those orders. For me, the logical driving table would be the <em>orders</em> table.<br />
</span></li>
<li><strong>Additional tables:</strong> When I started with Oracle SQL, back in 1997, I learned that you should (in your FROM statement) start with your driving table, and then add tables to the <span style="text-decoration: underline;">left</span> of the driving table. Today the Oracle optimizer is very smart, so it probably does not matter anymore. But, I still practice this old-fashioned way of thinking. I put my next-to-driving table above my driving table, so basically if you put it on one line&#8230;it would be to the left of the driving table. Then, as I go on, I put additional tables above.</li>
<li><strong>The inner query:</strong> If you know that you are going to add a lot of customer information to your query, but your main query has some summarizations on the orders table, I would do the the summarization first. So you would i.e. select the customer id, from the orders table, and then do a GROUP BY on that field. Then I would wrap another query around the inner query.
<pre class="brush: sql; gutter: true">SELECT	x.customer_id
		,c.cust_first_name
        ,c.cust_last_name
        ,c.credit_limit
		,x.order_total
FROM	oe.customers c
		,(
            SELECT	o.customer_id
                    ,SUM(o.order_total) order_total
            FROM	oe.orders o
            GROUP BY o.customer_id
		) x
WHERE	c.customer_id = x.customer_id
;</pre>
<p>The reason I do this, is that I do not like to do a GROUP BY on more fields than I need to. Besides, it looks a lot cleaner to me.</li>
<li><strong>Repetive queries:</strong> Let us say that you are doing a query that is similar to the one shown under point # 3, and you a bit later (on a different level) in your query select the similar query, but for the same time period <span style="text-decoration: underline;">last</span> year. To me, a bell would ring, telling me to consider using a WITH statement. I will go through the WITH statement and it&#8217;s use in a future tutorial.</li>
<li><strong>Use of SELECT *:</strong> I never use SELECT * for any query that is going to be used in any analytic scenario. I always specify the names of the few fields I need going along. It would then be easier to avoid &#8220;duplicate column names&#8221;. What I mean, is that if you have a SELECT * on the <em>orders</em> table, joined with a SELECT * on the customers table, and then wrap a query around it.. If you then in your outer query &#8220;SELECT customer_id&#8230;&#8221;, you would probably get an error, since the pre-compiler would not know which of the customer_id fields you were speaking about.</li>
</ol>
<h2>SQL Formatters</h2>
<p>What do you do if you have an editor that does not format your SQL query very well? There are many free SQL Formatters available on the Internet. Here are a few examples:</p>
<div class="checklist">
<ul>
<li><a title="Instant SQL Formatter" href="http://www.dpriver.com/pp/sqlformat.htm" target="_blank"><span style="text-decoration: underline;">Instant SQL Formatter</span></a></li>
<li><a title="SQL Format - Online SQL Formatter" href="http://sqlformat.appspot.com/" target="_blank"><span style="text-decoration: underline;">SQL Format &#8211; Online SQL Formatter</span></a></li>
<li><a title="Redgate Format SQL" href="http://format-sql.com/" target="_blank"><span style="text-decoration: underline;">Redgate Format SQL</span></a></li>
<li><a title="SQLInform" href="http://www.sqlinform.com/free_online_sw.html" target="_blank"><span style="text-decoration: underline;">SQLInform</span></a></li>
<li><a title="Devart Online SQL Formatter" href="http://www.sql-format.com/" target="_blank"><span style="text-decoration: underline;">Devart Online SQL Formatter</span></a></li>
</ul>
</div>
<p>But, these online tools would just be a backup solution for me. To me it is important to have tool available that do all the formatting you need for your SQL statements. The tool I have been using since I started as an Oracle developer, is <em>PL/SQL Developer</em> from <a title="Allround Automations" href="http://www.allroundautomations.com/" target="_blank"><span style="text-decoration: underline;"><em>Allround Automations</em></span></a>.  PL/SQL Developer has an awesome feature, called &#8220;<em>PL/SQL Beautifier</em>&#8220;. You can set up your own rules on how you want your SQL query to look. So, if you get a query from some old view in the database, that looks totally messed up, you can mark the query and &#8220;beautify&#8221; it, based on your own rules. It can come in really handy. Here is a screenshot:</p>
<p><img class="aligncenter size-full wp-image-2883" alt="PLSQL Developer Beautifier" src="http://cdn.oracletuts.net/assets/2013/04/plsql-developer-beautifier.jpg" width="550" height="476" /></p>
<p>You can order PL/SQL Developer by clicking on the green button:</p>
<a href=" http://oracletuts.net/go/plsqldeveloper/" target="_blank" class="button small green ">Order PL/SQL Developer *</a>
<p>* Affiliate link. For other license options than &#8220;<em>single user</em>&#8220;, please contact me through the contact page on my blog.</p>
<h2>Conclusion</h2>
<p>To me, writing a SQL statement can sometimes be like a piece of &#8220;art&#8221;&#8230; <a href="http://oracletuts.net/go/plsqldeveloper/"><img class="alignright size-full wp-image-2886" alt="PL/SQL Developer" src="http://cdn2.oracletuts.net/assets/2013/04/plsql-developer-2.jpg" width="189" height="190" /></a>It is all about  the &#8220;looks&#8221; and readability. Not just for you, but for anyone that looks at your SQL code.</p>
<p>Now, if you get your whole team to follow the same standards&#8230;life is just golden! But, sometimes there are people in your team that have different experiences than you, and you might not be able to nail your your &#8220;law&#8221; to the wall as something everyone has to follow.</p>
<p>Based on experience working in large teams, the best thing is to come up with some common ground, and write down a short document that everyone agrees upon. I have even worked for a large company with it&#8217;s own R&amp;D (Research and Development) team, setting all the standards for the whole company.</p>
<p>After reading all this, you might think &#8220;he&#8217;s just crazy picky&#8221;, or something. But, all these things are just &#8220;there&#8221; in my fingers, and in my head when I code SQL statements.</p>
<p>I hope this post has been of value to you. As always: &#8220;<em>Sharing is caring</em>&#8220;.</p>
<p>Also, if you have any thoughts, or other ideas&#8230;let us all know by leaving a comment.</p>
<p>~ TJ</p>
<p>The post <a href="http://oracletuts.net/articles/best-practices/formatting-sql-best-practices/">Formatting SQL &#8211; Best Practices</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/articles/best-practices/formatting-sql-best-practices/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>11 Ways to Increase Your Oracle Skills</title>
		<link>http://oracletuts.net/articles/skills/11-ways-to-increase-your-oracle-skills/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=11-ways-to-increase-your-oracle-skills</link>
		<comments>http://oracletuts.net/articles/skills/11-ways-to-increase-your-oracle-skills/#comments</comments>
		<pubDate>Sun, 21 Apr 2013 13:41:35 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[Skills]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[newbie]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=2655</guid>
		<description><![CDATA[<p>Being totally fresh and new as any kind of developer can be pretty tough sometimes. Maybe you were just hired by a company and they promised you that they would teach you everything you need to know? Let me tell you something&#8230; The life in an IT department is very often a very hectic life, and things ...</p><p>The post <a href="http://oracletuts.net/articles/skills/11-ways-to-increase-your-oracle-skills/">11 Ways to Increase Your Oracle Skills</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Being totally fresh and new as any kind of developer can be pretty tough sometimes. Maybe you were just hired by a company and they promised you that they would teach you everything you need to know? Let me tell you something&#8230; The life in an IT department is very often a very hectic life, and things do not always turn out like planned.</p>
<p>You might not get that kick-start of your knowledge base like you were expecting, because your team has a big delivery next month, and no-one really has time to sit down with you. But, at the same time, YOU are expected to come up-to-speed so that you can help to pull some of the weight in your team.</p>
<p>This is a very typical situation for many new developers, and in this article I wanted to tell you about <strong>11 ways to increase your Oracle skills</strong>. But, of course, you can use these 11 ways as any type of developer.</p>
<p><span id="more-2655"></span></p>
<ol>
<li>Classes (off site, virtual)</li>
<li>In-house classes</li>
<li>On site classes</li>
<li>Learn from others in your team</li>
<li>Forums</li>
<li>Books</li>
<li>Videos</li>
<li>Oracle User groups</li>
<li>Libraries</li>
<li>Learn by example</li>
<li>Blogs and Websites</li>
</ol>
<p>Below, I have divided these 11 ways to increase skills into two groups:<br />
<div class="checklist">
<ul>
<li>Taught by others</li>
<li>Self Learning</li>
</ul>
</div>
<h1>Taught by others</h1>
<h2>1. Classes (on site, virtual)</h2>
<p>One of the most common ways, for at least larger companies, to educate new developers is to send the newbie to a place where they give classes in what your are supposed to become an expert in. There are many companies that specializes in Oracle training, and you can search the Internet for these companies. Another variant that I like very much, is the &#8220;virtual class&#8221; type of courses. I am a &#8220;home-body&#8221;, and I do not care much for traveling, so I prefer sitting in my private office at home, and take a virtual class instead of going to a hotel for a few days. That is just me&#8230;</p>
<p>The virtual classes are usually organized so that you have an instructor that shares his/her computer screen, and all participants call a number so that you can all be part of the class, and ask questions to the instructor.</p>
<p>If you do not have your own home office, maybe you can schedule one of your company&#8217;s meeting rooms for a few days so that you can get some peace and quiet?</p>
<h2>2. In-house classes</h2>
<p>Depending on the work load in your team, or company, a very nice way yo learn is in-house classes. This is a class where people from your company come together, and one of your company&#8217;s knowledgeable people gives a class on a topic. This might often work very well, since you all belong to the same company, and the instructor will be able to help you more when you have questions on matters that are based on some of the rules and regulations of the company, guidelines for developers in your company, etc.</p>
<p>Currently I am actually giving SQL classes to some of my colleagues, and it can be a very nice way to learn.</p>
<h2>3. On site courses</h2>
<p>A way used by some companies, is to gather some of the developers, and then have the company pay for an instructor to come to YOU. So, it is basically the same as the first, but instead of YOU traveling, the instructor is traveling.</p>
<p>One of the nice things about using this way of classes, is that the instructor can be told up front specific topics that needs to be covered more deeply, etc.</p>
<h2>4. Learn from others in your team</h2>
<p>Well, as I mentioned in the beginning of this article, the IT department can be a hectic place sometimes, and it is not always time for someone in your team to sit down with you to teach you. And, I am sorry&#8230;but humans are just&#8230;humans, so psychologically,  the person set to teach you might not even WANT the task of teaching you, or he/she will look at you as a &#8220;lesser worth&#8221; person because you know so little. I migth be weird to say this, but there are too many examples in an IT department of these situations, so I felt I needed to mention this.</p>
<p>So, if you get the right person in your team to teach you, this can be an awesome experience.</p>
<p>Another issue, you might call it, is that even if you are lucky to get a good experience with being taught by a colleague, it can start out well, but after a couple of weeks the trainer/colleague is pulled into a big project, and you are left by yourself again.</p>
<h1>Self Learning</h1>
<p>Ok, now we are getting into my favorite ways to increase skills. At the time of writing this article, I have worked as a software developer for almost 25(!) years. The best way for me, personally, is to teach myself. This way I can teach myself on only the topics that matters.</p>
<p>Here are some of the ways I use all the time as a software developer.</p>
<h2>5. Forums</h2>
<p>There are many good Oracle forums out there, and here are few examples:</p>
<div class="checklist">
<ul>
<li><span style="text-decoration: underline;"><a title="The Oracle Technology Network Forum" href="https://forums.oracle.com/" target="_blank">The Oracle Technology Network Forum</a></span></li>
<li><span style="text-decoration: underline;"><a title="Oracle FAQ's" href="http://www.orafaq.com/forum/" target="_blank">Oracle FAQ&#8217;s</a></span></li>
<li><span style="text-decoration: underline;"><a title="dbforums for Oracle" href="http://www.dbforums.com/oracle/" target="_blank">dbforums for Oracle</a></span></li>
</ul>
</div>
<h2>6. Books</h2>
<p>There are definitively a lot of Oracle books available. You can find most of them at Amazon. A nice thing about many books, is that they come in .PDF format. That makes it so that you can have it on the computer, and search for words in the books, etc. In addition, with a .PDF book, you can have it on your iPad, if you have one.</p>
<h2>7. Videos</h2>
<p>If you have something you want to know about as an Oracle developer, a nice way to learn is to i.e. go to Google, and search for videos on a certain topic, or even beginner tutorials. You can use this <span style="text-decoration: underline;"><a title="Google Video Search" href="http://www.google.com/videohp" target="_blank">link</a></span>.</p>
<h2>8. Oracle User groups</h2>
<p>In most areas of  the world, you will be able to find Oracle User Groups. Search for them in your favorite search engine, and see if there is one close to you. Also, a lot of the bigger Oracle User Groups have their own website, that you can find i.e. by using Google.</p>
<h2>9. Libraries</h2>
<p>Ok, I am not speaking about the public library, with all them books. I am speaking about websites made as a &#8220;library&#8221; to help people that search for how to use a function, how to use a command, how to write a certain type of SQL statement, etc.</p>
<p>Here are a couple of them:</p>
<div class="starlist">
<ul>
<li><span style="text-decoration: underline;"><a title="Morgan's Library" href="http://www.morganslibrary.com/" target="_blank">Morgan&#8217;s Library</a></span></li>
<li><span style="text-decoration: underline;"><a title="Tech on the Net" href="http://www.techonthenet.com/oracle/" target="_blank">Tech on the Net</a></span></li>
</ul>
</div>
<p>You can search the Internet for many more of them.</p>
<h2>10. Learn by example</h2>
<p>This is something I like personally. Many a time I have learned how to do something by looking at other developer&#8217;s code. Like, if you are working in a team with many other developers, you will have a database where all the procedures, functions, and packages are residing. Browse through them, and see how things are being done.</p>
<p>In the latest years, a very often used way to store code files is by using web based code repositories, like GIT, etc. Many companies have these installed internally. You can ask to get access to these repositories, and look through some of the code.</p>
<h2>11. Blogs and Websites</h2>
<p>Well, I would hope you use OracleTuts, but there are a lot of blogs about Oracle on the Internet. I will leave up to you to do the search. But, a very well known one is the &#8220;<a title="Ask Tom" href="http://asktom.oracle.com" target="_blank">Ask Tom</a>&#8221; website, which is a part of Oracle&#8217;s website, and the &#8220;Tom&#8221; we are speaking about is the well know Oracle personality Tom Kyte.</p>
<p>&nbsp;</p>
<h1>Conclusion</h1>
<p>I am a very blessed person, in many ways. And, one of the ways is that I have a beautiful wife that I love very much. On of the ways I am very different than my wife, is in studying. My wife likes to read the whole book, but I prefer to look at the few paragraphs that solve my problem. The main difference might be that I am a technical person, and my beauty is not. Also, my wife likes to learn about many different things, but I like to be topic-oriented.</p>
<p>There are many different ways to learn, but if you want to go the &#8220;self-taught&#8221; way like I have, I would encourage you to specify the issue you have, or define exactly what you want to learn about, and then learn about it. Like I do:</p>
<p>I have a task, I get an issue, I look on the Internet how to solve it, and then I solve it. Short and sweet.</p>
<p>Well, that was the end of this article. I hope you have enjoyed it, and have learned form it. Please do not hesitate on leaving a comment, and if I have forgotten something, please put your way to learn in the comments section below.</p>
<p>And, as always, sharing is caring. <img src='http://cdn4.oracletuts.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>The post <a href="http://oracletuts.net/articles/skills/11-ways-to-increase-your-oracle-skills/">11 Ways to Increase Your Oracle Skills</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/articles/skills/11-ways-to-increase-your-oracle-skills/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Perform A Text Import With PL/SQL Developer</title>
		<link>http://oracletuts.net/tutorials/how-to-perform-a-text-import-with-plsql-developer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-perform-a-text-import-with-plsql-developer</link>
		<comments>http://oracletuts.net/tutorials/how-to-perform-a-text-import-with-plsql-developer/#comments</comments>
		<pubDate>Sun, 07 Apr 2013 08:47:15 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Videos]]></category>
		<category><![CDATA[import]]></category>
		<category><![CDATA[plsql developer]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=2576</guid>
		<description><![CDATA[<p>In this video I will show you how you can use PL/SQL Developer from Allround Automations to import a text file, in my case a .CSV file into a simple table. This tool can be used for many types of data imports into an Oracle table. Introduction Working with Oracle SQL and PL/SQL since 1997, ...</p><p>The post <a href="http://oracletuts.net/tutorials/how-to-perform-a-text-import-with-plsql-developer/">How To Perform A Text Import With PL/SQL Developer</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>In this video I will show you how you can use <strong>PL/SQL Developer</strong> from <strong>Allround Automations</strong> to <strong>import a text file</strong>, in my case a .CSV file into a simple table.</p>
<p>This tool can be used for many types of data imports into an Oracle table.</p>
<p style="text-align: center;"><span id="more-2576"></span><span>
			</span>
<h1 style="clear: left;">Introduction</h1>
<p>Working with Oracle <strong>SQL</strong> and <strong>PL/SQL</strong> since 1997, I have done a LOT of <strong>text import</strong> of data. Usually what I have done is to open i.e. a .CSV file in Excel, and add columns, so that when I save the file back to the .CSV file again, it creates a series of <em>INSERT INTO</em> statements. This way of preparing the data, and then import the data is just time consuming. There is a much better way.</p>
<div class="box info"><div>
			UPDATE 4/9/2013: Hey guys, TJ here. I had to import some data from Excel via a .CSV file myself today, and had some struggles. Everything ended up on ONE line under the &#8220;File Data&#8221; part. The reason ended up being that I had to save the .CSV as a file using Unix type of EOL characters. Solved this by opening the file in Notepad++, change the EOL format, and then save it.
			</div></div>
<h1>In this video we will</h1>
<ol>
<li>Create a table named &#8220;customer&#8221;</li>
<li>Import a .CSV text file into the table</li>
<li>Select from the &#8220;customer&#8221; table</li>
</ol>
<p>Very simple, this tool is just awesome.</p>
<p>If you have any other experiences with this text import tool, please leave a comment so that we all can know a bout it.</p>
<p>~ TJ</p>
<p>The post <a href="http://oracletuts.net/tutorials/how-to-perform-a-text-import-with-plsql-developer/">How To Perform A Text Import With PL/SQL Developer</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/tutorials/how-to-perform-a-text-import-with-plsql-developer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Welcome to OracleTuts!</title>
		<link>http://oracletuts.net/news/welcome-to-oracletuts/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=welcome-to-oracletuts</link>
		<comments>http://oracletuts.net/news/welcome-to-oracletuts/#comments</comments>
		<pubDate>Tue, 02 Apr 2013 06:41:31 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Videos]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[oracletuts]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=2545</guid>
		<description><![CDATA[<p>OracleTuts.net has been around for a while. In this video I thought I should present myself, and tell you a little bit about myself, and my experience with Oracle. Hey everyone! I am TJ Abrahamsen, the creator and owner of OracleTuts.net. I have been working full-time with Oracle SQL and PL/SQL since 1997. My specialty ...</p><p>The post <a href="http://oracletuts.net/news/welcome-to-oracletuts/">Welcome to OracleTuts!</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>OracleTuts.net has been around for a while. In this video I thought I should present myself, and tell you a little bit about myself, and my experience with Oracle.<br />
<span id="more-2545"></span></p>
<span>
			</span>
<p>Hey everyone!</p>
<p>I am TJ Abrahamsen, the creator and owner of OracleTuts.net. I have been working full-time with Oracle SQL and PL/SQL since 1997. My specialty is Oracle SQL and PL/SQL.</p>
<p>OracleTuts.net was created to share my experience with Oracle SQL and PL/SQL. My goal with the site is to help you to become experienced within these topics as well, if you are not already.</p>
<p>I really hope you enjoy my site, and that you will leave a comment if you like the content on OracleTuts.net.</p>
<p>Enjoy the site!</p>
<p>~ TJ</p>
<p>The post <a href="http://oracletuts.net/news/welcome-to-oracletuts/">Welcome to OracleTuts!</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/news/welcome-to-oracletuts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Change Background Color in Oracle SQL Developer</title>
		<link>http://oracletuts.net/tutorials/how-to-change-background-color-in-oracle-sql-developer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-change-background-color-in-oracle-sql-developer</link>
		<comments>http://oracletuts.net/tutorials/how-to-change-background-color-in-oracle-sql-developer/#comments</comments>
		<pubDate>Sat, 16 Mar 2013 00:09:17 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Videos]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=2474</guid>
		<description><![CDATA[<p>This video will guide you through the steps needed to change the background color in Oracle SQL Developer. It will help you if you are tired of looking at the bright background the whole day long. Introduction The default setup in SQL Developer has the plain white background. If you are a developer like me, ...</p><p>The post <a href="http://oracletuts.net/tutorials/how-to-change-background-color-in-oracle-sql-developer/">How to Change Background Color in Oracle SQL Developer</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>This video will guide you through the steps needed to change the background color in Oracle SQL Developer. It will help you if you are tired of looking at the bright background the whole day long.<br />
<span id="more-2474"></span></p>
<span>
			</span>
<h1 style="clear: left;">Introduction</h1>
<p>The default setup in SQL Developer has the plain white background. If you are a developer like me, and look at the screen all day long&#8230;you might want to consider changing the background color to a little bit darker setting to save your eyes a bit.</p>
<h1>In this video we will</h1>
<ol>
<li>Extract the default Fusion Blue jar file into a temporary folder</li>
<li>Change some of the content in the copied jar file</li>
<li>Compress our changed content, to a new jar file</li>
<li>Copy the new jar file to the theme folder</li>
<li>Change a setting inside SQL Developer</li>
<li>Restart SQL Developer</li>
</ol>
<p>The post <a href="http://oracletuts.net/tutorials/how-to-change-background-color-in-oracle-sql-developer/">How to Change Background Color in Oracle SQL Developer</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/tutorials/how-to-change-background-color-in-oracle-sql-developer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Transpose Columns To Rows In Oracle</title>
		<link>http://oracletuts.net/tutorials/how-to-transpose-columns-to-rows-in-oracle/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-transpose-columns-to-rows-in-oracle</link>
		<comments>http://oracletuts.net/tutorials/how-to-transpose-columns-to-rows-in-oracle/#comments</comments>
		<pubDate>Tue, 12 Mar 2013 15:46:34 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[operator]]></category>
		<category><![CDATA[oracle how to]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=2435</guid>
		<description><![CDATA[<p>In this little tutorial, I will show you how you can transpose columns into rows in Oracle, using SQL. This post is a follow-up of a post where I showed how to transpose rows into columns. Introduction A while ago I wrote a tutorial on how to transpose rows to columns using Oracle SQL. You ...</p><p>The post <a href="http://oracletuts.net/tutorials/how-to-transpose-columns-to-rows-in-oracle/">How To Transpose Columns To Rows In Oracle</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>In this little tutorial, I will show you how you can <strong>transpose columns into rows in Oracle</strong>, using SQL. This post is a follow-up of a post where I showed how to <strong>transpose rows into columns</strong>.</p>
<p><span id="more-2435"></span></p>
<span>
			</span>
<h1>Introduction</h1>
<p>A while ago I wrote a tutorial on how to t<strong>ranspose rows to columns</strong> using Oracle SQL. You can find the tutorial here: <a title="Three Ways To Transpose Rows Into Columns in Oracle SQL" href="http://oracletuts.net/tutorials/three-ways-to-transpose-rows-into-columns-in-oracle-sql/">Three Ways To Transpose Rows Into Columns in Oracle SQL</a></p>
<p>Many people would like to know how to do it the opposite way, <strong>transpose columns to rows</strong>, as well. So, here is a tutorial that shows a couple of ways you can do this.</p>
<h1>Examples</h1>
<p>In the tutorial we will pretend we have a survey table where the people taking the survey have filled out a form about what health concerns they have. Yes for a concern will be &#8220;1&#8243; in the table, and No will be &#8220;0&#8243; in the table.</p>
<p>We have the following records in the table:</p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	*
  2  FROM	survey
  3  /

                              SURVEY_ID CONCERN_EYE CONCERN_VISION CONCERN_BRAIN CONCERN_LUNG CONCERN_HIP
--------------------------------------- ----------- -------------- ------------- ------------ -----------
                                    123 0           0              1             0            1
                                    321 1           1              0             0            0
                                    456 0           0              0             0            0
                                    654 1           1              0             1            1
                                    789 0           1              0             0            0
                                    987 0           0              0             0            1

6 rows selected</pre>
<p>For one of our company&#8217;s reports, we need to come up with a SQL query where the columns are represented as rows &#8211; meaning that we have transposed the columns to rows.</p>
<h1>Example # 1: Using the UNION operator</h1>
<p>In this sample, we will solve the task simply by using several <strong>UNION</strong> statements. Our end result should be a resultset with 30 records. The reason for this is that we have six (6) unique ids, and we have five (5) columns for each of the ids. And&#8230; 6 x 5 = 30 <img src='http://cdn4.oracletuts.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<pre class="brush: sql; gutter: true">SQL&gt; WITH survey_query AS	(
  2                              SELECT	*
  3                              FROM	survey s
  4                          )
  5  SELECT	sq.survey_id
  6          ,&#039;EYE&#039; concern_type
  7          ,sq.concern_eye concern_flag
  8  FROM	survey_query sq
  9  UNION
 10  SELECT	sq.survey_id
 11          ,&#039;VISION&#039; concern_type
 12          ,sq.concern_vision concern_flag
 13  FROM	survey_query sq
 14  UNION
 15  SELECT	sq.survey_id
 16          ,&#039;BRAIN&#039; concern_type
 17          ,sq.concern_brain concern_flag
 18  FROM	survey_query sq
 19  UNION
 20  SELECT	sq.survey_id
 21          ,&#039;LUNG&#039; concern_type
 22          ,sq.concern_lung concern_flag
 23  FROM	survey_query sq
 24  UNION
 25  SELECT	sq.survey_id
 26          ,&#039;HIP&#039; concern_type
 27          ,sq.concern_hip concern_flag
 28  FROM	survey_query sq
 29  /

                              SURVEY_ID CONCERN_TYPE CONCERN_FLAG
--------------------------------------- ------------ ------------
                                    123 BRAIN        1
                                    123 EYE          0
                                    123 HIP          1
                                    123 LUNG         0
                                    123 VISION       0
                                    321 BRAIN        0
                                    321 EYE          1
                                    321 HIP          0
                                    321 LUNG         0
                                    321 VISION       1
                                    456 BRAIN        0
                                    456 EYE          0
                                    456 HIP          0
                                    456 LUNG         0
                                    456 VISION       0
                                    654 BRAIN        0
                                    654 EYE          1
                                    654 HIP          1
                                    654 LUNG         1
                                    654 VISION       1
                                    789 BRAIN        0
                                    789 EYE          0
                                    789 HIP          0
                                    789 LUNG         0
                                    789 VISION       1
                                    987 BRAIN        0
                                    987 EYE          0
                                    987 HIP          1
                                    987 LUNG         0
                                    987 VISION       0

30 rows selected</pre>
<p>As you can see, we got our 30 records. Also, note that I used a <strong>WITH statement</strong> for my main query. This is because I want to make sure that my query does not pull data from the survey table five times, but only once.</p>
<div class="boxshadow"><div>
			Note: Based on your data, you might want to consider using <strong>UNION ALL</strong> rather than <strong>UNION</strong>, whatever gives you the correct result.
			</div></div>
<h1>Example # 2: Using the UNPIVOT operator</h1>
<p>If you have a database with Oracle database version 11g or later, you might consider using the <strong>UNPIVOT operator</strong> to solve your task.</p>
<p>Here is a sample:</p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	survey_id
  2  		,concern_type
  3          ,concern_flag
  4  FROM	survey
  5  UNPIVOT (	concern_flag FOR concern_type IN (
  6  				concern_eye AS &#039;EYE&#039;
  7                  ,concern_vision AS &#039;VISION&#039;
  8                  ,concern_brain AS &#039;BRAIN&#039;
  9                  ,concern_lung AS &#039;LUNG&#039;
 10                  ,concern_hip AS &#039;HIP&#039;)
 11  		)
 12  /

                              SURVEY_ID CONCERN_TYPE CONCERN_FLAG
--------------------------------------- ------------ ------------
                                    123 EYE          0
                                    123 VISION       0
                                    123 BRAIN        1
                                    123 LUNG         0
                                    123 HIP          1
                                    321 EYE          1
                                    321 VISION       1
                                    321 BRAIN        0
                                    321 LUNG         0
                                    321 HIP          0
                                    456 EYE          0
                                    456 VISION       0
                                    456 BRAIN        0
                                    456 LUNG         0
                                    456 HIP          0
                                    654 EYE          1
                                    654 VISION       1
                                    654 BRAIN        0
                                    654 LUNG         1
                                    654 HIP          1
                                    789 EYE          0
                                    789 VISION       1
                                    789 BRAIN        0
                                    789 LUNG         0
                                    789 HIP          0
                                    987 EYE          0
                                    987 VISION       0
                                    987 BRAIN        0
                                    987 LUNG         0
                                    987 HIP          1

30 rows selected</pre>
<p>As you can see, we have the same amount of records.</p>
<p>In the query above, the &#8220;<em>concern_type&#8221;</em> and the &#8220;<em>concern_flag</em>&#8221; fields can be named anything.</p>
<div class="box info"><div>
			
<p>NOTE: If you choose to use the <strong>UNPIVOT operator</strong> &#8211; you need to be aware that if you are using an alias on your table, you might getting error messages. A query using <strong>UNPIVOT</strong> does not seem to like aliases very well.</p>
<p>Also, in the above query, you see that I use i.e. <em>concern_eye AS &#8216;EYE&#8217;</em>. This is a way that the aliasing works, so try to be careful.</p>

			</div></div>
<h1>Conclusion</h1>
<p>Ok, so we have seen two different ways to transpose columns into rows in Oracle, using SQL. The first example might be a good way, but it requires a little bit more code.</p>
<p>The second example, using <strong>UNPIVOT</strong>, is a good way to go if your database version is 11g or newer. There are though a few things to be aware of using the <strong>UNPIVOT operator</strong>, especially when using aliases.</p>
<p>I hope this has been helpful for you. If you liked this post, please share this post with others <img src='http://cdn4.oracletuts.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>~ TJ</p>
<p>The post <a href="http://oracletuts.net/tutorials/how-to-transpose-columns-to-rows-in-oracle/">How To Transpose Columns To Rows In Oracle</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/tutorials/how-to-transpose-columns-to-rows-in-oracle/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Oracle PLSQL and SQL Blog Posts From Around the Web (10/2013)</title>
		<link>http://oracletuts.net/news/oracle-plsql-and-sql-blog-posts-from-around-the-web-102013/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=oracle-plsql-and-sql-blog-posts-from-around-the-web-102013</link>
		<comments>http://oracletuts.net/news/oracle-plsql-and-sql-blog-posts-from-around-the-web-102013/#comments</comments>
		<pubDate>Wed, 06 Mar 2013 12:08:23 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[weekly news]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=530</guid>
		<description><![CDATA[<p>Here are some interesting Oracle PLSQL and SQL Blog Posts that we found during week 10 of 2013: Top 10 Tips &#38; Tricks for Oracle SQL Developer Oracle Magazine 15 Things You Should Know about the ORDER BY Clause Oracle FAQ&#8217;s Morgan&#8217;s Library &#160; Top 10 Tips &#38; Tricks for Oracle SQL Developer By Jeff Smith ...</p><p>The post <a href="http://oracletuts.net/news/oracle-plsql-and-sql-blog-posts-from-around-the-web-102013/">Oracle PLSQL and SQL Blog Posts From Around the Web (10/2013)</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Here are some interesting Oracle PLSQL and SQL Blog Posts that we found during week 10 of 2013:</p>
<ul>
<li>Top 10 Tips &amp; Tricks for Oracle SQL Developer</li>
<li>Oracle Magazine</li>
<li>15 Things You Should Know about the ORDER BY Clause</li>
<li>Oracle FAQ&#8217;s</li>
<li>Morgan&#8217;s Library</li>
</ul>
<p><span id="more-530"></span></p>
<span>
			</span>
<p>&nbsp;</p>
<h3><a title="Top 10 Tips &amp; Tricks for Oracle SQL Developer" href="http://www.thatjeffsmith.com/archive/2012/07/top-10-tips-tricks-for-oracle-sql-developer/">Top 10 Tips &amp; Tricks for Oracle SQL Developer</a></h3>
<p>By <a title="Jeff Smith" href="http://www.thatjeffsmith.com/about/">Jeff Smith</a></p>
<blockquote><p>I’ve been sharing 1-3 tips or ‘tricks’ a week since I started blogging about SQL Developer, and I have more than enough content to write a book. But since I’m lazy, I’m just going to compile a list of my favorite ‘must know’ tips instead. I always have to leave out a few tips when I do my presentations, so now I can refer back to this list to make sure I’m not forgetting anything.</p></blockquote>
<p><a title="Top 10 Tips &amp; Tricks for Oracle SQL Developer" href="http://www.thatjeffsmith.com/archive/2012/07/top-10-tips-tricks-for-oracle-sql-developer/">Read the complete post here &#8230;</a></p>
<h3><a title="Oracle Magazine Online" href="http://www.oracle.com/technetwork/oramag/magazine/home/index.html">Oracle Magazine Online</a></h3>
<p>By <a title="Oracle Corporation" href="http://oracle.com">Oracle</a></p>
<p>I have been receiving the Oracle Magazine for a while, and love it. I used to get it in printed format, but these days I receive it in an electronic format, for online reading. If you do not already subscribe to Oracle Magazine, I would definitely suggest that you check it out. It has a lot of news about Oracle. And, Steven Feuerstein usually have an awesome section on PL/SQL. Lately he has been speaking about PL/SQL Cursors.</p>
<p><a title="Check it out here" href="http://www.oracle.com/technetwork/oramag/magazine/home/index.html">Check it out here</a></p>
<h3><a title="15 Things You Should Know about the ORDER BY Clause" href="http://www.oratable.com/oracle-order-by-clause/">15 Things You Should Know about the ORDER BY Clause</a></h3>
<p>By <a title="Oratable About" href="http://www.oratable.com/about/">Oratable</a></p>
<ol>
<li>
<blockquote><p>When multiple columns/expressions are specified in the ORDER BY clause, the precedence of sorting is <strong>left to right</strong>.</p></blockquote>
</li>
<li>
<blockquote><p>The ORDER BY clause can order in ascending (ASC) or descending (DESC) sequence, or a mix of both. If <strong>ASC</strong> or <strong>DESC</strong> is not explicitly stated, then ASC is the default.</p></blockquote>
</li>
<li></li>
</ol>
<p><a title="15 Things You Should Know about the ORDER BY Clause" href="http://www.oratable.com/oracle-order-by-clause/">Read the complete post here &#8230;</a></p>
<h3><a title="Oracle FAQ's" href="http://www.orafaq.com/">Oracle FAQ&#8217;s</a></h3>
<p>By <a title="Oracle FAQ About" href="http://www.orafaq.com/about">Oracle FAQ</a></p>
<blockquote><p>The Oracle FAQ is NOT an official Oracle Support site, but rather a get-together of people with jobs in Oracle. In our spare time we come together here to learn about Oracle, share knowledge and try to help others solve their problems. In doing so, this sites puts a wealth of information at the fingertips of Oracle professionals all over the world. You can use our directories and powerful search facilities to quickly locate all the information you need. &#8230;</p></blockquote>
<p><a title="Oracle FAQ's" href="http://www.orafaq.com/">Check it out here</a></p>
<h3><a title="Morgan's Library" href="http://morganslibrary.org/">Morgan&#8217;s Library</a></h3>
<p>By <a title="Daniel Morgan" href="http://morganslibrary.org/about.html">Daniel Morgan</a></p>
<blockquote><p>The library is a spam-free on-line resource with code demos for DBAs and Developers.<br />
If you would like to see Oracle database funtionality added to the library &#8230; just email us.<br />
Coming soon &#8230; Oracle&#8217;s Database 12cR1. While waiting: check the section of ODA&#8217;s and ZFS.</p></blockquote>
<p><a title="Morgan's Library" href="http://morganslibrary.org/">Check it out here</a></p>
<p>The post <a href="http://oracletuts.net/news/oracle-plsql-and-sql-blog-posts-from-around-the-web-102013/">Oracle PLSQL and SQL Blog Posts From Around the Web (10/2013)</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/news/oracle-plsql-and-sql-blog-posts-from-around-the-web-102013/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Generate Date Range In Oracle SQL?</title>
		<link>http://oracletuts.net/tutorials/how-to-generate-date-range-in-oracle-sql/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-generate-date-range-in-oracle-sql</link>
		<comments>http://oracletuts.net/tutorials/how-to-generate-date-range-in-oracle-sql/#comments</comments>
		<pubDate>Wed, 27 Feb 2013 21:48:39 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[data retrieval]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[date and timestamp]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=2324</guid>
		<description><![CDATA[<p>Have you ever wanted to generate a list of dates using Oracle SQL? In this little tutorial I will show you three different ways you can do this with a simple SQL query. I will also show a practical use of it. Introduction I work in the Data Warehouse team of a large Multi Level ...</p><p>The post <a href="http://oracletuts.net/tutorials/how-to-generate-date-range-in-oracle-sql/">How To Generate Date Range In Oracle SQL?</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Have you ever wanted to generate a <strong>list of dates using Oracle SQL</strong>? In this little tutorial I will show you three different ways you can do this with a simple SQL query. I will also show a practical use of it.</p>
<p><span id="more-2324"></span></p>
<span>
			</span>
<h1>Introduction</h1>
<p>I work in the Data Warehouse team of a large Multi Level Marketing company. One thing I work with a lot, is dates.</p>
<p>Recently I had the following situation:</p>
<ul>
<li>For each distributor in our Philippines market that had done a purchase the last month, show the purchase amounts for the last 14 weeks for each of these distributors</li>
<li>Some of the distributors have not purchased every week</li>
</ul>
<p>So, based on the situation above, we might be missing some records if we just use i.e. our ORDERS table. This, since we know that some (or many) of the distributors have not purchased for each of the 14 weeks.</p>
<p>So, how can we avoid getting &#8220;holes&#8221;?</p>
<h2>Step # 1: Get the Date Range</h2>
<p>The first thing we would need to do to <strong>generate a date range in Oracle SQL</strong>, is to actually make sure we can actually create a <strong>SELECT</strong> that returns the data we need. There are probably many ways to do this, but here are three different methods.</p>
<h3>Method # 1: Get the Date Range Based on a Date Table</h3>
<p>In the database I work with on daily basis, we have a table that has a record for each date until probably 2016. I used this to get my date range.</p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	dd.date_key
  2  FROM	edw.dim_date dd
  3  WHERE	dd.cal_day_of_week_number = 6
  4  AND		dd.date_key BETWEEN TO_DATE(&#039;20130225&#039;, &#039;YYYYMMDD&#039;) - (7 * 14) AND TO_DATE(&#039;20130225&#039;, &#039;YYYYMMDD&#039;)
  5  ORDER BY dd.date_key
  6  /

DATE_KEY
-----------
11/23/2012
11/30/2012
12/7/2012
12/14/2012
12/21/2012
12/28/2012
1/4/2013
1/11/2013
1/18/2013
1/25/2013
2/1/2013
2/8/2013
2/15/2013
2/22/2013

14 rows selected</pre>
<p>In my company, we use a &#8220;commission week&#8221;, which always ends on a Friday. Since I wanted the Fridays, I used cal_day_of_week = 6 in line # 3.</p>
<h3>Method # 2: Get the Date Range Based on a &#8220;dummy&#8221; Table</h3>
<p>Another way to get a date range is to use any table that you know will have the amount of records that you will need for your date range</p>
<pre class="brush: sql; gutter: true">SQL&gt; WITH dateqry AS (
  2                      SELECT	TRUNC(SYSDATE) - ROWNUM dateval
  3                      FROM	all_objects
  4                      WHERE	ROWNUM &lt; (7 * 14)
  5  				)
  6  SELECT	*
  7  FROM	dateqry dq
  8  WHERE	TO_CHAR(dq.dateval, &#039;DY&#039;) = &#039;FRI&#039;
  9  /

DATEVAL
-----------
2/22/2013
2/15/2013
2/8/2013
2/1/2013
1/25/2013
1/18/2013
1/11/2013
1/4/2013
12/28/2012
12/21/2012
12/14/2012
12/7/2012
11/30/2012
11/23/2012

14 rows selected</pre>
<p>We still get the dates we want&#8230;</p>
<h3>Method # 3: (Preferred) Get the Date Ranges Based on The Oracle Dual Table</h3>
<p>I believe this method would be the preferred method to get the dates we need for the next step. In this method, we are actually using the <strong>Oracle dual table</strong>, which only contains one record!</p>
<p>Here is how you can do that, using a <strong>CONNECT BY</strong></p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	x.dateval
  2  FROM	(
  3  			SELECT	(TRUNC(TO_DATE(&#039;20130225&#039;, &#039;YYYYMMDD&#039;)) - ROWNUM) + 1 dateval
  4  			FROM	dual CONNECT BY ROWNUM &lt; (7 * 14)
  5  		) x
  6  WHERE	TO_CHAR(x.dateval, &#039;DY&#039;) = &#039;FRI&#039;
  7  /

DATEVAL
-----------
2/22/2013
2/15/2013
2/8/2013
2/1/2013
1/25/2013
1/18/2013
1/11/2013
1/4/2013
12/28/2012
12/21/2012
12/14/2012
12/7/2012
11/30/2012
11/23/2012

14 rows selected</pre>
<p>And&#8230;we got our 14 previous Friday records.</p>
<div class="box info"><div>
			UPDATE 3/26/2013: If you i.e. would like to run the above query for all Fridays up to previous Friday (without calculating number of days), you can i.e. do like below.</p>
<pre class="brush: sql; gutter: true">SELECT	x.dateval
FROM	(
            SELECT	(TO_DATE(&#039;20080111&#039;, &#039;YYYYMMDD&#039;) + ROWNUM) + 1 dateval
            FROM	dual 
            CONNECT BY ROWNUM &lt; ((TRUNC(SYSDATE + 1, &#039;d&#039;) - 2) - TO_DATE(&#039;20080111&#039;, &#039;YYYYMMDD&#039;))
		) x
WHERE	TO_CHAR(x.dateval, &#039;DY&#039;) = &#039;FRI&#039;
ORDER BY x.dateval
;</pre>

			</div></div>
<h2>Step # 2: Put it together</h2>
<p>Ok, so we now have decided on the method to get our <strong>date range</strong>. Let&#8217;s put it into action, for some practical use.</p>
<p>To avoid returning too many records for this sample, I picked out only two distributors. As you can see, these people do not have a purchase for all of our 14 weeks:</p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	o.commission_date
  2  		,o.customer_id
  3  FROM	odsy.orders o
  4  WHERE	o.commission_date BETWEEN TRUNC(SYSDATE + 1, &#039;d&#039;) - 2 - (7 * 13) AND TRUNC(SYSDATE + 1, &#039;d&#039;) - 2
  5  AND		o.ship_to_country_code = &#039;PH&#039;
  6  AND		o.customer_id IN (8001636, 6722194)
  7  ORDER BY	o.commission_date
  8  			,o.customer_id
  9  /

COMMISSION_DATE CUSTOMER_ID
--------------- -----------
11/23/2012          8001636
12/21/2012          8001636
1/18/2013           8001636
1/18/2013           8001636
1/18/2013           8001636
2/8/2013            6722194
2/15/2013           6722194
2/22/2013           6722194
2/22/2013           8001636

9 rows selected</pre>
<p>So, here comes the real trick. We are actually going to force a <strong>CARTESIAN JOIN</strong> to make sure we have the correct number of records.</p>
<p>&nbsp;</p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	dt.dateval
  2  		,ord.customer_id
  3  FROM	(
  4              SELECT	o.customer_id
  5              FROM	odsy.orders o
  6              WHERE	o.commission_date = TRUNC(SYSDATE + 1, &#039;d&#039;) - 2
  7              AND		o.ship_to_country_code = &#039;PH&#039;
  8              AND		o.customer_id IN (8001636, 6722194)
  9  		) ord
 10  		,(
 11              SELECT	x.dateval
 12              FROM	(
 13                          SELECT	(TRUNC(TO_DATE(&#039;20130225&#039;, &#039;YYYYMMDD&#039;)) - ROWNUM) + 1 dateval
 14                          FROM	dual CONNECT BY ROWNUM &lt; (7 * 14)
 15                      ) x
 16              WHERE	TO_CHAR(x.dateval, &#039;DY&#039;) = &#039;FRI&#039;
 17  		) dt
 18  /

DATEVAL     CUSTOMER_ID
----------- -----------
2/22/2013       6722194
2/15/2013       6722194
2/8/2013        6722194
2/1/2013        6722194
1/25/2013       6722194
1/18/2013       6722194
1/11/2013       6722194
1/4/2013        6722194
12/28/2012      6722194
12/21/2012      6722194
12/14/2012      6722194
12/7/2012       6722194
11/30/2012      6722194
11/23/2012      6722194
2/22/2013       8001636
2/15/2013       8001636
2/8/2013        8001636
2/1/2013        8001636
1/25/2013       8001636
1/18/2013       8001636
1/11/2013       8001636
1/4/2013        8001636
12/28/2012      8001636
12/21/2012      8001636
12/14/2012      8001636
12/7/2012       8001636
11/30/2012      8001636
11/23/2012      8001636

28 rows selected</pre>
<p>As you can see, we now have 14 records for each of these two distributors, all together 28 records. This is exactly what we need as our base to solve our task. We will now have to join this query with whatever other tables we need to get the data we need (not shown in this example).</p>
<h1>Summary</h1>
<p>As we have seen, there are at least three different ways to get date ranges in Oracle. If you do not have a date table (with records for each of the dates for multiple years, I would recommend method # 3 shown above.</p>
<p>Also, we can force a <strong>CARTESIAN JOIN</strong> to make sure we have all the records we need. In general: Be aware of <strong>CARTESIAN JOINS</strong>, and avoid them wherever you can.</p>
<p>If you have comments, or have other ways to do this&#8230;please let us all know.</p>
<p>&nbsp;</p>
<p>I hope you enjoyed this tutorial,</p>
<p>TJ</p>
<p>The post <a href="http://oracletuts.net/tutorials/how-to-generate-date-range-in-oracle-sql/">How To Generate Date Range In Oracle SQL?</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/tutorials/how-to-generate-date-range-in-oracle-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction To Aggregate Functions In Oracle</title>
		<link>http://oracletuts.net/tutorials/introduction-to-aggregate-functions-in-oracle/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=introduction-to-aggregate-functions-in-oracle</link>
		<comments>http://oracletuts.net/tutorials/introduction-to-aggregate-functions-in-oracle/#comments</comments>
		<pubDate>Mon, 13 Aug 2012 22:16:13 +0000</pubDate>
		<dc:creator>TJ Abrahamsen</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[newbie]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://oracletuts.net/?p=558</guid>
		<description><![CDATA[<p>If you are new to SQL, you still might have heard about aggregate functions. These are functions that can be used inside a SELECT query. In this tutorial we are going to look a bit on what it is, and how it can be used. Introduction Aggregate functions are common in most (if not all) ...</p><p>The post <a href="http://oracletuts.net/tutorials/introduction-to-aggregate-functions-in-oracle/">Introduction To Aggregate Functions In Oracle</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>If you are new to SQL, you still might have heard about <strong>aggregate functions</strong>. These are functions that can be used inside a SELECT query. In this tutorial we are going to look a bit on what it is, and how it can be used.</p>
<p><span id="more-558"></span><br />
<span>
			</span>
<h2>Introduction</h2>
<p>Aggregate functions are common in most (if not all) relational database management systems (RDBMS).</p>
<p>In a database like Oracle, you will find many single-row functions like <strong>SUBSTR</strong>, <strong>TO_NUMBER</strong>, <strong>ROUND</strong>, etc. These are&#8230;like the name indicates: Functions that return a <span style="text-decoration: underline;">single result row for each row</span> in your resultset (the data returned back from your query).</p>
<p>An aggregate Function, on the other hand, return a single result row based on a <span style="text-decoration: underline;">group of rows</span>.</p>
<p>As an example, let us pretend we have the following scenario:</p>
<ul>
<li>100 people are gathered in a large empty building</li>
<li>They all have a last name, and many of them actually have the <span style="text-decoration: underline;">same</span> last name.</li>
</ul>
<p>There are many ways we can look at these people. We can order them alphabetically, by age, etc. But, 100 people are a lot of people to deal with, and what we really wanted was to count how many had the different last names (just for this simple example). What we can do is to line up everyone alphabetically, and then go through all of them to write down their names&#8230;and then count.</p>
<p>But, what if there was a smarter way?</p>
<h2>Aggregate Function Explained</h2>
<p>Let us again think about the 100 people we mentioned above. What if we had some guys volunteer to organize the people into groups, one per last name. Each of the volunteers would gather their group, and when it was their turn to report back to the person that gathered all the people&#8230;they would stand up and shout: &#8220;Hansen &#8211; 10 people&#8221;, the next volunteer would yell &#8220;Bailey &#8211; 5 people&#8221;, etc.</p>
<p>So, basically, if we were the ones gathering the people in the building, all we would need to do would be to come in at the end to note down the different last names, and how many there were of the different names. Essentially this is what happens in the database when we use aggregate functions. We tell the database engine that we want to &#8220;gather some people&#8221;, and how we want to group them&#8230;and the database takes case of the rest.</p>
<p>The syntax for using an aggregate function in Oracle is:</p>
<pre class="brush: sql; gutter: true">SELECT	column_1, coumn_2, column_3,..column_n, AGGREGATE_FUNCTION(expression)
FROM	table_1, .. table_n
WHERE	where_clause
GROUP BY column_1, column_2
HAVING 	having_condition
ORDER BY column_1</pre>
<h2>Aggregate Function COUNT sample</h2>
<p>Ok, so we have some background. Let us look at a practical example. We want to list all the last names, and then show how many there are of each of the names.</p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	e.last_name
  2  		,COUNT(*) name_count
  3  FROM	hr.employees e
  4  GROUP BY e.last_name
  5  ;

LAST_NAME                 NAME_COUNT
------------------------- ----------
Abel                               1
Ande                               1
Atkinson                           1
Austin                             1
/* A lot of records go here */
Cabrio                             1
Cambrault                          2
Chen                               1
Chung                              1
Colmenares                         1
Davies                             1
De Haan                            1

LAST_NAME                 NAME_COUNT
------------------------- ----------
/* A lot of records go here */
Gietz                              1
Grant                              2

LAST_NAME                 NAME_COUNT
------------------------- ----------
/* A lot of records go here */
King                               2
Kochhar                            1
/* A lot of records go here */
LAST_NAME                 NAME_COUNT
------------------------- ----------
/* A lot of records go here */
Olsen                              1
Olson                              1
Sarchand                           1

LAST_NAME                 NAME_COUNT
------------------------- ----------
Smith                              2
/* A lot of records go here */
Sullivan                           1
Taylor                             2
/* A lot of records go here */

102 rows selected
SQL&gt; /

LAST_NAME                 NAME_COUNT
------------------------- ----------
/* A lot of records go here */
Bull                               1
Cabrio                             1
Cambrault                          2
/* A lot of records go here */

LAST_NAME                 NAME_COUNT
------------------------- ----------
/* A lot of records go here */
Gietz                              1
Grant                              2
Greenberg                          1
/* A lot of records go here */

LAST_NAME                 NAME_COUNT
------------------------- ----------

/* A lot of records go here */
Khoo                               1
King                               2
/* A lot of records go here */

LAST_NAME                 NAME_COUNT
------------------------- ----------
/* A lot of records go here */
Russell                            1
Sarchand                           1

LAST_NAME                 NAME_COUNT
------------------------- ----------
Sewall                             1
Smith                              2
Stiles                             1
Taylor                             2

/* A lot of records go here */

102 rows selected</pre>
<p>Please note that I skipped showing a lot of records so that you should not be annoyed scrolling through them. <img src='http://cdn4.oracletuts.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>So, let us shorten down the list a bit.</p>
<h2>Aggregate Function COUNT using HAVING sample</h2>
<p>Let us show ONLY the last names that are owned by more than one employee.</p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	e.last_name
  2  		,COUNT(*) name_count
  3  FROM	hr.employees e
  4  GROUP BY e.last_name
  5  HAVING COUNT(*) &gt; 1
  6  ;

LAST_NAME                 NAME_COUNT
------------------------- ----------
Cambrault                          2
Grant                              2
King                               2
Smith                              2
Taylor                             2</pre>
<p>Here you can see that we have used the <strong>HAVING</strong> clause to limit the data in our result set. It is kind-of the <em>WHERE</em> of a <strong>GROUP BY</strong> statement.</p>
<p>Ok, let us now pretend we want to show the last names that are owned by two or more people for only a given set of departments. This can be a sample of that:</p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	e.last_name
  2  		,COUNT(*) name_count
  3  FROM	hr.employees e
  4  WHERE	e.department_id IN (50, 80)
  5  GROUP BY e.last_name
  6  HAVING COUNT(*) &gt; 1
  7  ;

LAST_NAME                 NAME_COUNT
------------------------- ----------
Taylor                             2
Cambrault                          2
Smith                              2</pre>
<p>Above we used both a WHERE and a HAVING. What will happen in this query is that it will select employees from the given departments, and then group the people.</p>
<p>You can also use two (or more) aggregate functions in your SELECT part of your query, and still only use one of these functions in your HAVING filter. As shown in this example:</p>
<pre class="brush: sql; gutter: true">SQL&gt; SELECT	e.last_name
  2  		,COUNT(*) name_count
  3          ,SUM(e.salary) salary_sum
  4  FROM	hr.employees e
  5  WHERE	e.department_id IN (50, 80)
  6  GROUP BY e.last_name
  7  HAVING SUM(e.salary) &gt; 15000
  8  ;

LAST_NAME                 NAME_COUNT SALARY_SUM
------------------------- ---------- ----------
Cambrault                          2      18500
Smith                              2      15400</pre>
<h2>The GROUP BY columns</h2>
<p>As you see from the query above, we are GROUPing our data on the last_name. But, you can group on more than one column. If you again look at the query above, you can SELECT any column from the employee table, but all the columns you SELECT <span style="text-decoration: underline;">has</span> to be present in your GROUP BY clause.</p>
<p>But, you can GROUP BY any columns from the employee table, even if they are not present as your SELECT columns.</p>
<p>Also, note that the order of the columns in your GROUP BY clause might matter in some situations The most important column to GROUP BY is the most left one on your GROUP BY line.</p>
<h2>Additional Aggregate Functions in Oracle</h2>
<p>In addition to the COUNT and SUM used in the queries above, there are many different aggregate functions in oracle. If you want to read more about these functions, I would suggest you take a look at the Oracle documentation:</p>
<p><a title="Oracle 11g R2 Aggregated Functions" href="http://docs.oracle.com/cd/E11882_01/server.112/e10592/functions003.htm">Oracle 11g R2 Aggregated Functions</a></p>
<p>If you have any questions about aggregate functions, please leave a comment so that we can all help each other.</p>
<p>~ TJ</p>
<p>&nbsp;</p>
<p>The post <a href="http://oracletuts.net/tutorials/introduction-to-aggregate-functions-in-oracle/">Introduction To Aggregate Functions In Oracle</a> appeared first on <a href="http://oracletuts.net">OracleTuts</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://oracletuts.net/tutorials/introduction-to-aggregate-functions-in-oracle/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced
Content Delivery Network via cdn.oracletuts.net

 Served from: oracletuts.net @ 2013-06-19 14:11:05 by W3 Total Cache -->