ANKUR JAIN

December 25, 2006

Reunion of Batch 1999, Ramjas School - Pusa Road

After a long time, due to sincere efforts of few enlightened a.k.a connected people (people in touch with old pals), Reunion of Batch 1999, Ramjas School - Pusa Road happened.

Time & Venue : Dec 17th, 2006 11 A.M. @ Cafe Coffee Day, Connaught Place - New Delhi

Well, I reached the venue quite late. Reason being, I was searching my wardrobe specifically for a Yellow pullover, which took me sometime. Although, experts from textile industry didn’t appreciate really; I guess they’re learning about the fashion trends :P

Anyways, when I reached the venue I welcomed other late comers. Another surprise was the strength of this reunion, must say. Big round of applause for friends who organized this affair. I believe the attendance achieved was worth the ordeal for them.

People from all streams (Science, Commerce, Arts) were present. Since, not everyone knew everyone else, we all introduced ourselves. We discovered people coming mainly from IT industry (quite obvious), Textiles & Banking industry. Rest are doing their family/own business.

I met everyone although I didn’t know all of them well. But then that’s the reason for a reunion, so that person like me can benefit from it.

Thank you Sumita, Sherry for organizing the reunion.

Filed under: Personal — Ankur Jain @ 12:44 pm

November 24, 2006

Ubuntu 6.10 Edgy Installation

I installed ubuntu 6.10 using net-install method, and it was a no-problem installation.

After the initial installation, I’d to install several small packages for essential features like MP3 support, jre & flash-plugin for firefox, mplayer. I followed the instructions at the link : http://ubuntuguide.org/wiki/Ubuntu_Edgy

The link provides all the information required to do all such configuration/setup tasks. But I had 2 problem relating to keyboard and sound card.

The keyboard was not working properly, as in some of the keys like ” and ‘ did not work properly. I’d to use the following command :

sudo dpkg-reconfigure xserver-xorg

and change the keyboard configuration. I removed all the customizations displayed by the configuration script.

The other problem was that of sound card. I could access the sound card as root; but not as a non-root user. I resolved the problem by changing the permissions of the non-root user as explained below :

Go to : System->Administration->Users and Groups

Here select the non-root User and Click Properties. In the User Privileges Section:

Check the following :
Use audio devices
Use CD-ROM drives

After that when I restarted Gnome; both keyboard, sound problems were resolved.

For performance enhancement I used prelink and added it to daily cron. Steps are mentioned at the following link:

http://ubuntuforums.org/showthread.php?t=1971

Ubuntu 6.10 is no doubt a great product. But I’m yet to install/test Mandriva One ;)

Filed under: Wired-News — Ankur Jain @ 8:26 am

October 10, 2006

Oracle Indexes

Indexes are optional data structures associated with Database tables. Indexes are logically & physically independent of the data in the associated table. They are independent database objects created to reduce disk I/O & speed up execution of SQL statements on a table. We can create many indexes on a table given that each index points to different column (in case of a single column) or unique combination of columns from a table.

All Indexes offer complementary performance functionalities based on their structure:

B-Tree indexes : B-Tree Indexes are stored as a conventional binary data structure in the database. Each branch node contains a key prefix to make a direction between two keys. Each Leaf Node is at same depth from the branch node and contain complete key value for each row & ROWID.

Features :

  • All leaf blocks of the tree are at same depth, resulting same performance for retrieval of any record from the indexed table.
  • B-Trees are stay balanced automatically.
  • Excellent performance is achieved for wide range of queries and are generally suitable for both small & large sized tables without performance degradation.

Syntax :

CREATE INDEX last_name_idx ON students (last_name);

Bitmap indexes : Bitmap Indexes are space efficient indexes that represent trade-off between Disk I/O and CPU usage. A bitmap value is stored for each key value instead of a list of ROWIDs. Each bitmap corresponds to a possible ROWID. A mapping function returns actual ROWID at runtime in the form of a Row-ID list, and these ROWID values are directly used to access the data row. So, there is a trade-off between space (using compressed indexes) and CPU usage (for processing decompression).

