Monday, March 31, 2008

Asking questions on Forums

“The important thing is never to stop questioning.”
Albert Einstein

I was reading Shay Shmeltzer's and Hector Rivera Madrid's post on the generals rules on posting on User Forums. I don't want to summarize a list of my own as these gentlemen have already prepared a wonderful list of do's and don'ts.

I still have a bookmark to an old article - How to ask questions the smart way. The article is still being revised and maintained.

To summarize Shay's intentions :-

" I think there are some things that posters to the forums can do to make the whole experience of using the forums a lot better. "

Friday, March 21, 2008

Holi - 2008


It's Holi ! The festival of colors ! It's time to get drenched in a variety of colors !

Originally, Holi started out as a festival to celebrate good harvests. Now, it's more of a festival to have a good time :).

The day also marks Good Friday.

I am sitting at office trying to complete a pending task & suddenly, my colleagues smeared colors on my face. I am totally covered in colors & my laptop is sharing the same fate.

Well, I am looking forward to more fun & frolic during the weekend !

Self Appraisal

Another "gem" that I received in today's mail - thanks Vijay !:-

A little boy went into a drug store, reached for a soda carton and pulled it over to the telephone. He climbed onto the carton so that he could reach the buttons on the phone and proceeded to punch in eight digits (phone numbers).

The store-owner observed and listened to the conversation:

Boy: 'Lady, Can you give me the job of cutting your lawn?

Woman: (at the other end of the phone line): 'I already have someone to cut my lawn.'

Boy: 'Lady, I will cut your lawn for half the price of the person who cuts your lawn now.'

Woman: I'm very satisfied with the person who is presently cutting my lawn.

Boy: (with more perseverance): Lady, I'll even sweep our curb and your sidewalk, so on Sunday you will have the prettiest lawn in all of Palm beach, Florida.'

Woman: No, thank you.

With a smile on his face, the little boy replaced the receiver. The store-owner, who was listening to all this, walked over to the boy.

Store Owner: 'Son... I like your attitude; I like that positive spirit and would like to offer you a job.'

Boy: 'No thanks,

Store Owner: But you were really pleading for one.

Boy: No Sir, I was just checking my performance at the job I already have. I am the one who is working for that lady, I was talking to, and I was doing my 'Self Appraisal'

ORA-01000 maximum open cursors exceeded

" java.sql.SQLException : ORA-01000: maximum open cursors exceeded "

-- ORA-01000

I was recently asked my a colleague to help in resolving the ORA-01000 error. At a first glance, everything looked fine in the Java Code & it was baffling - it took sometime for enlightenment to illuminate the nature of the problem and one possible solution.

The program inherited by my colleague had two Java classes - Class A and Class B. Class A calls a method named insert() in Class B to save data into the database. Class A passed an ArrayList of Java Beans to the Class B's insert() method.

The logic to save the data was a plain - vanilla for loop :-

for ( int i = 0 ; i < number ; i++)
{

psSaveData = conOraleConnection.prepareStatement(insertSQL);
..........
..........
psSaveData.setString(1,dataBean.getId());
psSaveData.setString(2,dataBean.getName());
psSaveData.setString(3,dataBean.getAge());
..........
..........
psSaveData.executeUpdate();
}

Now, this piece of code was failing after the first 1000 rows !

We took sometime to methodically analyze the problem using an approach outlined at this link from BEA's Website. However, the problem persisted - either we missed something obvious or we were looking at something new. And then it occured to us :-

psSaveData = conOraleConnection.prepareStatement(insertSQL);

We finally figured out that the problem was caused by the statement marked in red. The line was actually telling the Oracle Database to precompile the same statement 1000 time !!

How does this matter ?

The Oracle Database contains a SQL Engine to deal with all SQL statements. The SQL Engine generally follows a two step process to execute a SQL Statement:-
  • parse : to check for syntax and semantic correctness.
  • execution plan : an optimized plan that details the instructions to execute the SQL statement.
The SQL Statement and the corresponding execution plan are stored together in a structure called a "Cursor". The Cursor is then stored in a special area of database memory called the "Shared Pool".

