Wednesday, August 28, 2013

TOPIC 2: LOGIC BUILDING USING PSEUDO CODE

2.1 Flowchart and Pseudo Code

Assignment 2.1.1: Problem Solving through flowchart

Problem Description: Draw a flowchart for the following problems:

1. Add first N even numbers

SOLUTION : 


flowchart to show addition of first 'n' even numbers


2.   Add first n odd numbers

SOLUTION :


Flowchart showing addition of first 'n' odd numbers


3.  Find maximum of three numbers

SOLUTION :


Flowchart showing maximum of three numbers


4. Determine whether a year s leap year or not

SOLUTION :


Flowchart showing whether a year is leap year or not

5. Input a number and check whether it is prime or not

SOLUTION :


Flowchart showing whether a number is prime or not


6. Input a number and check whether it can be expressed as some positive integer power of 2. For example 2,4,8,16,32… etc. can expressed as some positive integer power of 2 like 2^1,2^2,2^3,2^4, and 2^5……..

SOLUTION : 


Flowchart expressing a number as power of 2

Monday, August 26, 2013

INFOSYS FOUNDATION TRAINING PROGRAM (FTP) SOLUTION FOR LAB-GUIDE ASSIGNMENT PROBLEM SOLVING AND LOGIC BUILDING- part-2

TOPIC 1 : COMPUTATIONAL PROBLEM SOLVING

1.1 COMPUTATIONAL PROBLEM SOLVING AND ALGORITHM

ASSIGNMENT 1.1.1 : PROBLEM SOLVING EXERCISES ( part-b )


1. In an objective type programming contest, following are the rules

a. It will have multiple rounds.

b. In each round, every participant will get a set of 10 question out of which
one question is marked as star question (The toughest one).
c. The participant will get the next set, only if 50% of the questions are
marked correctly in the previous round or he attempted the star question
correctly. Otherwise he will be out of the contest.
It is found that in each round 50% of the participants are not able to attempt 50%
of the questions correctly but one out of those 50% participants, attempts the
star question correctly.
If only 4 participants are left for the 5th round what was the number of
participants in the first round?

SOLUTION :

Let the students appeared for 1st round be = x

Students appearing for the 2nd round :
Since half of them made for the 2nd round, which constitute = x / 2
and 1 candidate who attempted star question
So, total students who made for the 2nd round are = x/ 2 + 1 = (x + 2)/ 2

Students appearing for the 3rd round :
Since half of the previous round students made for the 3rd round, which constitute = ( (x + 2)/ 2 )/2
and 1 candidate who attempted star question
So, total students who made for the 2nd round are =  ( (x + 2)/ 4 ) + 1 = (x + 6)/ 4

Students appearing for 4th round :
Since half of the previous round students made for the 3rd round, which constitute = ( (x + 6)/ 4 )/2
and 1 candidate who attempted star question
So, total students who made for the 2nd round are =  ( (x + 6)/ 8 ) + 1 = (x + 14)/ 8

Students appearing for 5th round :
Since half of the previous round students made for the 3rd round, which constitute = ( (x + 14)/ 8 )/2
and 1 candidate who attempted star question
So, total students who made for the 2nd round are =  ( (x + 14)/ 16 ) + 1 = (x + 30)/ 16


Since it is given that the number of students appeared for the 5th round are =  4

This implies the expression we got for the 5th round i.e. (x + 30)/ 16 becomes = 4
i.e.                                                   (x + 30)/ 16 = 4
                                                         (x + 30 ) = 64
                                                            x = 64 - 30
                                                               x = 34

Since we assumed ' x ' to be the number of students present during the 1st round, which came out to be = 34. It means there were total of 34 students present in the 1st round.


2. A farmer had a lazy son. The farmer wanted his son to work in the farm. So he offered that the son will work for 50 days, for each day the son works, he will get 10 rupees, for each day he will not work, he need to pay back 15 rupees to his father. At the end of 50 days, when the son counted his income, it turned out that he had not got anything. How many days did the son actually worked?

SOLUTION :

Let the son worked for =  x days
money earned for x days = 10x