Features :

  • Bitmap indexes are generally used in data warehouses for executing bulk data operations.
  • They are space efficient, but need higher CPU usage in comparison to B-Tree Indexes.
  • Bitmap indexes are not suitable for OLTP applications with large number of concurrent operations modifying individual rows of data. They are efficient in querying large data.
  • Bitmap indexes are not useful when performing comparison operations, instead use them for logical operations on data (viz. AND, OR, NOT) or equality queries.

Syntax :

CREATE BITMAP INDEX last_name_idx ON students (last_name);

Bitmap Join indexes : As the name suggests, Bitmap join indexes are bitmap indexes defined using an equi-join condition between two or more tables. In bitmap-join index, indexed values comes from one table (Fact table) but bitmaps point to another table (Dimension table). Usually implemented in a data warehousing environment, they have similar features to bitmap indexes. Additionally, following considerations must be taken into account :

  • Bitmap-join indexes take much more time to build than a conventional bitmap index for a join is performed and bitmap value is generated.
  • Bitmap-join indexes should be applied on tables frequently used in tandem (using joins) with each other.

Syntax :

CREATE BITMAP INDEX last_name_idx ON students (math.marks) WHERE students.pk = math.fk;


Index-Organized Tables :
An index organized table has a storage organization that is different from a conventional (heap-organized) table whose data is stored as an unordered collection. Data for an index organized table is stored in a B-Tree index structure in a primary key sorted manner. Along with the primary key column data, it stores the values for the non-key columns as well.

Features :

  • Access to rows is defined using logical ROWID.
  • Full-Index returns all rows.
  • Avoid additional block fetch for accessing non-key columns’ data.

Syntax :

CREATE TABLE students (
rollno number,
first_name varchar2(20),
last_name varchar2(20),
CONSTRAINT pk_stud_iot_index PRIMARY KEY (rollno) )
ORGANIZATION index
TABLESPACE spc_example_ts_01
PCTHRESHOLD 20 INCLUDING last_name;


Function based indexes :
Function based indexes are based on functions, expressions that involve one or more columns in the table being indexed. A value of the function/expression is calculated and stored as the value for the index. They can be stored either as a B-Tree index or a bitmap index.

Features :

  • Function based indexes are beneficial for evaluating queries that involve functions in WHERE clauses. Example :
  • SELECT * FROM students WHERE substr(stud_name, 1, 5) = "PETER";

  • It’s easy & provides immediate values for expressions.
  • It provides additional functionality with little cost, if expensive functions/expressions need to be evaluated regularly from the indexed table.

Syntax :

CREATE INDEX fb_last_name_idx on students (UPPER(last_name));

Filed under: Wired-News — Ankur Jain @ 8:27 pm

September 4, 2006

Oracle Collections

PL/SQL Collections

Index-by tables (Associative Arrays): They are arrays with the only difference that we can use numbers, string literals for subscript values. Associative Arrays are sets of key-value pairs, where key can be an integer or a string. There is no limitation on the size of Associative Arrays.

Syntax: TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY [BINARY_INTEGER | PLS_INTEGER | VARCHAR2 (size_limit)] ;

Nested Tables: They are single dimensional, array-like tables, that can hold any number of elements inside another database table and can be manipulated by SQL as other database objects.

Syntax: TYPE type_name IS TABLE OF element_type [NOT NULL];

Varying Arrays: As the name suggests, varrays (Varying Arrays) are fixed length arrays that use sequential numbers as subscripts. varrays need to be dense and we cannot remove/delete individual elements from the array. Length is defined at design time and can be manipulated at runtime subject to maximum length defined. They are suitable in cases where all elements in the array are accessed in sequence.

Syntax: TYPE type_name IS [VARRAY | VARYING ARRAY] (size_limit) OF element_type [NOT NULL];

Using PL/SQL Collections in SQL statements

NESTED TABLE

CREATE TYPE Courseslist AS TABLE OF VARCHAR2(50);

CREATE TABLE student as OBJECT (
roll_no NUMBER(2),
name VARCHAR2(20),
courses Courseslist)
NESTED TABLE courses STORE AS courses_tab;