You can get handle to a cursor from a variety of languages like PL/SQL, Java, etc. You can then :-
  • Open the cursor.
  • Fetch the results
  • Close the cursor.
The Oracle database opens an "implicit cursor" for every SQL Statement that it encounters. Hence, a cursor is opened for every SELECT, INSERT, etc. statement that is issued to the SQL Engine.

Hence, you only need to prepare the "blueprint" once and execute it multiple times. The piece of code marked in red was preparing the "blueprint" 1000 times - as a result, 1000 cursors were opened !

We simply moved this line out of the for loop and solved one bottleneck.

We also noticed that the plain-vanilla JDBC Insert statement was not suitable for batch inserts. Well, that's another story :)


Thursday, March 20, 2008

Inspirations from Frogs

I was Googling around for something & came across this wonderful site about frogs. A page on the site is dedicated to "Frog Fables" - an eclectic of parables with a frog / toad as the topic of discussion.

I personally liked the story of "The Boiled Frog". I found it surprising that a frog's natural instincts are fine tuned to detect sudden changes in an environment, but not the slow changes that ultimately lead to the same change in the environment.

Well, this quote from the page, summarizes the story :-

" This parable is often used to illustrate how humans have to be careful to watch slowly changing trends in the environment, not just the sudden changes. Its a warning to keep us paying attention not just to obvious threats but to more slowly developing ones. "

Monday, March 17, 2008

Appending zeros in front of a number

I recently helped a colleague who had this simple requirement - to append zeros in front of a Number in a Java Method.

The purpose of the Method was to scan numbers between 1 and 999 and ensure that every number has three digits - the ones that have only two digits are appended by zeros.

The problem has multiple solutions & we were looking for the simplest possible solution. We tried a lot of solutions, starting with a simple for loop that counted the number of digits and appended zeros in front of it. We also looked at the Java API to see if a solution is already present.

However, we finalized two solutions that were very simple & elegant :-

Solution #1 ( JDK 1.5 onwards )

String.format("%03d", 1);
String.format("%03d", 10);
String.format("%03d", 100);


Solution #2 ( pre - JDK 1.5 )

NumberFormat objNumberFormat = new DecimalFormat("000");
objNumberFormat .format(Integer.parseInt( "1"));
objNumberFormat .format(Integer.parseInt( "10"));
objNumberFormat .format(Integer.parseInt( "100"));

We used Solution #2 to make the code reusable between JDK versions.

Thursday, March 13, 2008

What is domain knowledge ?

"Domain knowledge is defined as the collective knowledge gained through education, training, or a series of assignments in a functional area"

- Compensating for Incomplete Domain Knowledge

I frequently encounter profiles of candidates who claim to have knowledge in many domains in a very short time - sometimes, even less that two years. I usually view these profiles with suspect & many times, my suspicion was confirmed during conversations with the candidates. The candidates merely mention the domain of the clients they have worked with - often, they are unable to answer simple domain related questions or explain business needs that prompted the solutions they implemented.

I found that the definition I have mentioned in the beginning of his article captures the essence of Domain Knowledge. I would like to present my views about Domain Knowledge in this article.

Domain Knowledge is often gained through conversations with the business users. Often, Domain Knowledge is :-
  • Informal
  • Ill Structured
  • Incomplete
How is this kind of knowledge important ? What makes some of the IT companies & head hunters scourge for people with this kind of Domain Knowledge ?

Domain Knowledge is a key component in understanding :-
  • the problem space
  • the proposed solution
  • the slightly "bigger picture " - how the proposed solution formed a piece of the bigger puzzle.
Domain Knowledge is important as it helps you to communicate confidently with the business users in a particular domain. It helps you communicate to the business users in their language.

Example: if the users want to see a "tank", do they want to see an Armored Tank or a Septic Tank ?

You'd definitely be more confident in your solutions, if you knew precisely what the users expect to achieve from your solution - a few of these are :-
  • save time
  • co-ordinate better with their peers.
  • focus more on higher level activities after automating the trivial ones.