No. of days on which he didn't work = (50 - x)
Money he lost for days he didn't work = 15 ( 50 - x )

It is given in that the money he earned balances the money he paid back, which means :

                                                      10x = 15 ( 50 - x )
                                                       10x = 750 - 15x
                                                            25x = 750
                                                           x = 750/25
                                                              x = 30
Since we assumed ' x ' to be the number of days for which son worked, which came out to be = 30 days. Therefore, Son worked for 30 days.

INFOSYS FOUNDATION TRAINING PROGRAM (FTP) SOLUTION FOR LAB-GUIDE ASSIGNMENT PROBLEM SOLVING AND LOGIC BUILDING

TOPIC 1 : COMPUTATIONAL PROBLEM SOLVING

1.1 COMPUTATIONAL PROBLEM SOLVING AND ALGORITHM

ASSIGNMENT 1.1.1 : PROBLEM SOLVING EXERCISES

1 . The King ordered his servants to fill up his treasury. Each of the 3 servants, had to go to the treasury, count how much gold coins there was at that moment, and then triple it and leave. But then the King felt sorry for them and thought that he should probably reward the servants in some way, so he let each of them take 1 gold coin out before leaving. Once again the King had a good luck. He collected exactly 500 gold coins in the treasury. How much gold coins did he have before the order.

SOLUTION

Let initially coins be = x
a servant has to make thrice of them, which means, coins should be = 3x
and a servant is allowed to take 1 coin, which leave the total coins to =  ( 3x - 1 )

Next servant comes and does the same thing of making the count of coins to 3-times, which makes the present count to =                      3 ( 3x - 1 )
and when he take 1-coin out , then the present count becomes =  ( 3 ( 3x - 1 ) - 1 )

Finally the 3rd servant comes and make the present count to thrice again making it = 
3 ( 3 ( 3x - 1 ) - 1 )
and when he also takes 1-coin out, the total count becomes = ( 3 ( 3 ( 3x - 1 ) - 1 ) -1 )

At last, it was found that the total count of the coins = 500

which means our expression 3 ( 3 ( 3x - 1 ) - 1 ) -1 ) = 500

solving this expression step by step :
                                                  ( 3 ( 9x - 3 - 1) - 1 ) = 500
                                                    27x  - 12 - 1  = 500
                                                           27x -13 = 500
                                                             27x = 513
                                                             x = 513 / 27
                                                                x = 19
since ' x ' is the number of coins initially present in the treasury. It means 19 coins were initially present in the treasury.
                                                    

2. John decided to start working. He was hired on the following terms: during 30 days, for each day John works, he gets 6 dollars, for each day he doesn't work,he pays back 9 dollars. At the end of the month, when they counted his wages, it turned out that he had not got anything. How many days did John actually work?


SOLUTION :

Let the number of days for which Jhon worked be = x
This implies, the number days for which Jhon didn't work = 30 - x

Jhon gets 6 $ for each day he works
therefore, his total wages for his working days become = 6x

Jhon has to pay back 9 $ for the day he don't work
therefore, he has to pay back total of = 9( 30 - x )

Since Jhon gets nothing at the end of the month as the money he has to pay back balances the money he earned, which means : 

                                                              6x = 9( 30 - x )
                                                              6x = 270 - 9x
                                                                15x = 270
                                                                x = 270 / 15
                                                                   x = 18
Since, we assumed ' x ' to be the number of days for which Jhon worked, and it comes out to be 18 days for which Jhon worked for the company.
                                 


3. Smith's boss proposed to pay him in the following way: "See, there is some money in the purse. Every day I'll add 5 dollars to it, and then you'll take out half of what's in it”. Three days later it turned out that there were6 dollars left in the purse. How much did Smith get for three days' work ?

SOLUTION :

Let the amount of money present in the purse initially be = x
1st day The boss added 5 $ to the purse and the total amount becomes = x + 5
The employee took half of the total amount , which means, he took = ( x+ 5 ) / 2.............(i)
Money left behind in the purse = (x + 5 ) - ( x + 5 ) /2

