FYBSc - C and DB - Labbook
FYBSc - C and DB - Labbook
(Computer
Science)
Semester-I
II Work Book
Name:
College Name: _
Academic Year:
1
Savitribai Phule Pune
University
Section
-I
Lab Course –
IC
Programming
2
Introduction
1) Students are expected to carry this book every time they come to
the lab for computer science practical.
2) Students should prepare oneself beforehand for the
Assignment by reading the relevant material.
3) Instructor will specify which problems to solve in the lab during
the allotted slot and student should complete them and get
verified by the instructor. However student should spend
additional hours in Lab and at home to cover as many problems
as possible given in this work book.
3
4) Students will be assessed for each exercise on a scale from 0to5.
Not done 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
Well Done 5
Lab Course I
C Programming
Sr. Assignment Name Marks Teachers
No. (out of 5) Sign
1 Testing the Errors
Instructor H.O.D. /
Coordinator
2. #include<stdio.h>
void main()
{
printf("hello")
}
3. #include<stdio.h>
void Main()
{
int a = 10;
printf("%d", a);
}
4. void main()
{
int a, b, c;
a + b = c;
}
5. #include<stdio.h>
void main()
{
while(.)
{
printf("hello");
}
2. Expression Examples
Expression C expression
Increment by a 3 a=a+3
Decrement b by 1 b = b-1 or b--
2 a2 + 5 b/2 2*a*a + 5*b/2
7/13(x-5) (float)7/13*(x-5)
5% of 56 (float)5/100*56
n is between 12 to 70 n>=12 && n<=70
r2h Pi*r*r*h
n is not divisible by 7 n % 7 != 0
n is even n%2== 0
ch is an alphabet ch>=’A’ && ch<=’Z’ || ch>=’a’ && ch<=’z’
Note: The operators in the above expressions will be executed according to
precedence and associativity rules of operators.
3. Sample program- to calculate and print simple interest after accepting principal
sum, number of years and rate of interest.
Program development steps
1. Type the sample program given above. Execute it for the different values as
given below and fill the last column from the output given by the program.
Follow the following guidelines
a. At $ prompt type vi followed by filename. The filename should have .c as
extension for example
$vi pnr.c
b. Type the sample program given above using vi commands
and save it Compile the program using cc compiler available in
Linux
$cc pnr.c
It will give errors if any or it will give back the $ prompt if there are no errors
A executable file a.out is created by the compiler in current directory. The program
can be executed by typing name of the file as follows giving the path.
$ ./a.out
Alternatively the executable file can be given name by using –o option while
compiling as follows
$cc pnr.c –o pnrexec
$./pnrexec
The executable file by specified name will be created. Note that you have to
specify the path of pnrexec as ./pnrexec , i. e., pnrexec in current (. Stands for
current directory) directory otherwise it looks for program by that name in the
path specified for executable programs
int noofYears;
scanf(“%f”,&amount)
scanf(“%f”, amount);
scanf(“%d”, noOfYears);
Set A . Apply all the three program development steps for the following examples.
1. Accept dimensions of a cylinder and print the surface area and volume
(Hint: surface area = 2r2 + 2rh, volume = r2h)
2. Accept temperatures in Fahrenheit (F) and print it in Celsius(C) and Kelvin
(K) (Hint: C=5/9(F- 32), K = C + 273.15)
3. Accept initial velocity (u), acceleration (a) and time (t). Print the final
velocity (v) and the distance (s) travelled. (Hint: v = u + at, s = u + at2)
4. Accept inner and outer radius of a ring and print the perimeter and area
of the ring (Hint: perimeter = 2 (a+b) , area = (a2-b2) )
5. Accept two numbers and print arithmetic and harmonic mean of the two
numbers (Hint: AM= (a+b)/2 , HM = ab/(a+b) )
6. Accept three dimensions length (l), breadth(b) and height(h) of a
cuboid and print surface area and volume (Hint : surface
area=2(lb+lh+bh ), volume = lbh )
7. Accept a character from the keyboard and display its previous and next
character in order. Ex. If the character entered is ‘d’, display “The previous
character is c”, “The next character is e”.
8. Accept a character from the user and display its ASCII value.
During problem solving, we come across situations when we have to choose one of
the alternative paths depending upon the result of some condition. Condition is an
expression evaluating to true or false. This is known as the Branching or decision-
making statement. Several forms of If and else constructs are used in C to support
decision-making.
1) if statements
2) if – else
3) Nested if
Note: If there are more than one statement in the if or else part, they have to be
enclosed in { } braces
New statement
2. if - else
statement if( n % 2 == 0)
printf(“Even”);
if (condition) True If False else
{ condition ? printf(“Odd”);
statement;
}
statement statement
else
{
statement;
}
New statement
3. Nested if
If ( a >= b)
if (condition) { if ( a >= c)
{ False True printf(“ %d
if (condition) a>=b
is
{ maximum”,
b>= c True a); else
statement;} False True a>=c printf(“ %d
False
else is
{ statement;} c is b is c is a is maximum”,
max max max max c);
} }
else else
{ {
if (condition) if ( b >= c)
{ printf(“ %d
is
statement; } maximum”,
else b); else
{ statement; } printf(“ %d
is
} maximum”,
c);
}
start
/* Program to check range */
1. Start
2. Accept the number #include
3. Check if number <stdio.h>
is within range Read main( )
4. if true numbe { /* variable
r
print “Number declarations */ int n;
is within range int llimit=50, ulimit = 100;
“ otherwise /* prompting and accepting
False
print “number is input */ printf(“Enter the
If(n in range)
out of range”. number”); scanf(“%d”,&n);
5. Stop if(n>=llimit && n <= ulimit)
True printf(“Number is within
range”);
else
Number is
within range
printf(“Number is out of
range”);
}
Number is out
of range
stop
1. Execute the following program for five different values and fill in the adjoining
table
main() n output
{
int n;
printf(“Enter no.”);
scanf(“%d”,&
n); if(n%
==0)
printf(“divisible)
; else
printf(“not divisible”);
}
2. Type the above sample program 4 and execute it for the following values.
n Output
message
50
10
0
65
3. Using the sample code 3 above write the complete program to find the
maximum of three numbers and execute it for different set of values.
Set A: Apply all the three program development steps for the following examples.
1. Write a program to accept an integer and check if it is even or odd.
2. Write a program to accept three numbers and check whether the first is
between the other two numbers. Ex: Input 20 10 30. Output: 20 is between
10 and 30
3. Accept a character as input and check whether the character is a digit.
(Check if it is in the range ‘0’ to ‘9’ both inclusive)
4. Write a program to accept a number and check if it is divisible by 5 and 7.
5. Write a program, which accepts annual basic salary of an employee and
calculates and displays the Income tax as per the following rules.
Basic: < 1,50,000 Tax = 0
1,50,000 to 3,00,000 Tax = 20%
> 3,00,000 Tax = 30%
6. Accept a lowercase character from the user and check whether the character
is a vowel or consonant. (Hint: a,e,i,o,u are vowels)
1. Write a program to accept marks for three subjects and find the total
marks secured , average and also display the class obtained. (Class I –
above %, class II – % to
_%, pass class – _% to _% and fail otherwise)
2. Write a program to accept quantity and rate for three items, compute the
total sales amount, Also compute and print the discount as follows: (amount
> 20% discount,
amountbetween to _ _ 15% discount, amount between – to _ 8%
discount)
3. A library charges a fine for every book returned late. Accept the number of
days the member is late, compute and print the fine as follows:(less than five
days Rs fine, for 6 to 10 days Rs. fine and above 10 days Rs. _ fine )
The control statement that allows us to make a decision from the number of
choices is called a switch-case statement. It is a multi-way decision making
statement.
stop
2. The switch statement is used in writing menu driven programs where a menu
displays several options and the user gives the choice by typing a character or
number. A Sample program to display the selected option from a menu is given
below.
stop
1. Write the program that accepts a char–type variable called color and displays appropriate
message using the sample code 1 above. Execute the program for various character
values and fill in the following table. Modify the program to include all rainbow
colours
1. Accept a single digit from the user and display it in words. For example, if
digit entered is 9, display Nine.
2. Write a program, which accepts two integers and an operator as a
character (+ - * /), performs the corresponding operation and displays the
result.
3. Accept two numbers in variables x and y from the user and perform
the following operations
Options Actions
1. Equality Check if x is equal to y
2. Less Than Check if x is less than y
3. Quotient and Divide x by y and display the quotient and
Remainder remainder
4. Range Accept a number and check if it lies between
x and y (both inclusive)
5. Swap Interchange x and y
Set B: Apply all the three program development steps for the following examples.
1. Accept radius from the user and write a program having menu with the following
options and corresponding actions
Options Actions
1. Area of Circle Compute area of circle and print
2. Circumference of Compute Circumference of circle and print
Circle
3. Volume of Sphere Compute Volume of Sphere and print
2. Write a program having a menu with the following options and corresponding
actions
Options Actions
1. Area of square Accept length ,Compute area of square and print
2. Area of Rectangle Accept length and breadth, Compute area of
rectangle
and print
3. Area of triangle Accept base and height , Compute area of triangle
and
print
1. Accept the three positive integers for date from the user (day, month and
year) and check whether the date is valid or invalid. Run your program for the
following dates and fill the table. (Hint: For valid date 1<=month<=12,1<= day
<=no-of-days where no-of-days is 30 in case of months 4, 6,9 and 11. 31 in case
of months 1,3,5,7,8,10 and 12. In case of month 2 no-of-days is 28 or 29
depending on year is leap or not)
Date Outpu
t
12-10-
1984
32-10-
1920
10-13-
1984
29-2-1984
29-2-2003
29-2-1900
2. Write a program having menu that has three options - add, subtract or multiply
two fractions. The two fractions and the options are taken as input and the
result is displayed as output. Each fraction is read as two integers, numerator
and denominator.
We need to perform certain actions repeatedly for a fixed number of times or till
some condition holds true. These repetitive operations are done using loop control
statements. The types of loop structures supported in C are
1. while statement
2. do-while statement
3. for statement
} True
expr1 =
initialization
Loop
expression
expr2 = loop
condition expr3 = Body
alteration
expression which Expr3
alters the loop
variable
Note: Usually the for loop is used when the statements have to executed for a fixed
number of times. The while loop is used when the statements have to be executed as
long as some condition is true and the do-while loop is used when we want to
execute statements atleast once (example: menu driven programs)
Print
value of
sum
stop
4. Sample program- To read characters till EOF (Ctrl+Z) and count the total number
of characters entered.
Print count
stop
1. Write a program that accepts a number and prints its first digit. Refer sample
code 1 given above. Execute the program for different values.
2. Write a program that accepts numbers continuously as long as the number is
positive and prints the sum of the numbers read. Refer sample code 2 given
above. Execute the program for different values.
3. Write a program to accept n and display its multiplication table. Refer to
sample code 3 given above.
4. Type the sample program to print sum of first n numbers and execute the
program for different values of n.
5. Write a program to accept characters till the user enters EOF and count number
of times ‘a’ is entered. Refer to sample program 5 given above.
Set B. Apply all the three program development steps for the following examples.
1. Write a program to display the first n Fibonacci numbers. (1 1 2 3 5 ……)
2. Write a program to accept real number x and integer n and calculate the sum of
first n terms of the series x+ 3x+5x+7x+…
3. Write a program to accept real number x and integer n and calculate the sum of first
n terms
1 2 3
of the series
x + x2 + x3 +
4. Write a program to accept characters till the user enters EOF and count
number of alphabets and digits entered. Refer to sample program 5
given above.
5. Write a program, which accepts a number n and displays each digit in
words. Example: 6702 Output = Six-Seven-Zero-Two. (Hint: Reverse the
number and use a switch statement)
1. Write a program to accept characters from the user till the user enters * and
count the number of characters, words and lines entered by the user. (Hint:
Use a flag to count words. Consider delimiters like \n \t , ; . and space for
counting words)
2. Write a program which accepts a number and checks if the number is a
palindrome (Hint number = reverse of number)
Example: number = 3472 Output: It is not a palindrome number = 262, Output
: It is a palindrome
3. A train leaves station A at 4.00 a.m and travels at 80kmph. After every 30
minutes, it reaches a station where it halts for 10 minutes. It reaches its
final destination B at 1.00
p.m. Display a table showing its arrival and departure time at every
intermediate station. Also calculate the total distance between A and B.
4. A task takes 4 ½ hours to complete. Two workers, A and B start working on it
and take turns alternately. A works for 25 minutes at a time and is paid Rs 50,
B works for 75 minutes at a time and is paid Rs. 150. Display the total number
of turns taken by A and B, calculate their total amounts and also the total cost
of the task.
In the previous exercise, you used while, do-while and for loops. You should read
following topics before starting this exercise
1. Different types of loop structures in C.
2. Syntax for these statements.
3. Usage of each loop structure
Nested loop means a loop that is contained within another loop. Nesting can be done
upto any levels. However the inner loop has to be completely enclosed in the outer
loop. No overlapping of loops is allowed.
Note: It is possible to nest any loop within another. For example, we can have a for loop
inside a while or do while or a while loop inside a for.
1. The Sample program 1 displays n lines of the following triangle. Type the
program and execute it for different values of n.
1
1 2
1 2 3
1 2 3 4
2. Modify the sample program 1 to display n lines of the Floyd’s triangle as follows
(here n=4). 1
2 3
4 5 6
7 8 9 10
3. The sample program 2 computes the sum of digits of a number and the process
is repeated till the number reduces to a single digit number. Type the
program and execute it for different values of n and give the output
Note: If you want to use any of the above functions you must include the library
for example #include <ctype.h>
#include <math.h>
In case of math library , it needs to be linked to your program. You have to compile
the program as follows
$ cc filename -lm
A program that does multiple tasks, provides a menu from which user can choose the
appropriate task to be performed. The menu should appear again when the task is
completed so that the user can choose another task. This process continues till the
user decides to quit. A menu driven program can be written using a combination of
do-while loop containing a switch statement. One of the options provided in a menu
driven program is to exit the program.
1. Write a menu driven program to perform the following operations on a character type
variable.
i. Check if it is an alphabet
ii. Check if it is a digit.
iii. Check if it is lowercase.
iv. Check if it is uppercase.
v. Convert it to uppercase.
vi. Convert it to lowercase.
Refer to the sample code given above and use standard functions from ctype.h
Item Price
1. Write a program to calculate the total price for a picnic lunch that a user is
purchasing for her group of friends. She is first asked to enter a budget for the
lunch. She has the option of buying apples, cake, and bread. Set the price per kg
of apples, price per cake, and price per loaf of bread in constant variables. Use a
menu to ask the user what item and how much of each item she would like to
purchase. Keep calculating the total of the items purchased. After purchase of an
item, display the remaining amount. Exit the menu if the total has exceeded the
budget. In addition, provide an option that allows the user to exit the purchasing
loop at any time.
You have already used standard library functions. C allows to write and use user
defined functions. Every program has a function named main. In main you can call
some functions which in turn can call other functions.
The following table gives the syntax required to write and use functions
Sr. Actions involving Syntax Example
No functions
1. Function declaration returntype function(type void display();
arg1, type arg2 … ); int sum(int x, int y);
1. Sample code
The program given below calculates the area of a circle using a function and uses
this function to calculate the area of a cylinder using another function.
#include
<stdio.h> void
main()
{
float areacircle (float r);
float areacylinder(float r,
int h); float area, r;
printf(“\n Enter
Radius: “);
scanf(“%f”,&r);
area=areacircle(r);
printf(“\n Area of circle =%6.2f”, area);
scanf(“%d”,&h);
area=areacylinder(r,h);
printf(“\n Area of cylinder =%6.2f”, area);
}
#include
<stdio.h> void
main()
{
int iswhitespace (char
ch); char ch;
int count=0;
1. Type the program given in sample code 1 above and execute the program.
Comment function declarations and note down the type of error and the
error messages received. Add another function to calculate the volume of
sphere and display it.
2. Type the program given in sample code 2 above and execute the
program. Comment function declaration and note down the type of error and
the error messages received. Modify the function such that it returns 1 if
the character is a vowel. Also count the total number of vowels entered.
Set A . Write C programs for the following problems
1. Write a function isEven, which accepts an integer as parameter and returns 1
if the number is even, and 0 otherwise. Use this function in main to accept n
numbers and ckeck if they are even or odd.
2. Write a function, which accepts a character and integer n as parameter and
displays the next n characters.
3. Write a function, which accepts a character and integer n as parameter and
displays the next n characters.
b.sin(x)
c. cos (x)
Define separate functions to calculate xy and n! and use them in each function.
To demonstrate Recursion.
You should read the following topics before starting this exercise
1. Recursive definition
2. Declaring and defining a function
3. How to call a function
4. How to pass parameters to a function
Recursion is a process by which a function calls itself either directly or indirectly. The
points to be remembered while writing recursive functions
i. Each time the function is called recursively it must be closer to the solution.
ii. There must be some terminating condition, which will stop recursion.
iii. Usually the function contains an if –else branching statement where one
branch makes recursive call while other branch has non-recursive
terminating condition
Expressions having recursive definitions can be easily converted into recursive functions
2. Write the sample program 2 given above and execute the program for different
values of n and r. Modify the program to define a global integer variable count
and increment it in nCr function. Add a print statement in main function for
variable count. Execute the program for different values and fill in the following
table
1
disks 2
3
4
5
Sourc
e Intermedia Destinati
Needl te needle on Needle
e (A) (B) (C)
You should read the following topics before starting this exercise
1. What are arrays and how to declare an array?
2. How to enter data in to array and access the elements of an array.
3. How to initialize an array and how to check the bounds of an array?
4. How to pass an array to a function
An array is a collection of data items of the same data type referred to by a common
name. Each element of the array is accessed by an index or subscript. Hence, it is
also called a subscripted variable.
#include<stdio
.h> int main()
{
int arr[20]; int n;
void accept(int a[20], int
n); void display(int
a[20], int n); int
maximum(int a[20], int
n);
printf(”How many
numbers :”); scanf(“%d”,
&n); accept(arr,n);
display(arr,n);
printf(“The maximum is :%d” , maximum(arr,n));
}
1. Write a program to accept n numbers in an array and display the largest and
smallest number. Using these values, calculate the range of elements in the array.
Refer to the sample code given above and make appropriate modifications.
2. Write a program to accept n numbers in an array and calculate the average.
Refer to the sample code given above and make appropriate modifications.
1. Write a program to accept n numbers from the user and store them in an array
such that the elements are in the sorted order. Display the array. Write
separate functions to accept and display the array. (Hint: Insert every number
in its correct position in the array)
2. Write a function to sort an array of n integers using Bubble sort method.
Accept n numbers from the user, store them in an array and sort them using
this function. Display the sorted array.
3. Write a program to accept a decimal number and convert it to binary, octal
and hexadecimal. Write separate functions.
4. Write a program to find the union and intersection of the two sets of integers
(store it in two arrays).
5. Write a program to remove all duplicate elements from an array.
1. Write a program to merge two sorted arrays into a third array such that the
third array is also in the sorted order.
a1 10 25 90
a2 9 16 22 2 10
6
0
a3 9 10 16 2 25 26 90 100
2
2. Write a program to accept characters from the user till the user enters EOF and
calculate the frequency count of every alphabet. Display the alphabets and their
count.
Input: THIS IS A SAMPLE INPUT
Output: Character Count
T 2
H 1
I 3
…….
You should read the following topics before starting this exercise
1. How to declare and initialize two-dimensional array
2. Accessing elements
3. Usage of two dimensional arrays
#include<stdio
.h> int main()
{
int mat[10][10], m, n;
void display(int a[10][10], int m, int
n); void accept(int a[10][10], int m,
int n); void sumofrows(int a[10][10],
int m, int n);
1. Write a program to accept, display and print the sum of elements of each row
and sum of elements of each column of a matrix. Refer to sample code given above.
1
1 1
1 2 1
1 1 3 3
1
4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
2. A magic square of order n is an arrangement of n² numbers, in a square, such that the n
numbers in all rows, all columns, and both diagonals sum to the same constant. A normal
magic square contains the integers from 1 to n². The magic constant of a magic square
depends on n and is M(n) = (n 3+n)/2. For n=3,4,5, the constants are 15, 34, 65 resp. Write a
program to generate and display a magic square of order n.
Section-II
Lab Course – II
Relational Database
Management
System Assignments
Assignment Completion Sheet
Lab Course II
11 Nested Queries
Entities:
They are represented using the rectangle shape box. These rectangles are named with the
entity set they represent.
ER modeling is a top-down structure to database design that begins with identifying the
important data called entities and relationships in combination between the data that must
be characterized in the model. Then database model designers can add more details such as
the information they want to hold about the entities and relationships which are the
attributes and any constraints on the entities, relationships, and attributes. ER modeling is
an important technique for any database designer to master and forms the basis of the
methodology.
Entity type: It is a group of objects with the same properties that are
identified by the enterprise as having an independent existence. The
basic concept of the ER model is the entity type that is used to represent
a group of ‘objects’ in the ‘real world’ with the same properties. An entity
type has an independent existence within a database.
Entity occurrence: A uniquely identifiable object of an entitytype.
Each entity type is shown as a rectangle labeled with the name of the entity, which is
normally a singular noun.
What is Relationship Type?
In the above figured example “Branch has staff”, there is a relationship between two
participating entities. A relationship of degree two is called binary degree (relationship).
Attributes are the properties of entities that are represented by means of ellipse shaped
figures. Every elliptical figure represents one attribute and is directly connected to its
entity (which is represented as rectangle).
It is to be noted that multi-valued attributes are represented using double ellipse like this:
Relationships
Suppose you are given the following requirements for a simple database for the National
Hockey League (NHL):
Consider the case study given above and find out entities and their attributes.
Set B
Find different set of entities and their attributes for online bookstore
Assignment Evaluation
0: Not Done [ ]
1: Incomplete [ 2: Late Complete [ ]
3: Needs
] 4: Complete [ 5: WellDone [ ]
Improvement [ ]
]
Signature of Teacher
Assignment no 2
The ER model supported with additional semantic concepts is called the Enhanced Entity-
Relationship (EER) model. There are three of the most important and useful added concepts
of the EER model, namely specialization/generalization, aggregation, and composition. In this
chapter you will learn about the main two important concepts. These are:
Generalization Aggregation
Each member of a sub class is also a member of the super class i.e. the entity in the sub
class is the same entity in the super class, but has a different role. The relationship
between a super class and a sub class is one-to-one (1:1) and is termed as a
super-class/sub-class relationship.
Set A
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: WellDone
[]
Signature of Teacher
Assignment no.3
What is Aggregation?
A relationship represents a connection between two entity types that are conceptually at
the same level. Sometimes you may want to model a ‘has-a’, ‘is-a’ or ‘is-part-of’
relationship, in which one entity represents a larger entity (the ‘whole’) that will consist of
smaller entities (the ‘parts’). This special kind of relationship is termed as an aggregation.
Aggregation does not change the meaning of navigation and routing across the
relationship between the whole and its parts.
An example of an aggregation is the ‘Teacher’ entity following the ‘syllabus’ entity act as a
single entity in the relationship. In simple words, aggregation is a process where the relation
between two entities is treated as a single entity.
Set A
Consider a database used to record the marks that students get in different exams of
different course offerings.
a) Construct an E-R diagram that models exams as entities, and uses a ternary relationship,
for the above database.
b) Construct an alternative E-R diagram that uses only a binary relationship between
students and course-offerings. Make sure that only one relationship exists between a
particular student and course- offering pair, yet you can represent the marks that a
student gets in differentexams of a course offering.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ 2: Late Complete [ ]
3: Needs ] 4: Complete [ 5: WellDone [ ]
Improvement [ ]
]
Signature of Teacher
Assignment no.4 Using
Postgresql (Demo of Postgresql)
Download PostgreSQL
To download PostgreSQL to install it on Windows 7, please visit the following web page :
http://www.postgresql.org/download/windows and click on the "Download" link under "One
click installer". The downloaded package will install PostgreSQL Server and pgadmin III GUI to
manage PostgreSQL Server and StackBuilder which can be used to download drivers and tools
for PostgreSQL Server.
Once you click on the said "Download" link, it will take you to another page from where you
need to select the package depending upon your OS platform. So, for installing PostgreSQL
on 32 bit Windows 7, select "Win x86-32". If you are using a 64 bit OS, select "Win x86-64".
That will start the download process and depending up on your connection speed, take a while
to get downloaded.
Make sure you have turned Third Party AntiVirus off while installing.
Once the download is finished, run the postgresql-9.1.1-1-windows.exe file and select the
location where you want to install it. By default, it is installed within Program Files folder. Then
it asks you to enter a password. Keep the port as default. When asked for "Locale", we have
selected "English, United States". It will take a while to install PostgreSQL on your system.
On completion of the installation process, you will get the following screen.
After the installation process is completed, you can access pgAdmin III, psql,
StackBuilder and PostgreSQL shell from your Program Menu under PostgreSQL 9.1.
Running the PostgreSQL interactive terminal program, called psql, which allows you to
interactively enter, edit, and execute SQL commands. At the time of installing postgres to
your operating system, it creates an "initial DB" and starts the postgres server domain
running.
Typically initdb creates a table named "postgres" owned by user "current logged in user
name" At the command line in your operating system, type the followingcommand.
user@user-pc:~$ sudo -i -u
postgres postgres@user-pc:~$
psql
psql (9.3.5, server
9.3.6) Type "help" for
help.
user@user-pc:~$ su -
postgres user@user-pc:~$
psql
psql (9.3.6)
Type "help" for help.
Windows :
In windows, current user doesn't matter
C:\Program Files\PostgreSQL\9.4\bin>psql -U
postgres Password for user postgres:
psql (9.4.1)
Type "help" for help.
postgres=#
After accessing a PostgreSQL database, you can run SQL queries and more. Here are some common psql
commands
PostgreSQL-Data Types
A datatype specifies, what kind of data you want to store in the table field. While creating
table, for each column, you have to use a datatype. There are different categories of data
types in PostgreSQL discussed below for your ready reference:
1. Create table emp (eno integer primary key, enamevarchar[50] , salary float);
2. Create table books( id integer UNIQUE, title text NOT NULL,
author_idinteger,sub_idinteger,CONSTRAINTbooks_id_pkey PRIMARY
KEY(id));
3. Create table sales_order(order_no char[10] PRIMARY KEY,
order_date date, salesman_no integer);
4. Create table client_master (client_no integer CONSTRAINT p_client PRIMARY
KEY, name varchar[50], addr text, bal_due integer);
5. Create table inventory(inv_no integer PRIMARY KEY, in_stock Boolean);
6. create table sales_order1(order_no char[10],
product_no char[10],qty_orderedinteger,product_rate
numeric(8,2),PRIMARY KEY(order_no,product_no));
SET A
1. Create a table with following details
Set B
Create table for the information given below by choosing appropriate data types and also
specifying proper primary key constraint on fields which are underlined
1. Property ( property_id, property_desc , area, rate, agri_status )
2. Actor ( actor_id, Actor_name, birth_date )
3. Movie (movie-no, name, release-year )
4. Hospital (hno,hname,hcity)
Set C
Create table for the information given below by choosing appropriate data types
and also specifying proper primary key constraint on fields which are underlined
1. Table ( , , , , Primary key :
)
Instructor should fill in the blanks with appropriate values
Assignment Evaluation
0: Not Done [ ]
1: Incomplete [ 2: Late Complete [ ]
3: Needs
] 4: Complete [ 5: WellDone [ ]
Improvement [ ]
]
Signature of Teacher
Assignment No.6
Objective: To create one or more tables with Check constraint , Unique constraint,
Not null constraint , in addition to the first two constraints (PK &
FK)
Constraints can be defined as either of the
following: CREATE TABLE table_name (
column_name1TYPE
column_constraint, column_name2
type column constraint,
table_constrainttable_constraint
);
The table constraints are similar to column constraints except that they are applied to the
entire table rather than to an individual column.
1. Null constraint
Use of null constraint: Specifies that the column can contain null values
Use of not null constraint: Specifies that the column can not contain null values
Ex.: Create table client_master (client_no integer not null, name char(10) not
null, addr varchar(30) null, bal_due numeric);
2. Unique contarint
Use: forces the column to have unique value.
Ex.: Create table client_master (client_no integer not null, name char(10) not
null, addr varchar(30) null, bal_due numeric, ph_no integer unique);
3. Check constraint
Use : Specifies a condition that each row in the table must satisfy.Condition is
specified as a logical expression that evaluates either true orfalse.
Ex. Create table client_master (client_no varchar CHECK(client_no like ’C%’), name
char(10) check (name=upper(name)), addr varchar(30) null, bal_due numeric, ph_no
integer unique);
Set A
Table
Name Student
Colum
Columns n Column Data Type Constraints
Name
1 Stud_id integer Primary key
2 Stud _name varchar (50) NOT NULL, uppercase
3 Stud _Class varchar(10) Class in (
‘FY’, ‘SY’,
‘TY’)
Greater
4 Stud _Marks float than Zero
5 Stud _uid text Unique
Stud_uid not equal to Stud_id
Table level constraint
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: WellDone
[]
Signature of Teacher
Assignment No.7
Objective: To drop a table from the database, to alter the schema of a table in the
Database.
1. Alter Statement: Alter table command is use to modify the structure of the table.
Syntax:
ALTER TABLE table_name action;
Add a column, drop a column, rename a column, or change a column’s data type.
Set a default value for the column.
Add a CHECK constraint to a column.
Rename a table.
1. To add a new column to a table, you use ALTER TABLE ADD COLUMN statement:
2. To remove an existing column, you use ALTER TABLE DROP COLUMN statement:
3. To rename an existing column, you use the ALTER TABLE RENAME COLUMN
TO statement:
4. To change a default value of the column, you use ALTER TABLE ALTER COLUMN
SET DEFAULT or DROP DEFAULT:
ALTER TABLE table_name ALTER COLUMN [SET NOT NULL| DROP NOT NULL]
2. Drop Statement:
Use : Deletes an object (table/view/constraint) schema from the database.
Syntax: drop table table_name;
Example: drop table employee;
Set A
Create the table given below. Assume appropriate data types for attributes. Modify the
table, as per the alter statements given below. Type \d <table name> and write the
output.
Supplier_master(supplier_no, supplier_name,city,phone-no,amount)
1. Alter table supplier_master add primary key (supplier_no);
2. Alter table supplier_master add constraint city-check check city in(‘pune’, ‘mumbai’, ‘calcutta’);
3. alter table supplier_master drop phone-no;
4. alter table supplier_master modify (supplier_namevarchar(50));
5. alter table supplier_master drop constraint city-check;
6. drop table supplier_master;
Set B
1. Remove employee table from your database. Create table employee(eno,
ename, sal). Add designation column in the employee table with values
restricted to a set of values.
2. Remove student table from your database.
Create table student( student_no, sname,date_of_birth).
Add new column into student relation named address as a text data type with NOT
NULL integrity constraint and a column phone of data type integer.
3. Consider the project relation created in the assignment 12. Add a constraint that the
project name should always start with the letter ‘R’
4. Consider the relation hospital created in assignment 12. Add a column hbudget of type int
, with the constraint that budget of any hospital should always > 50000.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [
]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]
Signature of Teacher
Assignment No.8
Data Manipulation Queries (Insert, Delete, Update)
Objective: To insert / update / delete records using tables created in previous
Assignments. (Use simple forms of insert / update / delete statements)
INSERT syntax
INSERT INTO table_name (column1, column2 …) VALUES (value1, value2 …);
First, you specify the name of the table that you want to insert a new row after the
INSERT INTO clause, followed by a comma-separated column list.
Second, you list a comma-separated value list after the VALUES clause. The value list must
be in the same order as the columns list specified after the table name.
To add multiple rows into a table at a time, use the following syntax:
INSERT INTO table (column1, column2, …) VALUES (value1, value2, …),(value1, value2, …)
,...; You just need to add additional comma-separated value lists after the first list, each
value in the list is separated by a comma (,).
To insert data that comes from another table, use the INSERT INTO SELECT statement as follows:
The WHERE clause is used to filter rows that allow you to insert partial data from
the another_table into the table.
Set A
Consider the tables created in previous assignments .Type and execute the below
statements for these tables. Write the output of each statement & justify your answer
1. INSERT INTO sales_order(s_order_no,s_order_date,client_no) VALUES (‘A2100’, now()
,’C40014’);
2. INSERT INTO client_master values(‘A2100’,’NAVEEN’,’Natraj
apt’,’pune_nagar road’,’pune’,40014);
3. Insert into client_master values (‘A2100’,’NAVEEN’,NULL,’pune_nagar road’,’pune’,40014);
4. UPDATE emp SET netsal= net_sal_basic_sal*0.15;
5. UPDATE student
SET name=’SONALI’,address=’Jayraj apartment’ WHERE stud_id=104 ;
6. DELETE from emp;
7. DELETE from emp WHERE net_sal<1000;
Set B
An owner can have one or more properties, but a property belongs to exactly one owner .
Create the relations accordingly ,so that the relationship is handled properly and the
relations are in normalized form (3NF).
a) Insert two records into owner table.
b) insert 2 property records for each owner .
c) Update phone no of “Mr. Nene” to 9890278008
d) Delete all properties from “pune” owned by “ Mr. Joshi”
Dept(dno,dname,dloc)
There exists a one-to-many relationship between emp & dept.Create the Relations accordingly,
so that the relationship is handled properly and the relations are in normalized form (3NF).
a) Insert 5 records into department table
b) Insert 2 employee records for each department.
c) increase salary of “managers” by 15%;
d) delete all employees of deparment 30;
e) delete all employees who are working as a “clerk”
f) change location of department 20 to ‘KOLKATA’.
Set C
Create the following tables(Primary keys are underlined)
Machine (mno, name, mtype,
mcost) Part (pno, pname, pdesc)
Constraints : Primary Key constraints, machine name not null,
foreign key Machine & Parts are related with one-to-many
relationship.
Create the relations accordingly,so that the relationship is handled properly and the
relations are in normalized form(3NF) and insert 5 records into eachtable.
Assignment Evaluatio
0: Not Done [ ] 1: Incomplete [ ] 2:Late Complete[]
3: Needs Improvement 4: Complete [ ] 5: Well Done [ ]
[ ]
Signature of Instructor
Assignment No.9
Aggregate functions are used to produce summarized results. They operate on sets of
rows. They return results based on groups of rows. By default, all rows in a table are
treated as one group. The GROUP BY clause of the select statement is used to divide rows
into smaller groups.
Name Description
COUNT This function returns the number or rows or non NULL values for a
column SUM This function returns the sum of a selected column.
MAX This function returns the largest value of a specific
column. MIN This function returns the smallest value of a
specific column. AVG This function returns the average
value for a specific column.
Syntax
order_by_clause] ) OR
order_by_clause] ) OR
aggregate_name (* )
Set A
Create a table employee with attributes empno, name, address, salary and deptno. Insert
atleast 10 records into the same. Execute each query
Execute following select queries .
1. Select * from emp;
2. Select empno, name from emp;
3. Select distinct deptno from emp;
4. Select * from emp where deptno = ;
5. Select * from emp where address = ‘pune’ and sal> ;
6. Select * from emp where address = ‘pune and salary between and _;
7. Select * from emp where name like ‘---%’
8. Select * from emp where name like ‘%and%’
9. Select * from emp where salary is null;
10. Select * from emp order by eno;
11. Select * from emp order by deptno, enodesc;
12. Select deptno as department, sum(salary) as total from emp group by deptno order by deptno;
13. Select deptno as department , count(eno) as total_emp from emp group by
deptno having count(eno ) > order by deptno;
14. select avg(salary) from emp;
15. select max(salary),deptno from emp group by deptno having max(sal) > _;
16. select deptno, min(salary) from emp order bydeptno;
17. update emp set salary = salary + 0.5*salary where deptno = (select deptno from
department where dname = ‘finance’);
18. update emp set deptno = (select deptno from department where dname =
‘finance’) Where deptno = (select deptno from department where dname =
‘inventory’);
19. insert into emp_backup(eno,ename) values(select eno,ename from emp);
20. delete from emp where deptno = (select deptno from department where dname=’production’);
Set B
Prerequisite : Students should know the normalization
concept Consider the relations
Person (pnumber, pname, birthdate,
income), Area (aname,area_type).
An area can have one or more person living in it , but a person belongs to exactly one
area. The attribute ‘area_type’ can have values as either urban or rural.
Create the Relations accordingly, so that the relationship is handled properly and
the relations are in normalized form (3NF).
Assume appropriate data types for all the attributes. Add any new attributes as required,
depending on the queries. Insert sufficient number of records in the relations / tables with
appropriate values as suggested by some of the queries.
Write select queries for following and execute them.
65
Set C
Create the following tables(Primary keys are underlined):
Sailors(sid,sname,rate,age)
Boats(bid,bname,colour)
Reserves(sid,bid,date)
Sailors and boats are related many to many.
Create the relations accordingly,so that the relationship is handled properly and the
relations are in normalized form(3NF) and insert 5 records into eachtable.
Draw ER diagram for given relational schema and show normalization.
Solve the following quesries:
a) Find all the sailors with a rating above 8.
b) Find the ages of sailors whose name begins and ends with ‘P’.
c) Find name of sailors who have reserved red and greenboats.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete 2:Late Complete[]
3: Needs [ ] 4: 5: Well Done [ ]
Improvement [
Complete [ ]
Signature of Instructor
66
Assignment No.10 Queries
with set operations
Objective: To understand & get a Hands-on practice using set operations (union
,intersect and except) with select statement.
1. Union
Use: Returns the union of two sets of values, eliminating duplicates.
Syntax: <select query> Union<select query>
Ex.: Select cname from depositor Union Select cname from borrower;
2. Union all
Use: returns union of two sets of values ,retaining all duplicates
Syntax: <select query> Union all<select query>
Ex.: Select cname from depositor Union allSelect cname from borrower;
3. Intersect
Use:returns the intersection of two sets of values ,eliminating duplicates
Syntax: <select query> intersect<select query>
Ex.: Select cname from depositor intersect Select cname from borrower;
4. Intersect all
Use: returns intersection of two sets of values ,retaining all duplicates
Syntax: <select query> intersect all<select query>
Ex.: Select cname from depositor intersect all Select cname from borrower;
5. Except
Use: returns the difference between two sets of values.i.e returns all
values of set1 not contained in set2,eliminates duplicates
Syntax: <select query> except<select query>
Ex.: Select cname from depositor Except Select cname from borrower;
6. Except all
Use: returns the difference between two sets of values.i.e returns all values of
set1 not contained in set2, retains all duplicates
Syntax: <select query> except all<select query>
Ex.: Select cname from depositor Except Select cname from borrower;
Note: To use the INTERSECT operator, the columns that appear in the SELECT statements
must follow the rules below:
1. The number of columns and their order in the SELECT clauses must the be the same.
2. The data types of the columns must be compatible.
Set A
One deparment can have one or more teaching & non-teaching staff, but a teaching
or non- teaching staff belongs to exactly one department. Hence dno is a foreign key
in the both the relations. Create these relations in your database .
67
Department (dnoint primary key,dname)
· insert at least 10 records into both the relations.
· type the following select queries & write the output and the
business task performed by each query
1. Select empno from non-teaching union select empno from teaching;
2. Select empno from non-teaching union all select empno from teaching;
3. Select name from non-teaching intersect select name from teaching;
4. Select name from non-teaching intersect all select name from teaching;
5. Select name from non-teaching except select name from teaching;
6. Select name from non-teaching except all select name from teaching
Set B
Create the following relations, for an investment firm emp(emp-
id ,emp-name, address, bdate) Investor( inv-
name , inv-no, inv-date, inv-amt)
An employee may invest in one or more investments, hence he can be an
investor.But an investor need not be an employee of the firm.
Create the Relations accordingly, so that the relationship is handled properly and the
relations are in normalized form (3NF).
Assume appropriate data types for the attributes. Add any new attributes , as required by
the queries. Insert sufficient number of records in the relations / tables with appropriate
values as suggested by some of the queries.
Write the following queries & execute them.
1. List the distinct names of customers who are either employees, or investors or both.
2. List the names of customers who are either employees , or investors or both.
3. List the names of employees who are also investors.
4. List the names of employees who are not investors
Set C
Employee (emp_no, emp_name, address, city, birth_date,
designation,salary) Project (project_no, project_name, status)
Department (Dept_no, dept_name, location)
Constraints: Employee designation is either ‘manager’, ‘staff’ , ‘worker’.
There exists a one-to-many relationship between Department and Employee. Many
employees can work on many projects controlled by a department. Create the relations
accordingly, so that the relationship is handled properly and the relations are in
normalized form (3NF) and insert 5 records into each table.
Solve the following queries:
a) Find the details of employee who is having highest salary.
b) Delete all employees of department 20.
c) List the names and salary of employees sorted by their salary.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete 2:Late
3: Needs [ ] 4: complete[] 5:
Improvement[
Complete [ ] Well Done [ ]
Signature of Instructor
68
Assignment No.11
Queries &sub-queries, with joining of tables
To understand & practice session on nested queries & sub-queries using join operations.
Sub query:
A sub-query is a select-from-where expression that is nested within another query.
the ‘in’ & ‘not in’ connectivity tests for set
Set membership membership & absence
of set membership respectively.
the < some, > some, <= some, >= some, = some, <>
Set comparison some are the constructs allowed for comparison. = some
is same as the ‘in’ connectivity. <> some is not the same
as the ‘not n’i connectivity. Similarly sql also provides <
all, >all, <=all, >= all, <> all comparisons. <>all is same
as the ‘not in’ construct.
Set cardinality The ‘exists’ construct returns the value true if the
argument subquery is nonempty. We can test for
the non-existence of tuples
in a subquery by using the ‘not exists’ construct. The ‘not
exists ‘ construct can also be used to simulate the set
containment operation (the super set ). We can write
“relation A contains relation
B” as “not exists (B except A)”.
Set A
Create the following relation in your database (primary keys underlined)
Employee(ename, street, city)
Works(ename, company-name,
salary) Company(company-name,
city) Manages(ename, manager-
name )
An employee can work in one or more companies, a company can have one or more
employees working in it. Hence the relation ‘works’ with keyattributes as ename, company-
name.
An employee manages one or more employees, but an employee is managed by
exactly one employee ( a recursive relationship), hence the relation ‘manages’
with key ename.
Insert sufficient number of records in the relations / tables with appropriate values
as suggested by some of the queries.
Type the following queries , execute them and give the business task performed by each query
1. select ename from works w where salary >= all (select max(salary) from works));
2. select ename form works w where salary = (select max(salary) from
works w1 where w1.company-name = w.company-name));
3. select manager-name from manages where manager-name in(select ename from
works where company-name = “”);
4. select manager-name from manages where manager-name not in(select ename from
works where company-name = “ ”);
5. select ename from works w where salary > some (select salary from works where
company- name not in (select company-name from company where city = “ _”));
6. select ename from employee e where city = ( select city from employee e1 ,
manages m where m.ename = e.ename and m.manager-name = e1.ename);
7. select * from employee where ename in (select manager-name from manages)
8 select city count(*) from employee group by city having count(*) >= all (select count(*) from
69
employee group by city)
9. select ename from works w where salary <> all (select salary from
works where ename<>w.ename);
10. select company-name, sum(salary) from works w groupby company-name having sum(sal)
>= all ( select sum(sal) from works group by company-name)
11. select ename from employee e where city in(‘ ’,’ ’);
12. select ename from employee e where city = (select city from company c,
works w where w.ename = e.name and c.company-name = w.company-name);
Set B
Create the following relations :
Emp(eno,name,dno,salary)
Project(pno,pname,control-
dno,budget)
Each employee can work on one or more projects, and a project can have many
employees working in it. The number of hours worked on each project , by an
employee also needs to be stored.
Create the Relations accordingly, so that the relationship is handled properly and
the relations are in normalized form (3NF).
Assume appropriate data types for the attributes. Add any new attributes ,
new relations as required by the queries.
Insert sufficient number of records in the relations / tables with appropriate values
as suggested by some of the queries.
Write the queries for following business tasks & execute them.
1. list the names of departments that controls projects whose budget is greater than .
2.list the names of projects, controlled by department No , whose budget is greater
than atleast one project controlled by department No .
3. list the details of the projects with second maximum budget
70
Set C
Execute following queries on the relations mentioned in above case study
1. list the names of projects along with the controlling department name, for those
projects which has atleast employees working on it.
2. list the names of employees who is worked for more than 10 hrs on
atleast one project controlled by ‘ ’ dept.
3. list the names of employees , who are males , and earning the maximum
salary in their department.
4. list the names of employees who work in the same department as ‘ ’.
5. list the names of employees who do not live in or .
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2:Late Complete[]
3: Needs Improvement [ 4: Complete [ ] 5: Well Done [ ]
]
Signature of Instructor
71
Assignment No.12
Queries &sub queries, with joining of table
Execute the following queries on the table created in previous assignments.
Set A
Project-Employee database
Consider the database maintained by a company which stores the details of the projects
assigned to the employees.
Following are the tables:
72
Set C
Student- Teacher database
Consider the following database maintained by a school. The school maintains
information about students and the teachers. It also gives information of the subject
taught by the teacher.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2:Late Complete[]
3: Needs Improvement [ 4: Complete [ ] 5: Well Done [ ]
]
Signature of Instructor
73
Assignment No.13 Case
studies
Set A
Business trip database
Consider the business trip database that keeps track of the business trips of salesman in an office.
74
Set C
movie database
movies(m_name, release_year,
budget) actor(a_name, role,
charges, a_address)
producer(producer_id, name,
p_address)
each actor has acted in one or more movies. each producer has produced many movies and
each movie can be produced by more than one producers. each movie has one or more
actors acting in it, in different roles.
create the relations accordingly, so that the relationship is handled properly and the
relations are in normalized form(3nf).
insert sufficient number of appropriate records.
solve the queries:
1. list the names of actors who have acted in at least one movie, inwhich ‘ ’
has acted.
2. list the names of the movies with the highest budget.
3. list the names of actors who have acted in the maximum number of movies.
4. list the names of movies, produced by more than one producer.
5. list the names of actors who are given with the maximum charges for their movie.
6. list the names of producers who produce the same movie as ‘_ ’.
7. list the names of actors who do not live in or city.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2:Late Complete[]
3: Needs Improvement [ 4: Complete [ ] 5:Well Done [ ]
]
Signature of Instructor