Domain Knowledge is also narrow - you may only focus on one minute part of a bigger piece in a huge puzzle. However, a good understanding of the minute part will serve as a foundation to explore the bigger piece & venture into the huge puzzle.

Example: if you are confident about your understanding of the Recruitment Loop ( contact - schedule interview - propose offer - recruit ), you could easily move into other functions such as Trend Analysis, Vendor Management, etc.

Example: if you are confident about your understanding of the HL7 Healthcare Messaging Protocol, you could comfortably move up to understanding Patient Demographics, etc.

Domain Knowledge is thus very helpful in understanding the needs of the business users better & providing solutions that closely match their needs.

I would definitely love to hear about different opinions on this topic.

Tuesday, March 11, 2008

Learn Programming in 10 Years


" Learn thoroughly whatever is to be learnt;
Then, let the conduct be worthy of this learning "


I just came across a wonderful article titled "Teach Yourself Programming in Ten Years" crafted by Peter Norvig. I would recommend the article for anyone looking at a career in the IT Industry.

It takes a lot of effort, discipline, sacrifice & experience to learn & understand a subject, let alone master it. An artifact that claims to offer a "shortcut" to learning in a particular subject in a very short time, is simply dubious in it's claim.

You may probably get an insight into the subject being discussed, but learning takes its own time. You my need to encounter many "aha!" moments to ultimately arrive at an understanding of a small part of the subject.

I feel that the books that claim - "learn x in y days/hours" are best to simply get a "foot in the door". You can get hooked to the topic and the books do justice in enticing your interest in the topics. I would recommend these books if you need to quickly get an outline of a subject and start work on it - and, probably plan to learn on the fly.

A good example is the software books with similar titles - you can quickly learn the syntax & replicate some of the code recipes shown in the book & achieve small-time victories.

However, if you are looking for a long term solution, there is no shortcut.

Many thanks to Thiruvalluvar and Peter Norvig !

Which Programming Language is good ?

"...One Ring to rule them all, One Ring to find them,
One Ring to bring them all and in the darkness bind them...."


The topic has been debated numerous times in the past, in various Forums, Newsgroups, mailing lists, coffee tables,etc. - but, it still goes on. The answer has always been the same - you need to choose the right tool for the right job. The mythical "Silver Bullet" does not exist & there will never be one.

You need to decide the tool to use for a particular job & use that tool correctly. It's no use trying to debate over the "best" language & these discussions are simply absurd.

I think this "old" article by Tim Daneliuk summarizes the thought process that goes on in these kind of debates.

Moral of the story : There is no Silver Bullet. There is no One Ring.

Monday, March 03, 2008

Pitfalls of JSF

Java Server Faces ( JSF ) is yet another Java Web Framework that promises to simplify the development of JEE-based web applications.

It deviates from the traditional "request-driven" approach adopted by MVC frameworks such as Struts & attempts to achieve the same with a component-driven model.

I am a fan of this Component-driven model & am still nostalgic about some of the work I did in Visual Basic, Oracle Forms, etc. many eons ago.

However, JSF, in its current version has a lot of pitfalls - some of the pitfalls are unique to JSF & drastically hinder the productivity gains that were promised in the JSF specification.

I was reading an interesting article on TheServerSide.com about the pitfalls of JSF . The article by Dennis Byrne was well written & covered some of the most important pain points in JSF.

I particular liked his last topic where he sympathizes with Portlet Developers. I found this sentence very emphatic :-

" I feel sorry for Portlet developers. I really do. These people are always on the mailing lists and forums with problem after problem and it's never their fault. If any group of people has been bent over by the standards bodies, it is Portlet application developers. "

Truly, a very good article that captures some burning issues that can keep a developer up all night.

Wednesday, February 27, 2008

God does exist

Another "gem" that I received in today's mail :-

A man went to a barbershop to have his hair cut and his beard trimmed. As the barber began to work, they began to have a good conversation. They talked about so many things and various subjects.

When they eventually touched on the subject of God, the barber said: "I don't believe that God exists."

"Why do you say that?" asked the customer. "Well, you just have to go out in the street to realize that God doesn't exist.