2nd day The boss added 5 $ again to the purse, which makes the total amount present in the purse to   = 5 + ( x + 5 )/ 2  =  (10 + x + 5) / 2 =   ( x + 15 )/ 2
The employee took half of the amount present in the purse , which means, for this time, he took-
( x + 15 )/ 2*2 = ( x + 15 )/ 4................................(ii)
Money left behind in the purse = ( x + 15 )/ 2 -  ( x + 15 )/ 4 = ( x + 15 )/ 4

3rd day The boss added 5 $ again to the purse, which makes the total amount present in the purse to  = 5 + ( x + 15 )/ 4 = ( x + 35 ) / 4
The employee took half of the amount present in the purse , which means, for this time, he took-
( x + 35 ) / 4 *2 = ( x + 35 ) / 8..............................(iii)
Money left behind in the purse =  ( x + 35 ) / 4 - ( x + 35 ) / 8 = ( x + 35 ) / 8

Since money left in the purse on 3rd day = ( x + 35 ) / 8
and it is given that on 3rd day money present in the purse = 6 $
which means :
                                                           ( x + 35 ) / 8 = 6
                                                               x + 35 = 48
                                                                    x = 13

Since, we assumed ' x ' as the money present in the purse initially, which means there were 13 $ present in the purse initially.

We've to find out the amount earned by the employee on 3rd day, which we can calculate by adding (i), (ii) and (iii) expressions above  as :

                           ( ( x+ 5 ) / 2 )   +   ( ( x + 15 )/ 4 )      +    ( ( x + 35 ) / 8 )
Putting 13 in place of x, we get the expression as :
                           ( ( 13 + 5 ) / 2 ) +  ( ( 13 + 15 ) / 4)   +   ( ( 13 + 35 ) / 8) 
                                       ( 18/ 2 )   +      (28 / 4 )    +     (48 / 8 )
                                                             9 +  7 +  6
                                                                   22


This implies the total of 22 $ earned by the employee. and If we see the amount only for 3rd day, it comes out to be : ( x + 35 ) / 8 =  ( 13 + 35 ) / 8  =    (48 / 8 )  =    6


4. Two friends who have an eight-quart jug of water wish to share it evenly. They also have two empty jars, one holding five quarts, the other three. How can they each measure exactly 4 quarts of water ?

SOLUTION : 

Step-1:
First of all water from 8-quart jug is poured into 3-quart jar, so now the values are :
8-quart jug = 5-quart water
3-quart jar = 3-quart water
5-quart jar = 0-quart water

Step-2 :
Now, water from 3-quart jar is poured into 5-quart jar, so now the values are :
8-quart jug = 5-quart water
3-quart jar = 0-quart water
5-quart jar = 3-quart water

Step-3:
Now again, water from 8 quart jug is poured into 3-quart jar, so now the values are :
8-quart jug = 2-quart water
3-quart jar = 3-quart water
5-quart jar = 3-quart water

Step-4:
Now, water from 3-quart jar is poured into 5-quart jar, Notice this time, since the 5-quart jar is left with only 2-quarts of capacity, therefore, 3-quart jar will be able to pour only 2-quarts of water, leaving 1-quart behind. So now the values are :
8-quart jug = 2-quart water
3-quart jar = 1-quart water
5-quart jar = 5-quart water

Step-5:
Now, the whole of water from 5-quart jar is poured back into 8-quart jug, which will set the values to :
8-quart jug = 7-quart water
3-quart jar = 1-quart water
5-quart jar = 0-quart water

Step-6:
Now, pour the water from 3-quart jar into 5-quart jar, making the values to :
8-quart jug = 7-quart water
3-quart jar = 0-quart water
5-quart jar = 1-quart water

Step-7:
Now again, fill the 3-quart jar by pouring water from 8-quart jug, making the values to :
8-quart jug = 4-quart water
3-quart jar = 3-quart water
5-quart jar = 1-quart water

Step-8:
Now, fill this 3-quart of water from 3-quart jar to 5-quart jar, and see it yourself that we have successfully divided  8-quarts of water into equal halves, so that both friends can get exactly 4-quarts of water. And the values can finally be seen as :
8-quart jug = 1-quart water
3-quart jar = 3-quart water
5-quart jar = 4-quart water 