VARRAY

CREATE TYPE Courseslist AS VARRAY(50) OF VARCHAR2(20);

CREATE TABLE student (
roll_no NUMBER(2),
name VARCHAR2(20),
courses Courseslist);

USING COLLECTIONS IN SQL

DECLARE
TYPE Courseslist is TABLE OF VARCHAR2(20);
TYPE Courseslist2 is VARRAY(40) OF VARCHAR2(20);
my_courses Courseslist;
my_courses2 Courseslist2;
BEGIN
my_courses := Courseslist(’English’, ‘Mathematics’, ‘Science’);
my_courses2 := Courseslist2(’English’, ‘Mathematics’, ‘Science’);
INSERT INTO student values(12, ‘Ankur’, Courseslist(’English’, ‘Mathematics’, ‘Science’));
END;

Manipulating Individual Elements in Collections

Using subqueries within TABLE operator we can extract varrays and Nested tables from containing table and execute INSERT, UPDATE and DELETE operations.

Syntax:

BEGIN
INSERT INTO TABLE (SELECT courses FROM student where roll_no=2) VALUES (’German’);
DELETE TABLE (SELECT courses FROM student where roll_no = 1) WHERE course_strength < 5;
END;

USING COLLECTION METHODS

EXISTS - Check if an element exists in the collection.
Syntax : IF courses.EXISTS(i) THEN courses(i) = new_course; END IF;

COUNT - Count the elements in collection
Syntax : IF courses.COUNT > 20 THEN...

LIMIT - Check the Maximum Size of a collection
Syntax: IF new_courses.COUNT < courses.LIMIT THEN ...

FIRST and LAST - Retrieve the FIRST and LAST element from collection
Syntax: IF courses.FIRST = courses.LAST THEN ...

PRIOR and NEXT - Retrieve Previous and Next element of an index in collection.
Syntax: courses(i) = courses.NEXT(courses.PRIOR(i));

EXTEND - Append a null element at the end of collection.
EXTEND (n) - Append n null elements to the collection.
EXTEND (n,m) - Append n copies of element m to the collection.
Syntax: courses.EXTEND(2,1) : Appends 2 copies of 1st element of courses collection.

TRIM - Remove the last element from a collection.
TRIM(n) - Remove n elements from the end of a collection.
Syntax: courses.TRIM(5) : Remove last 5 elements from courses collection.

DELETE - Delete all elements from a collection
DELETE(n) - Delete nth element from an associative array with numeric key or a nested table. If key is string in Associative Array, element corresponding to the key value is deleted. If n is null, DELETE(n) does nothing.
DELETE(m, n) - DELETE elements in the range m-n from an associative array or nested table.

Varrays are dense, therefore, individual elements cannot be deleted from Varrays.

BULK BINDING

Assigning of values to PL/SQL variables in SQL statements is called binding. Use FORALL statement for bulk-bind input operations before sending them to SQL engine. It improves performance by minimizing context switching between SQL Engine and PL/SQL Engine and passing whole collections to SQL ENGINE at a time during execution.

Syntax:

DECLARE
TYPE NumList is VARRAY(20) OF NUMBER;
courses NumList := NumList(10, 20, 30);
BEGIN
FORALL i in courses.FIRST..courses.LAST
DELETE FROM student where course_id = courses(i);
END;

We can redefine the length of loop to execute the FORALL statement selectively. We may count number of rows affected, exceptions occurred in FORALL statement using SQL%BULK_ROWCOUNT, SQL%BULK_EXCEPTIONS attributes after the end of the loop.

BULK COLLECT

We use BULK COLLECT to bulk-bind output collections before returning to PL/SQL Engine as so to improve the performance, in a similar way, we used FORALL statement.

Syntax: SELECT courses BULK COLLECT INTO my_courses FROM student;

We can also use BULK COLLECT with cursors.

Syntax:

BEGIN
OPEN c1;
FETCH c1 BULK COLLECT INTO my_courses;
END;

LIMIT clause to limit the rows fetched for a BULK FETCH Operation

Syntax:

BEGIN
OPEN c1;
FETCH c1 BULK COLLECT INTO my_courses LIMIT 10;
END;

RETURNING INTO Clause

We can use RETURNING INTO clause to retrieve DML results into a collection.

Syntax:

BEGIN
DELETE FROM student WHERE marks < 50;
RETURNING courses BULK COLLECT INTO my_courses;
END;

We can use Host Arrays with Bulk Binds for output and input, as they are the most effective way to pass collections between database server and clients.

Syntax:

BEGIN
FORALL i in :lower .. :upper
DELETE FROM student WHERE roll_no := roll(i);
END;

Filed under: Wired-News — Ankur Jain @ 3:37 pm

August 23, 2006

Sites We Cant Live Without

Recently, I came across the Time.com’s list of 25 sites, We Can’t Live Without.

I read it till the end to discover the new websites, I might be unaware of. I thought so because being a software professional, I spend much of my time daily browsing Internet. Not to my surprise, I came across quite a few websites, I had not heard of. More so, may be because I don’t need the services offered by them like one that’s selling shoes and accessories. But there were some websites, I was happy to browse.

One of them is Craiglist, it’s more like Yellow Pages cum Free Advertisements that are bundled for free alongwith the Newspapers. I was surprised to see a separate section for Bangalore and that too quite an active one.

Others in the list were mainly News-Related Websites or portals like Yahoo, MSN & AOL. Though they are not exactly comparable in terms of size and content, but that’s a broad category I’m putting them into.

Drudge Report, Factcheck.org, National Public Radio and The Onion are the ones, which are mainly meant for reading news. Out of all of them, I found Drude Report quite unique. It’s like Bookmark folder in your browser, with links to almost all popular news websites and some other hyperlinks to the Breaking News of the day.

Other than them, one of the interesting website, I came across is Netflix.com It’s an online movie rental website, with more than 65,000 titles - Classics to new releases. It offers free shipping, no late fees and free trial for new customers. Ultimate treat for movie buffs. A clean interface to browse the movie titles is appealing and little background about the movies is quite informative. A rating mechanism or a link to IMDB for that particular title would have been great :) But I think the other website Rotten Tomatoes fills in that gap.

Last category of websites was shopping websites like Shopzilla and Zappos. Shopzilla has quite a vast variety of products from different stores, zappos offers accessories mainly like shoes, handbags and apparels. Both of them are quite okay, as you can rate them after comparing the deals offered by them.

Then, there were the giants like Amazon, Google, Yahoo etc. everyone knows, use and of course, we can’t live WITHOUT any one of them. In the end, here is a list of sites, I can’t live without - Amazon, Google, Yahoo!, Wikipedia, Blogger, Google News, ESPN, Ebay, Flickr, Apple Movie Trailers and The Internet Movie Database.

Filed under: Personal — Ankur Jain @ 7:18 pm

August 9, 2006

Lyceum Installation

Lyceum is an extension of the popular Wordpress blogging software. While Wordpress is a single user blogging software, Lyceum is a multiple users blogging software. Under early development, read about it here

I tried installing it on my Windows XP system, running Apache 2.0.59, PHP 4.4.3 & MySQL 3.23.42 and faced quite some problems, so thought to blog about it.

Installation Steps

Download, Install and configure Apache, MySQL and PHP on your Windows Machine. Download and Installation should not be a problem. For configuration, you may follow these links:

http://www.thesitewizard.com/archive/php4install.shtml

http://www.dmxzone.com/ShowDetail.asp?NewsId=6452

After you’ve configured all the above 3 components, download Lyceum source from here

Extract the source and place it under your DocumentRoot (<DOC_ROOT>). You should have the following directory structure.

	<DOC_ROOT>/lyceum
		+  /dev
		|  /doc
		|  /src
		|    + /bin
		|    | /config
		|    | /installation
		|    | /lib
		|    + /lyceum
		+   /tests

Before starting the installation verify the Apache configuration first. You must have mod_rewrite module enabled in your Web Server Configuration. Also in the <Directory> configuration part of your Apache configuration file, you must set the AllowOverride directive to “All”; that is, “AllowOverride All