Tell me, if God exists, would there be so many sick people? Would there be abandoned children?

If God existed, there would be neither suffering nor pain. I can't imagine a loving God who would allow all of these things." The customer thought for a moment, but didn't respond because he didn't want to start an argument. The barber finished his job and the customer left the shop.

Just after he left the barbershop, he saw a man in the street with long, stringy, dirty hair and an untrimmed beard. He looked dirty and unkempt. The customer turned back and entered the barber shop again and he said to the barber:

"You know what? Barbers do not exist."

"How can you say that?" asked the surprised barber.

"I am here, and I am a barber. And I just worked on you!"

"No!" the customer exclaimed. "Barbers don't exist because if they did, there would be no people with dirty long hair and untrimmed beards, like that man outside."

"Ah, but barbers DO exist! That's what happens when people do not come to me."

"Exactly!" affirmed the customer. "That's the point! God, too, DOES exist!

That's what happens when people do not go to Him and don't look to Him for help.

That's why there's so much pain and suffering in the world."

The Hinderer

Another "gem" that I received in today's email :-

One day all the employees reached the office and they saw a big advice on the door on which it was written:

"Yesterday the person who has been hindering your growth in this company passed away. We invite you to join the funeral in the room that has been prepared in the gym".

In the beginning, they all got sad for the death of one of their colleagues, but after a while they started getting curious to know who was that man who hindered the growth of his colleagues and the company itself.

The excitement in the gym was such that security agents were ordered to control the crowd within the room.
The more people reached the coffin, the more the excitement heated up. Everyone thought: "Who is this guy who was hindering my progress? Well, at least he died!".

One by one the thrilled employees got closer to the coffin, and when they looked inside it they suddenly became speechless. They stood nearby the coffin, shocked and in silence, as if someone had touched the deepest part of their soul.

There was a mirror inside the coffin: everyone who looked inside it could see him/herself.

There was also a sign next to the mirror that said:
"There is only one person who is capable to set limits to your growth: it is YOU.
You are the only person who can revolutionize your life. You are the only person who can influence your happiness, your realization and your success. You are the only person who can help yourself.

Your life does not change when your boss changes, when your friends change, when your parents change, when your partner changes, when your company changes. Your life changes when YOU change, when you go beyond your limiting beliefs, when you realize that you are the only one responsible for your life.

"The most important relationship you can have is the one you have with yourself"
Examine yourself, watch yourself. Don't be afraid of difficulties, impossibilities and losses: be a winner, build yourself and your reality.

The world is like a mirror: it gives back to anyone the reflection of the thoughts in which one has strongly believed.

The world and your reality are like mirrors lying in a coffin, which show to any individual the death of his divine capability to imagine and create his happiness and his success.

It's the way you face Life that makes the difference

Tuesday, February 26, 2008

Different Attitude

Another "gem" that I received in today's mail :-

A Cold December night in West Orange, New Jersey. Thomas Edison's factory was humming with activity. Work was proceeding on a variety of fronts as the great inventor was trying to turn more of his dreams into practical realities. Edison's plant, made of concrete and steel, was deemed "fireproof". As you may have already guessed, it wasn't!

On that frigid night in 1914, the sky was lit up by a sensational blaze that had burst through the plant roof. Edison's 24-year-old son, Charles, made a frenzied search for his famous inventor-father. When he finally found him, he was watching the fire. His white hair was blowing in the wind. His face was illuminated by the leaping flames. "My heart ached for him," said Charles. "Here he was, 67 years old, and everything he had worked for was going up in flames. When he saw me, he shouted, 'Charles! Where's your mother?' When I told him I didn't know, he said, 'Find her! Bring her here! She'll never see anything like this as long as she lives.'"

Next morning, Mr. Edison looked at the ruins of his factory and said this of his loss: "There's value in disaster. All our mistakes are burned up. Thank God, we can start anew."

What a wonderful perspective on things that seem at first to be so disastrous. A business failure, personal dream gone sour . . . whether these things destroy an individual depends largely on the attitude he or she takes toward them. Sort out why it happened, and learn something from the blunders.

Think of different approaches that can be taken !