5. The bin packing problem is an example of a wide set of problems. The task is to find how many set sized bins are required to hold a number of differently sized boxes. How many bins (10 units high) are required to contain the following boxes (1,3,4 and 5 units high) ?

SOLUTION :

Since, we've to put 1,3,4 and 5 units high boxes into 10 units high bins.
As can be seen, we can put 
1.)      1,4 and 5 units high boxes into 10 units high bin( all these boxes completely fit into bin w/o leaving any space behind )
2.)   Now we're left with only 3 unit high  box, which we've to put it into another 10 unit high bin, as we've no other option.

Friday, August 23, 2013

PACKAGES IN JAVA

WHAT ARE PACKAGES IN JAVA ?

When making any project in java, the project may constitute large number of classes and interfaces which are assigned to different development teams to code them. They place classes and interfaces having same category into packages. Packages are nothing but named directory /folder, where programmers keep classes and interfaces of same functionality.
e.g.
Suppose, you've made different classes such as :
Lion
Tiger
Peacock
Vulture
Car
Bus
We can easily sense some kind of similarities among certain classes, such as:
Lion and Tiger are ANIMALS
Peacock and Vulture are BIRDS 
Car and Bus are VEHICLES
Instead of keeping all these classes together, we would surely like to categorize classes of similar types together for well organization.
Therefore, we would put classes Lion and Tiger in ANIMAL PACKAGE.
Peacock and Vulture in BIRDS PACKAGE
Car and Bus in VEHICLES PACKAGE


HOW DO WE CREATE PACKAGE IN JAVA ?

When we create a class, we start by writing e.g.

public class <name_of_class> {
Data Members
/ / / / / / / / / / 
/ / / / / / / / / 
Methods
/ / / / / / / / / 
 / / / / / / / 
}

So, we want the above class to belong to some package, we just have to write the 'package' keyword with a appropriate name given to that package as the first line of the program.

e.g.

package  <name_of_package>;
public class <name_of_class> {
Data Members
/ / / / / / / / / / 
/ / / / / / / / / 
Methods
/ / / / / / / / / 
 / / / / / / / 
}

NOTE : if we want our class to belong to some package, then we must begin our program with the package keyword and the name of the package as 1st line of the program.
By doing this, a directory / folder gets created of the same name as that of package, in which our class get stored.

WHAT ARE SUB-PACKAGES IN JAVA ?

As name itself indicates, it is just another package inside the package.Lets take a scenario to understand the concept of sub-packages. Suppose we created a package called ANIMALS
and we have made classes such as :
Lion
Tiger
Peacock
Eagle
Salmon
Shark
It is absolutely clear that all the above classes are animals, but, if we look further, then we can sense that:
Lion and Tiger are NON-FLYING ANIMALS
Peacock and Eagle are FLYING ANIMALS
Salmon and Shark are SEA ANIMALS
Therefore, there arises a need to categorize them further. In-order to deal with this situation we need to put them in packages further, and all these newly formed packages will go into ANIMAL PACKAGE.

Now, ANIMAL PACKAGE Contains 3 SUB-PACKAGES namely :
NON-FLYING ANIMALS ( containing classes : Lion and Tiger )
FLYING ANIMALS ( containing classes : Peacock and Eagle )
SEA ANIMALS ( containing classes : Salmon and Shark )

HOW DO WE CREATE SUB-PACKAGES IN JAVA ?

Suppose we have classes Tiger and Eagle. We know that both of these are animals, but at the same time both belong to a different category. Tiger belongs to Non flying category and Eagle belongs to Flying category. So, we need to put these classes into different sub-packages, and to do that, we begin the class code with 'package' keyword then name of the package then period(a dot) then the name of the sub-package. 
e.g.

package animals.non_flying_animals;
public class Tiger {
/ / / / /
 / / / 
}
By doing so, the class Tiger will get stored in directory / folder structure:  animals / flying_animals

To put Eagle class in another sub-package, we would insert tha package statement as :

package animals.flying_animals;
public class Eagle {
/ / / / /
 / / / 
}