Now, create a database in your MySQL server for lyceum as lyceum does not create the database itself.
SQL : mysql>CREATE DATABASE lyceum;

In case you are using MySQL < 4.0.X, verify if you’ve got InnoDB & MyISAM database engines enabled in your MySQL server. If not modify schema.php (<DOC_ROOT>/lyceum/src/installation/) accordingly to remove the ENGINE directives from SQL statements.

Modify wp-config-sample.php (<DOC_ROOT>/lyceum/src/config/) to create wp-config.php with modifications to following fields:

DB_NAME : Name of the Database you’ve created in MySQL.
DB_USER : Database User Name
DB_PASSWORD : Password for the specified Database User Name.
DB_HOST : Server Name / Addresss (’localhost’ in case of local installation)
WEBROOT : Location of /lyceum/src/lyceum on the server (Directory where portal.php is placed. Note: ‘no trailing slash after the path)
MAINDOMAIN : 127.0.0.1 ( For local installation. Note: ‘localhost’ will not work)

Start the installation from your web browser using the URL : <server_address>/<webroot>/wp-admin/install.php

It should work fine. Comment if you face any issues.

Filed under: Wired-News — Ankur Jain @ 8:25 am

July 14, 2006

Yahoo, Microsoft Integrate IM Services

Yahoo & Microsoft have opened their Instant Messaging Networks to inter-operate with each other early today, in a limited public test.

This move shall be welcomed by users who don’t want to switch to other network or manage multiple buddy lists for different networks.

Now after this integration, Yahoo & MSN Messenger users can talk with each other using their choice of IM network/application.

This move poses pressure on AOL, the market leader with 56 percent market share of IM users.

According to Nielsen/Netratings, a market intelligence firm, Microsoft’s MSN Messenger and Windows Live Messenger were the second-biggest instant messaging services in the United States with a combined 28 million users last month. AOL ranked first with 47 million users and Yahoo ranked third with 22 million users.

Google’s Google Talk, which is based on an open standard, has only a fraction of the users, 811,000, of the top three IM companies. Windows Live Messenger comes second at 25 percent, while Yahoo is in third place with 19 percent of share.

Beta users will be able to send IMs, check to see who is online, share emoticons, view offline messages, and add users from both services to their contact lists. Though, voice chat is not on the list of features for the beta.

For using this feature, users need to download Windows Live Messenger Beta and Yahoo Messenger Beta. Third party applications like Gaim/Trillian cannot make use of this feature as of now. But they should be able to support this feature sometime later.

Filed under: Wired-News — Ankur Jain @ 9:04 am

June 29, 2006

Open Document Format

Open Document Format (ODF), short name for OASIS Open Document Format for Office Applications (OpenDocument). ODF is an open document file format that can be used for creating various document types like text documents, spreadsheets, presentations, databases, charts, tables and formulas. It was initially developed by Openoffice.org and later on developed by OASIS International Consortium.

By open document file format, I mean the XML-based format specifications are accessible by everyone and anyone can implement it freely to create editable office documents. As ODF is based upon XML, it defines a schema for representing all types of data. The complete specifications are available online.

It provides an alternative solution to vendor-specific (Microsoft Office, being the single major one) proprietary formats, so that organizations and individuals may adopt an open format and can use other software in case they don’t want to depend on a proprietary format & software and want to remain flexible.

ODF Specifications

An OpenDocument file can be either a single XML file, or as a collection of several subdocuments within a package (ZIP archive mainly) each of which represents part of the complete document. The latter is used almost exclusively, for it can embed binary content and tends to be significantly smaller. In OpenDocument format, each structural component is represented by an element with associated attributes. It applies to all document types, so there is no difference between a text document, a spreadsheet or a presentation, apart from content.

There are four types of subdocuments, each with different root elements. Additionally, the single XML document has its own root element. The root elements are given below:

Root Element Subdocument Content Name in Package
<office:document> Complete document in a single XML Document. n/a
<office:document-content> Document content & automatic style used in the content. content.xml
<office:document-styles> Styles used in document content & automatic style used in the styles. styles.xml
<office:document-meta> Document meta information, like author name, last time of save action. meta.xml
<office:document-settings> Application-specific settings such as zoom factor, cursor position etc. settings.xml

OpenDocument format is also supported for the Accessibility features. Specification of OpenDocument is going through an extensive review, and many sub-components of ODF have gone through W3C’s Web Accessibility Initiative processes. ODF is supported as it’s got an advantage over proprietary formats, which generally don’t undergo peer reviews for accessibility issues. Open specifications of OpenDocument allows anyone to create software for those suffering from disabilities unlike proprietary formats which cannot be implemented easily by everyone.

Microsoft Office Open XML

Microsoft Open XML format is again Microsoft-specific file format to be implemented in upcoming Microsoft Office 2007 release of Office Suite. It’s the only competitor considered to the Open Document Format. Now, the difference between the two is ODF is an open format, but Microsoft’s Open XML has licensing requirements and it prevent some competitors from using it.

Now, we need to know what it means when Microsoft has created a separate format for itself. Certain software companies have criticized this move as Microsoft’s plan to counter attack the ODF standard, as currently Microsoft enjoys almost complete monopoly in the Office-suite market. So, if ODF becomes a popular, de-facto standard for creating, exchanging office documents, that means Microsoft loses its monopoly over the market.

But Microsoft maintains its stand for a different XML format so as to allow for backwards compatibility for existing documents and full support of all the features available, which are not supported by ODF, according to Microsoft. So, that is Microsoft’s decision.

But the good point is, Industry is slowly progressing from conventional binary formats (.ppt, .doc etc.) to open XML based formats which would open many other options for users to create office documents. The new format allows for smaller sized documents and allows for lower level of content manipulations for document recovery, modular structure by separating content, layout, styles & better accessibility to all types of users.

Filed under: Wired-News — Ankur Jain @ 11:32 am

June 22, 2006

Single File Format

Recently, I read this article, where in the Author has imagined interoperability of all files some way; where all possible file formats could be represented in a standard/single format, so as to ease the process of file editing/creating and parsing.

Read it here

Filed under: Wired-News — Ankur Jain @ 9:20 am

June 12, 2006

Oracle Joins

Definition / Concept

If we need to retrieve data from more than one table we use JOINs. A join is a query, used to retrieve data from more than one table based on JOIN condition (Note: Same table can referenced more than once).

Conditions

In SQL terms, Join occurs when we specify more than one table in the FROM clause of the SELECT statement. Additionally, we also specify a condition in the WHERE clause to specify JOIN condition in the SELECT statement. Now, JOINs are conditions to join/compare two tables’ data retrieved from the selected tables’ columns based on JOIN Condition. Oracle combines the rows’ data to compare with other tables’ rows and evaulate the JOIN condition for TRUE/FALSE.

We need to qualify columns having same name with table names/aliases to avoid ambiguity errors, for joins can be extended to multiple tables. In case of multiple joins extending to more than 2 tables, let’s say 3 for example, we create a recordset based on 1st join between 1st two tables & join the resulting recordset with 3rd table using 2nd Join.

Table 1 + 
        |
      (JOIN)--->Recordset I +
        |                   |
Table 2 +                   |
                          (JOIN)--- Final Recordset
                            |
                            |
                            +
                          Table 3

Now, we’ve understood what are joins, their need & application, let’s see what are the different types of JOINs
available.

SIMPLE JOIN/INNER JOIN/EQUALITY JOIN/EQUIJOIN

All the above terms refer the same JOIN type. Let’s call them INNER JOIN for our reference. Inner Join have equality operator as the JOIN condition. So, INNER JOIN returns only those rows from two tables that have same data for the specified columns.

Example:

+--------+              +---------+
|   ID   |              |   ID    |
|  NAME  |              | SALARY  |
|  AGE   |              |         |
|--------|              |---------|
|EMPLOYEE|              | PAYROLL |
+--------+              +---------+

We need to extract the salary of an employee from the payroll table. So, a INNER JOIN shall be created between EMPLOYEE
& PAYROLL table, using ID columns from the two tables.