Monday, February 25, 2008

Soldier and the Spider

Another "gem" that I received in today's mail :-

During World War II, a US marine was separated from his unit on a Pacific island. The fighting had been intense, and in the smoke and the crossfire he had lost touch with his comrades.

Alone in the jungle, he could hear enemy soldiers coming in his direction.
Scrambling for cover, he found his way up a high ridge to several small caves in the rock. Quickly he crawled inside one of the caves. Although safe for the moment, he
realized that once the enemy soldiers looking for him swept up the ridge, they would quickly search all the caves and he would be killed.

As he waited, he prayed, Lord, if it be your will, please protect me.
Whatever your will though, I love you and trust you. Amen.
After praying, he lay quietly listening to the enemy begin to draw close.

He thought, well, I guess the Lord isn't going to help me out of this one.
Then he saw a spider begin to build a web over the front of his cave.

As he watched, listening to the enemy searching for him all the while, the spider layered strand after strand of web across the opening of the cave.

Hah, he thought. What I need is a brick wall and what the Lord has sent me is a spider web. God does have a sense of humor.

As the enemy drew closer he watched from the darkness of his hideout and could see them searching one cave after another. As they came to his, he got ready to make his last stand. To his amazement, however, after glancing in the direction of his cave, they moved on.

Suddenly, he realized that with the spider web over the entrance, his cave looked as if no one had entered for quite a while. Lord, forgive me, prayed the young man. I had forgotten that in you a spider's web is stronger than a brick wall.

We all face times of great trouble. When we do, it is so easy to forget the victories that God would work in our lives, sometimes in the most surprising ways.

Remember: Whatever is happening in your life, with God, a mere spiders web can become a brick wall of protection. Believe He is with you always and you will see His great power and love for you.

Network Troubleshooting - 6 : Application Issues

I believe that after eliminating the possibilities of problems at the previous steps, the only remaining option at this step is to troubleshoot the application. You may need to scrounge through log files, check application consoles, etc.

However, the possibility of a problem occurring due to the underlying network is extremely minimal at this level - even if it does, it's probably due to some idiosyncrasies of the Operating System or the Application Platform.

Network Troubleshooting - 5 : NETSTAT

You need to now move on to the Remote System & check if the program / process is listening on a particular port that you are trying to connect to.

Netstat (network statistics) is a command-line tool that displays network connections (both incoming and outgoing), routing tables, and a number of network interface statistics.

- Wikipedia


You can use the simple NETSTAT command on the remote system to check the open Network ports, active connections, etc . You just need to open a Command Prompt ( Terminal in LINUX ) & type :-

( LINUX )

netstat -an | grep port_name

OR

( WINDOWS )

netstat -an | findstr port_name

You should see a bunch of Network statistics like this :-

TCP 0.0.0.0:1521 0.0.0.0:0 LISTENING
TCP 127.30.22.11:1521 10.177.239.210:2527 ESTABLISHED
TCP 127.30.22.11:25271 10.177.239.210:1521 ESTABLISHED
TCP 127.30.22.110:28802 10.177.145.53:1521 ESTABLISHED


If you don't get this response, you can conclude on these :-

1. The program / process on the remote system that should be "listening" on the port is not running.

Now, it's time to call up the IT Help Desk & tell them that there's a problem with Network Access.

At the end of this exercise, you have :-

* tried some basic troubleshooting steps.
* identified the source of the problem.
* communicated effectively to the IT Support Staff.

You can now confidently communicate with the IT Support Staff & they'd be more than happy to work with an "educated" colleague.

Network Troubleshooting - 4 : TELNET

A TCP/IP standard for remote terminal connection to another machine.

- Wikipedia


You can use the simple TELNET command to ensure that you can communicate with the remote system, by opening a connection to a port on the remote system. You just need to open a Command Prompt ( Terminal in LINUX ) & type :-

telnet ip_address port

OR

telnet hostname port

You should see a blank screen that allows you to type commands.

If you don't get this response, you can conclude on these :-

1. The program / process on the remote system that should be "listening" on the port is not running.
2. The remote system is protected by a "firewall" that's preventing access.