By doing so, the class Eagle will get stored in directory / folder structure as :
animals / flying_animals

NOTE : i) the name of the package should start with a small case.
ii) the name must not contain blank spaces in between as in 'non flying animals', rather it should be written as 'non_flying_animals'.

INTRODUCTION TO ALGORITHMS

WHAT IS AN ALGORITHM ?

An algorithm is a s What tep by step approach to solve any computational problem.

PROPERTIES OF AN ALGORITHM

1.) FINITENESS : An algorithm must have finite number of steps, because if it has infinite number of steps(endless) then its of no use as it would never produce any expected output.
2.) DEFINITENESS : An algorithm must be definite in nature i.e. all the steps must be unambiguous.
3.) INPUT : An algorithm must at-least take an input to work on.
4.) OUTPUT : An algorithm must produce at-least one or more outputs as final result.

ALGORITHM DESIGN TECHNIQUES

There are several approaches which are followed to have a computational solutions. These approaches are as follows :
1.) BRUTE FORCE TECHNIQUE : in this technique, all the available attempts are made to get a perfect solution for the existing problem. An analogy can be made with locker, where all the combinations are tried to open the locker.
2.) DIVIDE AND CONQUER : in this technique, a problem is divided into small modules and for each of those modules solutions are found recursively, which are further integrated to get the final desired output desired.
3.) GREEDY METHOD : in this technique, the easiest solution is tried to be found out. An analogy can be made with the popular travel salesman problem, in which a sales man has to travel several cities and his target is to choose such a path which cost him least and he doesn't have to repeat any city which he has already travelled. The solution to this kind of problem lies in selecting the shortest path which connects all cities. This kind of approach is followed in greedy methods.
4.) DYNAMIC PROGRAMMING : it is a design technique, in which a problem is divided into sub-problems and the subproblems are in turn dependent on each other for their solutions. The perfect example for this is the Fibonacci series, in which the subsequent number is found by adding the previous two numbers. e.g.
0,1,1,2,3,5,8,1,3,2,1             
  

Wednesday, August 7, 2013

CONVERTING ER DIAGRAMS TO RELATIONAL DATABASE

An example of converting ER diagram to Tables

Here we've an image showing an ER-diagram :
ER-diagram
ER-diagram
Our target is to implement this ER-diagram into SQL code, make tables and establish relationships between tables, satisfying the ER-diagram.

Below given are the CREATE TABLE statements, which are used to implement the above given ER-diagram.


1) Department table :
create table department
 (dept_id number not null primary key, 
  dept_name varchar2(15) not null
 );

2) Branch table
create table branch
 (branch_id varchar2(5) not null primary key, 
  electives varchar2(10),
  dept_id number not null,
  constraint Department_Has_Branches
    foreign key (dept_id)
    references department(dept_id)
 );

3) Course table:
create table course
 (course_id number not null primary key,
  course_name varchar2(10) not null,
  branch_id varchar2(5) not null,
  constraint Branch_Offers_Courses
    foreign key (branch_id)
    references branch(branch_id)
 );

4) Student table:
create table student
 (stud_id number not null primary key, 
  stud_name varchar2(30) not null,
  branch_id varchar2(5) not null,
  constraint Student_BelongsTo_Branch
    foreign key (branch_id)
    references branch(branch_id)
 );

5) Applicant table:
create table applicant
 (app_id number not null primary key,constraint Student_SelectedAs_Applicant foreign key (app_id) to Student table
references student(stud_id)
);

6) applicant_AppliesFor_branch Table :
create table applicant_AppliesFor_branch
 (app_id number not null, 
  branch_id varchar2(5) not null,
  primary key (app_id, branch_id),
  constraint Student_AppliesFor_Branch
    foreign key (app_id)
    references applicant(app_id),
  constraint Branch_AppliedBy_Student
    foreign key (branch_id)
    references branch(branch_id)
);

Sunday, August 4, 2013

SOLVED SQL QUERIES FROM INFOSYS LAB ASSIGNMENT part 1 of RDBMS

SQL queries based on Aggregate functions :


1. List branchid and the number of courses offered by each branch.