SELECT employee.id, employee.name, payroll.salary
FROM employee, payroll
WHERE employee.id = payroll.id;

SELF JOIN

If we compare the data of a table with itself, we create a self join. I’ll give here a classical example of employees & managers. Suppose, we need to know the name of employees’ manager from the employee table, we’ll create a self join. For example purpose, I modify the EMPLOYEE table.

+--------+
|   ID   |
|  NAME  |
|  AGE   |
| MGR_ID |
|--------|
|EMPLOYEE|
+--------+

SELECT e1.name EMPLOYEE, e2.name MANAGER
FROM employee e1, employee e2
WHERE e1.mgr_id = e2.id;

CARTESIAN PRODUCT

If there is no comparison condition specified in a JOIN condition, a cartesian product is returned. In such a case, every row in a table is joined with every row in the other table of the JOIN. Let’s say, if there are 3 rows in Ist table & 4 rows in the IInd table, 12 rows (3×4) would be produced.

+--------+              +---------+
|   ID   |              |   ID    |
|  NAME  |              | SALARY  |
|  AGE   |              |         |
|--------|              |---------|
|EMPLOYEE|              | PAYROLL |
+--------+              +---------+

SELECT employee.id, payroll.salary
FROM employee, payroll
WHERE employee.name LIKE 'A%';

NATURAL JOIN

In a NATURAL JOIN all columns with same names & datatype are joined from both tables. Here, we need to qualify the column name by table name or alias. All rows matching with the same column data are retrieved.

+--------+              +---------+
|   ID   |              |   ID    |
|  NAME  |              | SALARY  |
|  AGE   |              |         |
|--------|              |---------|
|EMPLOYEE|              | PAYROLL |
+--------+              +---------+

SELECT id, name, salary
FROM employee NATURAL JOIN payroll;

OUTER JOIN

Till now, all joins we’ve discussed retrieve all matching records from both tables. But sometimes, there is a situation when we also need to retrieve non-matching records from either one or both tables. For retrieving such non-matching records, we create OUTER JOINs. There are 3 type of OUTER JOINs based on from which side of the JOIN Condition we extract the non-matching records. We assume the following structure for our examples:

+--------+              +---------+ 
|   ID   |              |         | 
|  NAME  |              |   ID    | 
|  AGE   |              |  SALARY | 
| MGR_ID |              |         | 
|--------|              |---------| 
|EMPLOYEE|              | PAYROLL | 
+--------+              +---------+

RIGHT OUTER JOIN

As the name suggests, we extract non-matching records from the table mentioned on the right hand side of the JOIN condition. So, all the matching records from two tables, as well as non-matching records from the 2nd table (on right hand) are retrieved. NULL values are replaced for the non-existing values for columns extracted from table on the right hand side in non-matching rows.

SELECT e.id, p.salary
FROM employee e, payroll p
WHERE e.id = p.id (+);

LEFT OUTER JOIN

In this JOIN, we extract non-matching records from the table mentioned on the left hand side of the JOIN condition in addition to the matching records. NULL value is displayed for the columns extracted from table on the left hand side in the non-matching rows.

SELECT e.id, p.salary
FROM employee e, payroll p
WHERE e.id (+) = p.id;

FULL OUTER JOIN

In case of a full outer join, we extract matching records from both tables specified in JOIN condition, as well as non-matching records from both tables. Actually to create FULL OUTER JOIN, a UNION set is generated from both LEFT OUTER JOIN & RIGHT OUTER JOIN. NULL values are displayed for non-existing records of the other table in each non-matching row of either table.

SELECT e.id, p.salary
FROM employee e, payroll p
WHERE e.id = p.id (+)
UNION
SELECT e.id, p.salary
FROM employee e, payroll p
WHERE e.id (+) = p.id;

Note:

  • SQL statements provided in the post were tested on Oracle 8 version only. Natural Joins don’t exist on Oracle 8
  • ANSI syntax has not been covered here.
Filed under: Personal — Ankur Jain @ 11:06 am
« Previous PageNext Page »

Powered by WordPress