Now, it's time to call up the IT Help Desk & tell them that there's a problem with Network Access.

At the end of this exercise, you have :-

* tried some basic troubleshooting steps.
* identified the source of the problem.
* communicated effectively to the IT Support Staff.

You can now confidently communicate with the IT Support Staff & they'd be more than happy to work with an "educated" colleague.

Network Troubleshooting - 3 : PING

Ping!

Ping is a computer network tool used to test whether a particular host is reachable across an IP network.

- Wikipedia


You can use the simple PING command to ensure that you can communicate with the other system. You just need to open a Command Prompt ( Terminal in LINUX ) & type :-

ping ip_address

OR

ping hostname

You should see a reply from the Network Card like this :-

Pinging sandeep-personal [127.0.0.1] with 32 bytes of data:

Reply from 127.30.22.11: bytes=32 time 1ms TTL=128
Reply from 127.30.22.11: bytes=32 time 1ms TTL=128
Reply from 127.30.22.11: bytes=32 time 1ms TTL=128
Reply from 127.30.22.11: bytes=32 time 1ms TTL=128

If you don't get this response, you can conclude on these :-

1. Your system is not connected to the same network as the remote system.
2. The remote system is not connected to the same network as your system.
3. Your system / the remote system is protected by a "firewall" that's preventing access.

Now, it's time to call up the IT Help Desk & tell them that there's a problem with Network Access.

At the end of this exercise, you have :-

* tried some basic troubleshooting steps.
* identified the source of the problem.
* communicated effectively to the IT Support Staff.

You can now confidently communicate with the IT Support Staff & they'd be more than happy to work with an "educated" colleague.

Revision Control for Rows

Revision Control deals with managing multiple revisions of an entity. The core functionality in any Revision Control system is to ensure that the previous version is not lost. Revision Control is a vast topic that merits hours of study & practice.

I definitely don't have the breadth of knowledge or experience to comment on various "must-have" features, etc. However, I did encounter an interesting scenario where I put Revision Control to practice for information stored in rows of a Database Table.

We can achieve Revision Control for rows in a Database Table in a simple way - with two columns. We can use one column to store the Row version and another to "flag" the row that contains the latest version.

I am using an Oracle XE Database & Oracle SQL Developer to model the tables, fashion out the queries, etc. You could do the same with any other Database & your favorite tools.

Here, I consider the example of an Item "on display" at a shop. The Product is available in multiple version ( different colors ), but only one "version" of the product is currently on display ( the item ).

First, I'll model the database table. I have made a few assumptions to arrive at this model :-

Assumption # 1 :- All the rows are linked by a common identifier ( in my case, the Product ID ).
Assumption # 2 :- At any given point of time, only one version of the product is "active".
Assumption # 3 :- Each "version" is saved into the database. Any "undo" will simply revert back to the previous saved version.
Assumption # 4 :- Each "undo" or "redo" is saved into the database as the current version.

Here's a table that shows this design :-

CREATE TABLE ITEM
(
ITEM_ID NUMBER PRIMARY KEY,
ITEM_PRODUCT_ID NUMBER,
ITEM_DESCRIPTION VARCHAR2(100),
ITEM_COLOR VARCHAR2(10),
ITEM_VERSION NUMBER,
ITEM_CURRENT_VERSION VARCHAR2(1) CONSTRAINT check_ver_flag CHECK(ITEM_CURRENT_VERSION IN ('Y','N'))
);


Here's the data that I stuffed into the table :-

INSERT INTO ITEM VALUES (1,566,'Smiley Dolls','Red',1,'N');
INSERT INTO ITEM VALUES (2,566,'Smiley Dolls','Blue!',2,'N');
INSERT INTO ITEM VALUES (3,566,'Smiley Dolls','Yellow',3,'Y');
INSERT INTO ITEM VALUES (4,566,'Smiley Dolls','Cyan',4,'N');

COMMIT;


Now, to dish out the queries...

Which is the current version of the Product ?

SELECT ITEM_DESCRIPTION, ITEM_COLOR FROM ITEM WHERE ITEM_CURRENT_VERSION = 'Y';