2. List branchid and the number of electives offered in each branch.

3. List instructorid and number of different courses offered by those instructors.
4. List the total strength of students staying in each Hostel.
5. List courseid and number of students registered in each course.
6. Count the number of students currently studying in branch B2.
7. Find the details of the total allocated hours for every branch.
8. List the instructorid who has taken at least 2 courses.

Inorder to solve the above queries, we would require several tables and the structure of those required tables to solve problems are as follows :

1. Course(course_id, course_name, semester, branch_id, electives, duration_hrs, all )
2. Instructors( inst_id, course_id )
3. Hostels( hostel_id, stud_id )
4. Registration( course_id, stud_id )
5. Student( stud_id, branch_id )

Solutions :

Query 1 :
List branchid and the number of courses offered by each branch.
Let's populate the 'course' table as follows: 
Course table
Course table



So, we are asked to list branch_ids and the number of courses associated with it. 
e.g. as can be seen in the table, 

  • B1 offers two courses( i.e. 101 and 103 )
  • B2  also offers two courses( i.e. 102 and 104 )
It is pretty much clear that we require to retrieve two columns : 
  1) branch-id
  2) number of courses
As it is clear by looking at the table, we can't retrieve the 'number of columns' directly from the 'course' table, therefore, in-order to achieve that, we've to use aggregate function COUNT() clause on 'course_id' column, which will count the number of courses associated with one brach_id and give us the number of courses.

Another thing is that, we've to group the retrieved data, in-order to prevent repetition of data. 
e.g. 'B1' comes twice in the 'branch_id' column
and 'B2' also comes twice in the 'branch_id' column
Therefore, to prevent this repetition in our retrieved data, we use GROUP BY clause  .

SQL code :
SELECT branch_id, COUNT(course_id) AS number_of_students FROM course GROUP BY branch_id;

-------------------------------------------------------------------------------------------------------------------------------

Query 2 :
List branchid and the number of electives offered in each branch.
This case is almost similar to the solution of Query 1, as now, we've to see for electives associated with branch_ids.
Course Table
Course Table


CAUTION : the course_id values were unique in every row, but its not case with electives. We can see repeated values under 'electives' columns. Here in-order to  prevent repetition of values , we'll use DISTINCT keyword.

SQL code :

SELECT branch_id, COUNT(DISTINCT electives) AS elective_subjects FROM course GROUP BY branch_id;

----------------------------------------------------------------------------------------------------------------------------------



Query 3 :
List instructorid and number of different courses offered by those instructors.
We've 'instructors' table as follows :
Instructor Table
Instructor Table
 As can be clearly seen in the table, an instructor can have more than one course_ids associated with him and that's what we are asked to solve in query. i.e. we've to retrieve the instructor_id and the number of course_ids associated with him.

SQL code:
SELECT inst_id, COUNT( course_id) FROM instructors GROUP BY inst_id;

-----------------------------------------------------------------------------------------------------------------------------------

Query 4 :
List the total strength of students staying in each Hostel.
                                   __________________________________
We've to use table : | hostels( hostel_id, stud_id ) |
                                ---------------------------------------
--------------------------------------
hostel_id     |     stud_id       |
--------------------------------------
     H1          |       401          |
     H1          |       402          |
     H2          |       403          |
     H3          |       405          |
     H3          |       406          |
--------------------------------------

As can be seen in the table, there can be more than one students in the same hostel, and that's what we are asked to find the number of students in each of the present hostel. Therefore, we'll put the 'stud_id' in the COUNT() aggregate function, which will give us the total number of students. And we'll use GROUP BY clause to group hostels.

SQL code :
SELECT hostel_id, COUNT( stud_id ) AS total_students FROM hostels GROUP BY hostel_id;

-----------------------------------------------------------------------------------------------------------------------------------

Query 5 :
List courseid and number of students registered in each course.

We've to use another table named Registration :
---------------------------------------
course_id    |      stud_id       |
---------------------------------------
     101        |         401          |
     101        |         402          |
     102        |         401          |
     103        |         404          |
     104        |         405          |
     104        |         406          |
---------------------------------------
As can be seen in the above table, more than one student can pursue same course. It means, with single course_id, there can be many stud_id associated with it. And that's what we are asked to find, i.e. group by the course_ids and number of students associated with those course_ids.

Also, it can be seen, that a student can pursue more than one course at a time, as student with stud_id 401 is pursuing two courses with course_id 101 and 102.

SQL code:
SELECT course_id, COUNT( stud_id ) FROM Registration GROUP BY course_id;

------------------------------------------------------------------------------------------------------------------------------------

Query 6 :
Count the number of students currently studying in branch B2.

We've to use table named Student :
---------------------------------------

stud_id       |      branch_id    |
---------------------------------------
     401        |         B1            |
     402        |         B2            |
     403        |         B2            |
     404        |         B4            |
     405        |         B2            |
     406        |         B3            |
---------------------------------------
This is almost similar to previous problem, as we are asked to find how many students took branch_id B2. It can be clearly seen from that there are 3 students who took branch_id B2.

SQL code :
SELECT COUNT( stud_id ) FROM Student WHERE branch_id = 'B2';

------------------------------------------------------------------------------------------------------------------------------------

Query 7 :
Find the details of the total allocated hours for every branch.
We've to use table named 'course' as given follows :
Course Table
As can be seen, total hours for branch_id B1 are 48  +  52
So, we have to use SUM() aggregation function on column duration_hrs.

SQL code :
SELECT branch_id, SUM( duration_hrs ) AS total_duration FROM course GROUP BY branch_id;

------------------------------------------------------------------------------------------------------------------------------------

Query 8 :


List the instructorid who has taken at least 2 courses.

Here, we have to use instructors table :
Instructor Table
Instructor Table
It can be seen in the table that instructor with inst_id 1001 takes two courses with course_id 101 and 102. And we are asked to find those instructors those who have taken atleast two courses.

NOTE : since we have to use aggregate function COUNT(course_id ) in-order to count the number of courses associated with one instructor. So, it's a fact the counting is done at the run-time of SQL code, which means value is not already present anywhere in the table.
And we have a condition that we must display only those instructors who has taken at-least 2 courses.
This condition can be applied using 'HAVING' clause.
Some of you may argue, Why can't we use 'WHERE' clause as a conditional test ?
'WHERE' clause is always used for the already present columns of the table, whereas, 'HAVING' clause is used for the aggregate functions.

One thing to note is that any column name appearing in the HAVING clause must also appear in the GROUP BY clause.

SQL code :
SELECT inst_id, COUNT( course_id) AS total_courses FROM instructors GROUP BY inst_id HAVING COUNT(course_id) >= 2;

-----------------------------------------------------------------------------------------------------------------------------------

Strange Behaviour of 'GROUP BY' clause when used without 'ORDER BY' clause

Using GROUP BY clause without using 'ORDER BY' clause

 A table named HOSTEL(hostel_no NUMBER, no_of_stud NUMBER)  is created and populated with values as follows : 
--------------------------------------
hostel_no|     no_of_stud     |
--------------------------------------
1001       |             124          |
1001       |             234          |
1002       |               97          |
1002       |             134          |
1003       |             234          |
1004       |             123          |
1004       |               89          |
1001       |               67          |
-------------------------------------

When GROUP BY command is applied as : 
SELECT hostel_no, sum(no_of_stud) as total_students FROM
HOSTELS GROUP BY hostel_no;

, and the output comes as:
--------------------------------------
hotel_no  |     total_students |
--------------------------------------
1003        |            234           |
1001        |            425           |
1002        |            231           |
1004        |            212           |
--------------------------------------

Now, the questions arise : 
  • Why the hostel_num 1003 came at the top ?
  •  Shouldn't it come at row number 3 ?
  •  What is the logic behind this kind of order ?

It is  known, that GROUP BY clause consolidates the repetitive column values and group them together. Now the doubt here is: How it decides the order of displaying those values, as here, one would expect an output like this :
--------------------------------------
hotel_no  |     total_students |
--------------------------------------
1001        |      425                 |
1002        |      231                 |
1003        |      234                 |
1004        |      212                 |
--------------------------------------