ITEM_DESCRIPTION ITEM_COLOR
------------------- ----------
Smiley Dolls Yellow

1 rows selected


Can we "undo" the current version & revert to the previous saved version ?

SELECT a.ITEM_DESCRIPTION, a.ITEM_COLOR FROM ITEM A, ITEM B
WHERE A.ITEM_VERSION = B.ITEM_VERSION-1 AND B.ITEM_CURRENT_VERSION = 'Y'


ITEM_DESCRIPTION ITEM_COLOR
----------
Smiley Dolls Blue!

1 rows selected


( After this, we set the current version flag to "Y" )

Revision Control can be achieved in this simple manner.

Sunday, February 24, 2008

Parent Child Relations in a Database Table

Parent - Child relationships ( hierarchical relationships ) are very common & often crop often during database designs.

You can expect to find Parent -Child relationships while modeling employee-manager, office-outlets & other similar concepts. I recently encountered the need for a parent - child relationship in a need to model a product-sub product concept.

You can find a lot of literature that talks about this topic in detail. I just want to add my 2 cents..

The hierarchical relationships are best explained by examples. Here, I consider a popular fast food chain of outlets ( "Yummies" ) that has outlets across the city.
Al the outlets in a particular part of the city "report" to a single outlet - the "parent" outlet.

All these "parent" outlets in turn "report" to a single "parent" outlet - something like a "head office".

The "report"s could be anything - daily sales figures, inventory status, customer feedback, staff shortages, etc. However, at this point of time, the main focus is to model the relationship of a parent-child outlet chain.

I am using an Oracle XE Database & Oracle SQL Developer to model the tables, fashion out the queries, etc. You could do the same with any other Database & your favourite tools.

First, I'll model the database table. I have made a couple of assumptions to arrive at this model :-

Assumption #1 : Each child outlet has a single parent outlet.
Assumption #2 : Each outlet has a parent outlet, except the "root" outlet ( head office ) .

Here's the table structure that I have designed :-

CREATE TABLE OUTLET
(
OUTLET_ID NUMBER PRIMARY KEY,
OUTLET_NAME VARCHAR2(30) NOT NULL,
OUTLET_PARENT NUMBER
);


The OUTLET_ID of the "parent" outlet is stored in the "child" outlet's OUTLET_PARENT.

Here's the data I stuffed into the table :-

INSERT INTO OUTLET VALUES(1,'Yummies M G Rd',null);
INSERT INTO OUTLET VALUES(2,'Yummies BSK ',1);
INSERT INTO OUTLET VALUES(3,'Yummies BSK I Stage ',2);
INSERT INTO OUTLET VALUES(4,'Yummies BSK II Stage ',2);
INSERT INTO OUTLET VALUES(5,'Yummies BSK III Stage ',2);
INSERT INTO OUTLET VALUES(6,'Yummies Food World ',3);

COMMIT;


Now, to dish out the queries...

Which outlet is the "mother of all outlets" ? ( root outlet / head office )

The outlet that has no parent ( OUTLET_PARENT is null ) is the "mother of all outlets".

SELECT * FROM OUTLET WHERE OUTLET_PARENT IS NULL;

OUTLET_ID OUTLET_NAME OUTLET_PARENT
--------- ------------------ ---------------
1 Yummies M G Rd


1 rows selected

Which are the outlets under the root outlet ?

SELECT
a.outlet_id,
a.outlet_name,
a.outlet_parent,
b.outlet_parent
FROM outlet a,
outlet b
WHERE b.outlet_id = a.outlet_parent
AND b.outlet_parent IS NULL;


OUTLET_ID OUTLET_NAME OUTLET_PARENT OUTLET_PARENT_1
--------- ------------------ --------------- ---------------
2 Yummies BSK 1


I can now dish out various queries that involve parent-child relationships on the chain of outlets.

The model described above works best only if the two critical assumptions are satisfied. If not, you may need to explore alternate ways to achieve this relationship - e.g.: moving the relationship data ( OUTLET_ID, OUTLET_PARENT) to a separate table, etc.