Friday, June 19, 2026

NEP-SYBCS- DS-I Assignment- 3

 Assignment 3 Sorting Algorithms –Counting Sort, Merge Sort, Quick Sort


Set A
a) Accept the array of n integers from user and sort the array in ascending order by using
recursive Counting sort algorithm.
/*
 * C Program for counting sort
 */
#include <stdio.h>  
 
void counting_sort(int A[], int k, int n)
{
    int i, j;
    int B[15], C[100];
    for (i = 0; i <= k; i++)
        C[i] = 0;
    for (j = 1; j <= n; j++)
        C[A[j]] = C[A[j]] + 1;
    for (i = 1; i <= k; i++)
        C[i] = C[i] + C[i-1];
    for (j = n; j >= 1; j--)
    {
        B[C[A[j]]] = A[j];
        C[A[j]] = C[A[j]] - 1;
    }
    printf("The Sorted array is : ");
    for (i = 1; i <= n; i++)
        printf("%d ", B[i]);
}

int main()
{
    int n, k = 0, A[15], i;
    printf("Enter the number of input : ");
    scanf("%d", &n);
    printf("\nEnter the elements to be sorted :\n");
    for (i = 1; i <= n; i++)
    {
        scanf("%d", &A[i]);
        if (A[i] > k) {
            k = A[i];
        }
    }
    counting_sort(A, k, n);
    printf("\n");
    return 0;
}


b) Create random array of n integers and sort the array in ascending order by using recursive
Merge sort algorithm
Program

#include<stdio.h>
merge(int a[10],int l,int m,int u)
{
                int c[10],i,j,k;
                i=l;
                j=m+1;
                k=0;
                while(i<=m && j<=u)
                {
                                if(a[i]<a[j])
                                {
                                                c[k]=a[i];
                                                k++;i++;
                                }
                                else
                                {
                                                c[k]=a[j];
                                                k++;j++;
                                }
                }
                while(i<=m)
                {
                                c[k]=a[i];
                                i++;k++;
                }
                while(j<=u)
                {
                                c[k]=a[j];
                                k++;j++;
                }
                for(i=l,j=0;i<=u;i++,j++)
                                a[i]=c[j];
}

void generate(int a[10],int n)
{
                int i;
                for(i=0;i<n;i++)
                                a[i]=rand()%10;
}

merge_sort(int a[10],int i,int j)
{
                int k=0;
                if(i<j)
                {
                                k=(i+j)/2;
                                merge_sort(a,i,k);
                                merge_sort(a,k+1,j);
                                merge(a,i,k,j);
                }
}

main()
{
                int i,n,a[10];
                printf("how many elements:");
                scanf("%d",&n);
                generate(a,n);
                printf("elements are:\n");
                for(i=0;i<n;i++)
                                printf("%d\t",a[i]);
                merge_sort(a,0,n-1);
                printf("\nafter sorting:\n");
                for(i=0;i<n;i++)
                printf("%d\t",a[i]);
}



c) Accept the array of n integers from user and sort the array in ascending order by using
recursive Quick sort algorithm.
Program

#include<stdio.h>
enum bool {false,true};
void disp(int a[],int l,int u)
{
                int i;
                for(i=l;i<=u;i++)
                                printf("%d\t",a[i]);
}

void quick(int a[],int l,int u)
{
                int temp,piv,left,right;
                enum bool pivot_places=false;
                left=l;
                right=u;
                piv=l;
                if(l>=u)
                                return;
                printf("\nsublist:\n");
                disp(a,l,u);
                while(pivot_places==false)
                {
                                while(a[piv]<=a[right] && piv!=right)
                                                right--;
                                if(piv==right)
                                                pivot_places=true;
                                if(a[piv]>a[right])
                                {
                                                temp=a[piv];
                                                a[piv]=a[right];
                                                a[right]=temp;
                                                piv=right;
                                }
                                while(a[piv]>=a[left] && piv!=left)
                                                left++;
                                if(piv==left)
                                                pivot_places=true;
                                if(a[piv]<a[left])
                                {
                                                temp=a[piv];
                                                a[piv]=a[left];
                                                a[left]=temp;
                                                piv=left;
                                }
                }
                disp(a,l,u);
                quick(a,l,piv-1);
                quick(a,piv+1,u);
}

void generate(int a[],int n)
{
                int i;
                for(i=0;i<n;i++)
                                a[i]=rand()%20;
}

main()
{
                int a[10],n,i;
                printf("how many elements:");
                scanf("%d",&n);
                generate(a,n);
                printf("\nelements are:");
                for(i=0;i<n;i++)
                                printf("%d\t",a[i]);
                quick(a,0,n-1);
                printf("\nafter sorting:\n");
                for(i=0;i<n;i++)
                                printf("%d\t",a[i]);
}


Set B
a) Read the data from the ‘employee.txt’ file and sort on age using Counting sort and Merge
sort. Write the sorted data to another file 'sortedemponage.txt'.

employee.txt (Input File)

Amit 25 30000
Neha 22 35000
Rahul 30 45000
Priya 24 40000
Karan 28 38000

(Format: Emp_name Age Salary)

1. Counting Sort on Age

#include <stdio.h>

#include <string.h>

struct Employee

{

    char name[30];

    int age;

    float salary;

};


int main()

{

    struct Employee emp[100], output[100];

    int count[101] = {0};

    int n = 0, i;


    FILE *fp, *fs;


    fp = fopen("employee.txt", "r");


    if (fp == NULL)

    {

        printf("File not found.\n");

        return 1;

    }


    while (fscanf(fp, "%s%d%f",

                  emp[n].name,

                  &emp[n].age,

                  &emp[n].salary) != EOF)

    {

        n++;

    }


    fclose(fp);


    // Count frequency of ages

    for (i = 0; i < n; i++)

        count[emp[i].age]++;


    // Cumulative count

    for (i = 1; i <= 100; i++)

        count[i] += count[i - 1];


    // Build output array

    for (i = n - 1; i >= 0; i--)

    {

        output[count[emp[i].age] - 1] = emp[i];

        count[emp[i].age]--;

    }


    fs = fopen("sortedemponage.txt", "w");


    fprintf(fs, "Name\tAge\tSalary\n");


    for (i = 0; i < n; i++)

        fprintf(fs, "%s\t%d\t%.2f\n",

                output[i].name,

                output[i].age,

                output[i].salary);


    fclose(fs);


    printf("Data sorted using Counting Sort.\n");


    return 0;

}



2. Merge Sort on Age

#include <stdio.h>

#include <string.h>


struct Employee

{

    char name[30];

    int age;

    float salary;

};


void merge(struct Employee a[], int low, int mid, int high)

{

    struct Employee temp[100];

    int i = low, j = mid + 1, k = low;


    while (i <= mid && j <= high)

    {

        if (a[i].age <= a[j].age)

            temp[k++] = a[i++];

        else

            temp[k++] = a[j++];

    }


    while (i <= mid)

        temp[k++] = a[i++];


    while (j <= high)

        temp[k++] = a[j++];


    for (i = low; i <= high; i++)

        a[i] = temp[i];

}


void mergeSort(struct Employee a[], int low, int high)

{

    if (low < high)

    {

        int mid = (low + high) / 2;

        mergeSort(a, low, mid);

        mergeSort(a, mid + 1, high);

        merge(a, low, mid, high);

    }

}


int main()

{

    struct Employee emp[100];

    int n = 0, i;


    FILE *fp, *fs;


    fp = fopen("employee.txt", "r");


    if (fp == NULL)

    {

        printf("File not found.\n");

        return 1;

    }


    while (fscanf(fp, "%s%d%f",

                  emp[n].name,

                  &emp[n].age,

                  &emp[n].salary) != EOF)

    {

        n++;

    }


    fclose(fp);


    mergeSort(emp, 0, n - 1);


    fs = fopen("sortedemponage.txt", "w");


    fprintf(fs, "Name\tAge\tSalary\n");


    for (i = 0; i < n; i++)

        fprintf(fs, "%s\t%d\t%.2f\n",

                emp[i].name,

                emp[i].age,

                emp[i].salary);


    fclose(fs);


    printf("Data sorted using Merge Sort.\n");


    return 0;

}


b) Read the data from the file and sort on names in alphabetical order (use strcmp) using Quick
sort and write the sorted data to another file 'sortedemponname.txt'.

employee.txt (Input File)

Amit 25 30000
Neha 22 35000
Rahul 30 45000
Priya 24 40000
Karan 28 38000

Format: Emp_name Age Salary


C Program (Quick Sort on Employee Name)

#include <stdio.h>
#include <string.h>

struct Employee
{
char name[30];
int age;
float salary;
};

void quickSort(struct Employee emp[], int low, int high);
int partition(struct Employee emp[], int low, int high);

int main()
{
struct Employee emp[100];
int n = 0, i;
FILE *fp, *fs;

fp = fopen("employee.txt", "r");

if (fp == NULL)
{
printf("File not found.\n");
return 1;
}

while (fscanf(fp, "%s%d%f",
emp[n].name,
&emp[n].age,
&emp[n].salary) != EOF)
{
n++;
}

fclose(fp);

quickSort(emp, 0, n - 1);

fs = fopen("sortedemponname.txt", "w");

if (fs == NULL)
{
printf("Cannot create output file.\n");
return 1;
}

fprintf(fs, "Name\tAge\tSalary\n");

for (i = 0; i < n; i++)
{
fprintf(fs, "%s\t%d\t%.2f\n",
emp[i].name,
emp[i].age,
emp[i].salary);
}

fclose(fs);

printf("Data sorted successfully using Quick Sort.\n");
printf("Sorted data stored in sortedemponname.txt\n");

return 0;
}

int partition(struct Employee emp[], int low, int high)
{
struct Employee pivot = emp[high], temp;
int i = low - 1, j;

for (j = low; j < high; j++)
{
if (strcmp(emp[j].name, pivot.name) < 0)
{
i++;
temp = emp[i];
emp[i] = emp[j];
emp[j] = temp;
}
}

temp = emp[i + 1];
emp[i + 1] = emp[high];
emp[high] = temp;

return i + 1;
}

void quickSort(struct Employee emp[], int low, int high)
{
if (low < high)
{
int p = partition(emp, low, high);
quickSort(emp, low, p - 1);
quickSort(emp, p + 1, high);
}
}

Thursday, June 18, 2026

NEP-SYBCS-DS-I Assignment-2

 Assignment 2 Sorting Algorithms (Non Recursive) – Bubble Sort, Insertion Sort, Selection Sort

Set A

a) Sort a random array of n integers (accept the value of n from user) in ascending order by using bubble sort algorithm.

Program


#include <stdio.h>

#define MAXSIZE 10


void main()

{

    int array[MAXSIZE];

    int i, j, num, temp;


    printf("Enter the value of num \n");

    scanf("%d", &num);

    printf("Enter the elements one by one \n");

    for (i = 0; i < num; i++)

    {

        scanf("%d", &array[i]);

    }

    printf("Input array is \n");

    for (i = 0; i < num; i++)

    {

        printf("%d\n", array[i]);

    }

    for (i = 0; i < num; i++)

    {

        for (j = 0; j < (num - i - 1); j++)

        {

            if (array[j] > array[j + 1])

            {

                temp = array[j];

                array[j] = array[j + 1];

                array[j + 1] = temp;

            }

        }

    }

    printf("Sorted array is...\n");

    for (i = 0; i < num; i++)

    {

        printf("%d\n", array[i]);

    }

}


b) Sort a random array of n integers (create a random array of n integers) in ascending order by using insertion sort algorithm.

Program


#include <stdio.h>

int main()

{

  int n, array[1000], c, d, t;


  printf("Enter number of elements\n");

  scanf("%d", &n);


  printf("Enter %d integers\n", n);


  for (c = 0; c < n; c++) {

    scanf("%d", &array[c]);

  }


  for (c = 1 ; c <= n - 1; c++) {

    d = c;


    while ( d > 0 && array[d-1] > array[d]) {

      t          = array[d];

      array[d]   = array[d-1];

      array[d-1] = t;


      d--;

    }

  }


  printf("Sorted list in ascending order:\n");


  for (c = 0; c <= n - 1; c++) {

    printf("%d\n", array[c]);

  }


  return 0;

}


c) Sort a random array of n integers (accept the value of n from user) in ascending order by using selection sort algorithm.

#include <stdio.h>

void selection_sort();

int a[30], n;

void main()

{

    int i;

    printf("\nEnter size of an array: ");

    scanf("%d", &n);

    printf("\nEnter elements of an array:\n");

    for(i=0; i<n; i++)

        scanf("%d", &a[i]);

    selection_sort();

    printf("\n\nAfter sorting:\n");

    for(i=0; i<n; i++)

        printf("\n%d", a[i]);

}

void selection_sort()

{

    int i, j, min, temp;

    for (i=0; i<n; i++)

    {

        min = i;

        for (j=i+1; j<n; j++)

        {

            if (a[j] < a[min])

                min = j;

        }

        temp = a[i];

        a[i] = a[min];

        a[min] = temp;

    }

}


Set B

a) Read the data from “Student.txt (Stud_name, Age, Percentage)” file and sort on Stud_name using bubble sort.(Create a separate sorted file).

Student.txt (Input File)

Amit 20 78.5
Neha 19 88.0
Rahul 21 72.5
Priya 20 91.5
Karan 22 68.0


#include <stdio.h> #include <stdlib.h> #include <string.h> struct Student { char Stud_name[30]; int Age; float Percentage; }; int main() { struct Student s[100], temp; int n = 0, i, j; FILE *fp, *fs; fp = fopen("Student.txt", "r"); if (fp == NULL) { printf("Unable to open Student.txt\n"); return 1; } // Read records from file while (fscanf(fp, "%s %d %f", s[n].Stud_name, &s[n].Age, &s[n].Percentage) != EOF) { n++; } fclose(fp); // Bubble Sort on Stud_name for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) { if (strcmp(s[j].Stud_name, s[j + 1].Stud_name) > 0) { temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; } } } // Create Sorted File fs = fopen("SortedStudent.txt", "w"); if (fs == NULL) { printf("Unable to create SortedStudent.txt\n"); return 1; } fprintf(fs, "Name\tAge\tPercentage\n"); for (i = 0; i < n; i++) { fprintf(fs, "%s\t%d\t%.2f\n", s[i].Stud_name, s[i].Age, s[i].Percentage); } fclose(fs); printf("Records sorted successfully.\n"); printf("Sorted data stored in SortedStudent.txt\n"); return 0; }


b) Read the data from “Student.txt (Stud_name, Age, Percentage)” file and sort on Age using insertion sort. (Create a separate sorted file).

Student.txt (Input File)

Amit 20 78.5
Neha 19 88.0
Rahul 21 72.5
Priya 20 91.5
Karan 22 68.0

#include <stdio.h> #include <stdlib.h> struct Student { char Stud_name[30]; int Age; float Percentage; }; int main() { struct Student s[100], key; int n = 0, i, j; FILE *fp, *fs; fp = fopen("Student.txt", "r"); if (fp == NULL) { printf("Unable to open Student.txt\n"); return 1; } // Read data from file while (fscanf(fp, "%s %d %f", s[n].Stud_name, &s[n].Age, &s[n].Percentage) != EOF) { n++; } fclose(fp); // Insertion Sort on Age for (i = 1; i < n; i++) { key = s[i]; j = i - 1; while (j >= 0 && s[j].Age > key.Age) { s[j + 1] = s[j]; j--; } s[j + 1] = key; } // Create sorted file fs = fopen("SortedStudent.txt", "w"); if (fs == NULL) { printf("Unable to create SortedStudent.txt\n"); return 1; } fprintf(fs, "Name\tAge\tPercentage\n"); for (i = 0; i < n; i++) { fprintf(fs, "%s\t%d\t%.2f\n", s[i].Stud_name, s[i].Age, s[i].Percentage); } fclose(fs); printf("Records sorted successfully.\n"); printf("Sorted data stored in SortedStudent.txt\n"); return 0; }


c) Read the data from “Student.txt (Stud_name, Age, Percentage)” file and sort on Percentage using selection sort.(Create a separate sorted file).


Student.txt (Input File)

Amit 20 78.5
Neha 19 88.0
Rahul 21 72.5
Priya 20 91.5
Karan 22 68.0


#include <stdio.h> #include <stdlib.h> struct Student { char Stud_name[30]; int Age; float Percentage; }; int main() { struct Student s[100], temp; int n = 0, i, j, min; FILE *fp, *fs; fp = fopen("Student.txt", "r"); if (fp == NULL) { printf("Unable to open Student.txt\n"); return 1; } // Read data from file while (fscanf(fp, "%s %d %f", s[n].Stud_name, &s[n].Age, &s[n].Percentage) != EOF) { n++; } fclose(fp); // Selection Sort on Percentage for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) { if (s[j].Percentage < s[min].Percentage) min = j; } if (min != i) { temp = s[i]; s[i] = s[min]; s[min] = temp; } } // Create sorted file fs = fopen("SortedStudent.txt", "w"); if (fs == NULL) { printf("Unable to create SortedStudent.txt\n"); return 1; } fprintf(fs, "Name\tAge\tPercentage\n"); for (i = 0; i < n; i++) { fprintf(fs, "%s\t%d\t%.2f\n", s[i].Stud_name, s[i].Age, s[i].Percentage); } fclose(fs); printf("Records sorted successfully.\n"); printf("Sorted data stored in SortedStudent.txt\n"); return 0; }



NEP-SYBCS DS-I Assignment -I

Assignment 1:-  Searching Algorithms

Set A

a) Create a random array of n integers. Accept a value x from user and use linear search algorithm to check whether the number is present in the array or not and output the position if the number is present.

#include<stdio.h>
#define max 10

int main()
{
int a[max],k,i,n,flag=0,index;
printf("Enter n:");
scanf("%d",&n);

generate(a,n);
printf("Random elements are\n");
   for(i=0;i<n;i++)
      printf("%d\n",a[i]);

printf("Enter number to search: ");
   scanf("%d",&k);
linearsearch(a,n,k);
}
void generate(int a[],int n)
{
int i;
for(i=0;i<n;i++)
   a[i]=rand()%100;

}
void linearsearch(int a[],int n,int k)
{
int i,flag=0,index ;
for(i=0;i<n;i++)
if(a[i]==k)
{
flag=1;
index=i;
}
if(flag==1)
{
printf("Element found at index %d",index+1);
}
else
printf("Not Found");
}


b) Accept n sorted values in array from user. Accept a value x from user and use binary search algorithm to check whether the number is present in sorted array or not and output the position if the number is present.

#include<stdio.h>
#define max 10

int main()
{
int a[max],i,n,key,high,low=0,mid;

printf("how many array elements:");
scanf("%d",&n);
printf("Enter array:");
accept(a,n);//calling function

printf("Array elements are:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);//displaying array

printf("\nEnter number to search:");
scanf("%d",&key);
binarysearch(0,n-1,a,key);//calling function
}

//function binary
void binarysearch(int low,int high,int a[],int key)
{
 int mid;
 if(low>high)
 {
  printf("Search is not successful\n");
  return;
 }
 mid=(low+high)/2;
 if(key==a[mid])
 {
  printf("Search Found at index %d\n",mid+1);
  return;
 }

 else if(key<a[mid])
 {
  return binarysearch(low,mid-1,a,key);
 }
 else if(key>a[mid])
 {
  return binarysearch(mid+1,high,a,key);
 }
}
//Accept function to store element
void accept(int a[],int n)
{
int i;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}


Set B

a) Read the data from file 'student.txt' containing names of student and their class (FY, SY, TY). Accept a student name from user and use linear search algorithm to check whether the name is present in the file and output the Class of student otherwise output “Student not in the list”.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>


#define MAX_STUDENTS 100

#define NAME_LEN 50

#define CLASS_LEN 5


// Structure to store student records

typedef struct {

    char name[NAME_LEN];

    char s_class[CLASS_LEN];

} Student;


int main() {

    FILE *fp;

    Student s[MAX_STUDENTS];

    char search_name[NAME_LEN];

    int n = 0;

    int found = 0;


    fp = fopen("student.txt", "r");

    if (fp == NULL) {

        printf("Error: Could not open file student.txt\n");

        return 1;

    }

    while (fscanf(fp, "%s %s", s[n].name, s[n].s_class) != EOF) {

        n++;

        if (n >= MAX_STUDENTS) break; 

    }

    fclose(fp);

    printf("Enter the student name to search: ");

    scanf("%s", search_name);

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

        // Perform a case-sensitive string match

        if (strcmp(s[i].name, search_name) == 0) {

            printf("Class: %s\n", s[i].s_class);

            found = 1;

            break; // Stop looking once the item is found

        }

    }

    if (!found) {

        printf("Student not in the list\n");

    }

    return 0;

}


create student.txt file 

Amit FY
Rahul SY
Pooja TY
Sneha SY

b) Read the data from file 'student.txt' containing names of student and their class(FY, SY,TY). Accept a student name from user and use binary search algorithm to check whether the name is present in the file  and output the class of student otherwise output “Student not in the list”.

Create Student.txt file 

Amit FY

Kiran SY

Rahul TY

Zoya SY



Complete C Code Implementationc#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct {

    char name[50];

    char s_class[10]; // Named s_class to avoid conflict with C++ keywords

} Student;


int read_file(Student s[]);

void sort_records(Student s[], int n);

void binary_search(Student s[], int n, char key[]);


int main() {

    Student s[100];

    int n;

    char search_name[50];

    n = read_file(s);

    if (n == 0) {

        printf("No records found or file error.\n");

        return 1;

    }


    sort_records(s, n);

     printf("Enter the name of the student to search: ");

    scanf("%s", search_name);

    binary_search(s, n, search_name);

    return 0;

}


int read_file(Student s[]) {

    FILE *fp;

    int i = 0;

    fp = fopen("student.txt", "r");

    if (fp == NULL) {

        printf("Error: Cannot open file 'student.txt'. Make sure it exists.\n");

        return 0;

    }

    while (fscanf(fp, "%s %s", s[i].name, s[i].s_class) != EOF) {

        i++;

    }

    fclose(fp);

    return i; // Returns total number of students read

}


void sort_records(Student s[], int n) {

    int i, j;

    Student temp;


    for (i = 0; i < n - 1; i++) {

        for (j = 0; j < n - i - 1; j++) {

            // Compare names using strcmp

            if (strcmp(s[j].name, s[j + 1].name) > 0) {

                temp = s[j];

                s[j] = s[j + 1];

                s[j + 1] = temp;

            }

        }

    }

}


void binary_search(Student s[], int n, char key[]) {

    int low = 0;

    int high = n - 1;

    int mid;

    int found = 0;


    while (low <= high) {

        mid = (low + high) / 2;

      int res = strcmp(s[mid].name, key);

        if (res == 0) {

                   printf("Class of student: %s\n", s[mid].s_class);

            found = 1;

            break;

        } 

        else if (res < 0) {

                    low = mid + 1;

        } 

        else {

                     high = mid - 1;

        }

    }


    if (!found) {

        printf("Student not in the list\n");

    }

}



Saturday, January 24, 2026

SYBCS-DBMS-II-Triggers

 Assignment 5: Triggers.


SET A

Movie – Actor Database

Consider the following database

Movie (m_name varchar (25), release_year integer, budget money)

Actor (a_name varchar(30), role varchar(30), charges money, a_address varchar(30) ) Movie

and Actor are related with many to many relationship.

Create the above database in PostGreSQL and insert sufficient records.

a. Write a trigger which will be executed whenever an actor is deleted from the actor table, display

appropriate message.

b. Write a trigger which will be executed whenever a movie is deleted from the movie table, display

appropriate message.

c. Write a trigger which will be executed whenever insertion is made to the movie table. If the

budget is less than 1,00,000 do not allow the insertion. Give appropriate message.

-- Movie Table

CREATE TABLE Movie (

m_name VARCHAR(25) PRIMARY KEY,

release_year INT,

budget MONEY

);

-- Actor Table

CREATE TABLE Actor (

a_name VARCHAR(30) PRIMARY KEY,

role VARCHAR(30),

charges MONEY,

a_address VARCHAR(30)

);

-- Junction Table for Many-to-Many Relationship

CREATE TABLE Movie_Actor (

m_name VARCHAR(25),

a_name VARCHAR(30),

PRIMARY KEY (m_name, a_name),

FOREIGN KEY (m_name) REFERENCES Movie(m_name),

FOREIGN KEY (a_name) REFERENCES Actor(a_name)

);

2. Insert Sample Records

sql

-- Insert into Movie

INSERT INTO Movie VALUES

('Inception', 2010, 160000000),

('Titanic', 1997, 200000000),

('The Matrix', 1999, 63000000);

-- Insert into Actor

INSERT INTO Actor VALUES

('Leonardo DiCaprio', 'Lead', 20000000, 'LA'),

('Kate Winslet', 'Lead', 15000000, 'UK'),

('Keanu Reeves', 'Lead', 10000000, 'Canada');

-- Insert into Movie_Actor

INSERT INTO Movie_Actor VALUES

('Inception', 'Leonardo DiCaprio'),

('Titanic', 'Leonardo DiCaprio'),

('Titanic', 'Kate Winslet'),

('The Matrix', 'Keanu Reeves');

3. Triggers

a) Trigger on Actor deletion Display message whenever an actor is deleted

sql

-- Function for Actor deletion

CREATE OR REPLACE FUNCTION actor_delete_msg()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

RAISE NOTICE 'Actor "%" is deleted from Actor table', OLD.a_name;

RETURN OLD;

END;

$$;

-- Trigger on DELETE

CREATE TRIGGER trg_actor_delete

AFTER DELETE ON Actor

FOR EACH ROW

EXECUTE FUNCTION actor_delete_msg();

Test

sql

DELETE FROM Actor WHERE a_name = 'Keanu Reeves';

-- NOTICE: Actor "Keanu Reeves" is deleted from Actor table

b) Trigger on Movie deletion Display message whenever a movie is deleted

sql

-- Function for Movie deletion

CREATE OR REPLACE FUNCTION movie_delete_msg()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

RAISE NOTICE 'Movie "%" is deleted from Movie table', OLD.m_name;

RETURN OLD;

END;

$$;

-- Trigger on DELETE

CREATE TRIGGER trg_movie_delete

AFTER DELETE ON Movie

FOR EACH ROW

EXECUTE FUNCTION movie_delete_msg();

Test

sql

DELETE FROM Movie WHERE m_name = 'Titanic';

-- NOTICE: Movie "Titanic" is deleted from Movie table

c) Trigger on Movie insertion to check budget Prevent insertion if budget < 100,000

sql

-- Function for Movie insertion

CREATE OR REPLACE FUNCTION check_movie_budget()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$


BEGIN

IF NEW.budget < 100000 THEN

RAISE EXCEPTION 'Insertion not allowed. Budget less than 1,00,000: %', NEW.budget;

END IF;

RETURN NEW;

END;

$$;

-- Trigger on INSERT

CREATE TRIGGER trg_movie_insert

BEFORE INSERT ON Movie

FOR EACH ROW

EXECUTE FUNCTION check_movie_budget();

Test

sql

-- Valid insertion

INSERT INTO Movie VALUES ('Avatar', 2009, 237000000); -- Works fine

-- Invalid insertion

INSERT INTO Movie VALUES ('LowBudgetMovie', 2026, 50000);

-- ERROR: Insertion not allowed. Budget less than 1,00,000: 50000


SET B

Doctor – Hospital Database

Consider the following database

Doctor (d_no int, d_name varchar(30), specialization varchar(35), charges int)

Hospital (h_no int, h_name varchar(20), city varchar(10))

Doctor and Hospital are related with many to one relationship.

Create the above database in PostGreSQL and insert sufficient records.

a. Write a trigger before insert/update on Doctor table. Raise exception if charges are <0.

b. Write a trigger that restricts insertion of charges value greater than 400.

-- Create Hospital table

CREATE TABLE Hospital (

h_no int PRIMARY KEY,

h_name varchar(20),

city varchar(10)

);

-- Create Doctor table (Many-to-One: Many doctors belong to one hospital)

CREATE TABLE Doctor (

d_no int PRIMARY KEY,

d_name varchar(30),

specialization varchar(35),

charges int,

h_no int REFERENCES Hospital(h_no)

);


-- Insert sample records

INSERT INTO Hospital VALUES (1, 'City Care', 'Mumbai'), (2, 'Life Line', 'Pune');

INSERT INTO Doctor VALUES (101, 'Dr. Sharma', 'Cardiology', 500, 1);

CREATE OR REPLACE FUNCTION validate_doctor_charges()

RETURNS TRIGGER AS $$

BEGIN

-- a. Check if charges are less than 0

IF NEW.charges < 0 THEN

RAISE EXCEPTION 'Invalid Charges: Charges cannot be negative.';

END IF;

-- b. Restrict insertion of charges greater than 400

IF NEW.charges > 400 THEN

RAISE EXCEPTION 'Invalid Charges: Charges cannot exceed 400.';

END IF;

RETURN NEW;

END;

$$ LANGUAGE plpgsql;

Create the Trigger

CREATE TRIGGER trg_check_charges

BEFORE INSERT OR UPDATE ON Doctor

FOR EACH ROW

EXECUTE FUNCTION validate_doctor_charges();

SET C

Student – Subject database

Consider the following database :

Student (rollno integer, name varchar(30),city varchar(50),class varchar(10))

Subject(Scode varchar(10),subject name varchar(20))

Student and subject are related with M-M relationship with attributes marks_scored.

Create the above database in PostGreSQL and insert sufficient records

a. Write a trigger before insert/update the marks_scored. Raise exception if Marks are negative.

b. Write a trigger which is executed when insertion is made in the student-subject table. If

marks_scored is less than 0, give appropriate message and do not allow the insertion.

c. Write a trigger which will prevent deleting students from ‘Mumbai’ city.

-- Student Table

CREATE TABLE Student (

rollno INT PRIMARY KEY,

name VARCHAR(30),

city VARCHAR(50),

class VARCHAR(10)

);


-- Subject Table

CREATE TABLE Subject (

scode VARCHAR(10) PRIMARY KEY,

subject_name VARCHAR(20)

);

-- Student_Subject Table (junction table with marks_scored)

CREATE TABLE Student_Subject (

rollno INT,

scode VARCHAR(10),

marks_scored INT,

PRIMARY KEY (rollno, scode),

FOREIGN KEY (rollno) REFERENCES Student(rollno),

FOREIGN KEY (scode) REFERENCES Subject(scode)

);

2. Insert Sample Records

sql

-- Insert into Student

INSERT INTO Student VALUES

(1, 'Amit', 'Mumbai', 'BScCS'),

(2, 'Sneha', 'Pune', 'BScIT'),

(3, 'Rahul', 'Mumbai', 'BCA');

-- Insert into Subject

INSERT INTO Subject VALUES

('S101', 'DBMS'),

('S102', 'AI'),

('S103', 'OS');

-- Insert into Student_Subject

INSERT INTO Student_Subject VALUES

(1, 'S101', 85),

(1, 'S102', 90),

(2, 'S101', 70),

(3, 'S103', 60);

3. Triggers

a) Trigger BEFORE INSERT/UPDATE on marks_scored Raise exception if marks are negative

sql

-- Function to check marks before insert/update

CREATE OR REPLACE FUNCTION check_marks_before_insert_update()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

IF NEW.marks_scored < 0 THEN

RAISE EXCEPTION 'Marks cannot be negative: %', NEW.marks_scored;


END IF;

RETURN NEW;

END;

$$;

-- Trigger BEFORE INSERT

CREATE TRIGGER trg_marks_before_insert

BEFORE INSERT ON Student_Subject

FOR EACH ROW

EXECUTE FUNCTION check_marks_before_insert_update();

-- Trigger BEFORE UPDATE

CREATE TRIGGER trg_marks_before_update

BEFORE UPDATE ON Student_Subject

FOR EACH ROW

EXECUTE FUNCTION check_marks_before_insert_update();

Test


INSERT INTO Student_Subject VALUES (2, 'S102', -10);

-- ERROR: Marks cannot be negative: -10

b) Trigger on INSERT in Student_Subject to prevent negative marks Display message and prevent insertion

sql

-- Function to prevent negative marks on insert

CREATE OR REPLACE FUNCTION prevent_negative_marks_insert()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

IF NEW.marks_scored < 0 THEN

RAISE EXCEPTION 'Insertion not allowed: Marks are negative (%).', NEW.marks_scored;

END IF;

RETURN NEW;

END;

$$;

-- Trigger BEFORE INSERT

CREATE TRIGGER trg_prevent_negative_marks

BEFORE INSERT ON Student_Subject

FOR EACH ROW

EXECUTE FUNCTION prevent_negative_marks_insert();

Test

sql

INSERT INTO Student_Subject VALUES (3, 'S102', -5);

-- ERROR: Insertion not allowed: Marks are negative (-5).

✅ Note: This trigger complements the previous one; ensures marks validation during insert.


c) Trigger to prevent deleting students from 'Mumbai'

sql

-- Function to prevent deletion of Mumbai students

CREATE OR REPLACE FUNCTION prevent_mumbai_student_delete()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

IF OLD.city = 'Mumbai' THEN

RAISE EXCEPTION 'Cannot delete student from Mumbai: %', OLD.name;

END IF;

RETURN OLD;

END;

$$;

-- Trigger BEFORE DELETE

CREATE TRIGGER trg_prevent_mumbai_delete

BEFORE DELETE ON Student

FOR EACH ROW

EXECUTE FUNCTION prevent_mumbai_student_delete();

Test

sql

DELETE FROM Student WHERE rollno = 1;

-- ERROR: Cannot delete student from Mumbai: Amit

DELETE FROM Student WHERE rollno = 2;

-- Works fine (Sneha is from Pune)


SET D

Customer – Account database

Consider the following database

Customer (cno integer, cname varchar(20), city varchar(20))

Account (a_no int, a_type varchar(10), opening_date date, balance money) Customer

and Account are related with one to many relationship

Create the above database in PostGreSQL and insert sufficient records.

a. Write a trigger which is executed whenever update is made to the account table. If the balance

becomes less than 1000, print an error message that balance cannot be less than 1000.

b. Write a trigger before deleting an account record from Account table. Raise a notice and display

the message “Account record is being deleted.”

c. Write a trigger before inserting an account record in Account table and raise exception if

balance is <500.

-- Customer Table

CREATE TABLE Customer (

cno INT PRIMARY KEY,

cname VARCHAR(20),

city VARCHAR(20)

);


-- Account Table

CREATE TABLE Account (

a_no INT PRIMARY KEY,

cno INT REFERENCES Customer(cno),

a_type VARCHAR(10),

opening_date DATE,

balance MONEY

);

2. Insert Sample Records

-- Insert into Customer

INSERT INTO Customer VALUES

(1, 'Amit', 'Mumbai'),

(2, 'Sneha', 'Pune'),

(3, 'Rahul', 'Delhi');

-- Insert into Account

INSERT INTO Account VALUES

(101, 1, 'Savings', '2022-01-10', 5000),

(102, 2, 'Current', '2022-05-15', 1500),

(103, 3, 'Savings', '2022-03-20', 2000);

3. Triggers

a) Trigger on UPDATE of Account balance Raise exception if balance < 1000

sql

-- Function for balance check on update

CREATE OR REPLACE FUNCTION check_balance_update()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

IF NEW.balance < 1000 THEN

RAISE EXCEPTION 'Balance cannot be less than 1000. Current balance: %', NEW.balance;

END IF;

RETURN NEW;

END;

$$;

-- Trigger BEFORE UPDATE

CREATE TRIGGER trg_check_balance_update

BEFORE UPDATE ON Account

FOR EACH ROW

EXECUTE FUNCTION check_balance_update();

Test

sql

UPDATE Account SET balance = 900 WHERE a_no = 101;

-- ERROR: Balance cannot be less than 1000. Current balance: 900

b) Trigger BEFORE DELETE on Account Display notice “Account record is being deleted.”

sql

-- Function for delete notice

CREATE OR REPLACE FUNCTION account_delete_notice()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

RAISE NOTICE 'Account record is being deleted. Account No: %', OLD.a_no;

RETURN OLD;

END;

$$;

-- Trigger BEFORE DELETE

CREATE TRIGGER trg_account_delete_notice

BEFORE DELETE ON Account

FOR EACH ROW

EXECUTE FUNCTION account_delete_notice();

Test

sql

DELETE FROM Account WHERE a_no = 103;

-- NOTICE: Account record is being deleted. Account No: 103

c) Trigger BEFORE INSERT on Account Raise exception if balance < 500

sql

-- Function for insert validation

CREATE OR REPLACE FUNCTION check_balance_insert()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

IF NEW.balance < 500 THEN

RAISE EXCEPTION 'Insertion not allowed. Balance cannot be less than 500. Entered: %',

NEW.balance;

END IF;

RETURN NEW;

END;

$$;

-- Trigger BEFORE INSERT

CREATE TRIGGER trg_check_balance_insert

BEFORE INSERT ON Account

FOR EACH ROW

EXECUTE FUNCTION check_balance_insert();

Test


sql

-- Valid insertion

INSERT INTO Account VALUES (104, 2, 'Savings', '2023-01-01', 2000);

-- Invalid insertion

INSERT INTO Account VALUES (105, 1, 'Current', '2023-01-05', 400);

-- ERROR: Insertion not allowed. Balance cannot be less than 500. Entered: 400


SET E

Project-Employee Database

Consider the following Entities and their Relationships for Project-Employee database.

Project (pno integer, pname char (30), ptype char (20), duration integer)

Employee (eno integer, ename char (20), qualification char (15), joining_date date)

Relationship between Project and Employee is many to many with descriptive

attribute start_date date, no_of_hours_worked integer.

Constraints: Primary Key, pname should not be null.

Create trigger for the following:

a. Write a trigger before inserting into an employee table to check current date should be always

greater than joining date. Display appropriate message.

b. Write a trigger before inserting into a project table to check duration should be always greater

than zero. Display appropriate message.

c. Write a trigger before deleting an employee record from employee table. Raise a notice and

display the message “Employee record is being deleted”.

-- Project Table

CREATE TABLE Project (

pno INT PRIMARY KEY,

pname CHAR(30) NOT NULL,

ptype CHAR(20),

duration INT

);

-- Employee Table

CREATE TABLE Employee (

eno INT PRIMARY KEY,

ename CHAR(20),

qualification CHAR(15),

joining_date DATE

);

-- Junction Table for Many-to-Many Relationship

CREATE TABLE Project_Employee (

pno INT,

eno INT,

start_date DATE,

no_of_hours_worked INT,

PRIMARY KEY (pno, eno),

FOREIGN KEY (pno) REFERENCES Project(pno),


FOREIGN KEY (eno) REFERENCES Employee(eno)

);

2. Insert Sample Records

sql

-- Insert into Project

INSERT INTO Project VALUES

(1, 'ERP System', 'Software', 12),

(2, 'Website Dev', 'Web', 6);

-- Insert into Employee

INSERT INTO Employee VALUES

(101, 'Amit', 'MScCS', '2020-01-10'),

(102, 'Sneha', 'MCA', '2019-07-15');

-- Insert into Project_Employee

INSERT INTO Project_Employee VALUES

(1, 101, '2022-01-01', 120),

(2, 102, '2023-02-01', 80);

3. Triggers

a) Trigger before inserting into Employee Check: joining_date should be less than or equal to

current_date

sql

-- Function for Employee insertion validation

CREATE OR REPLACE FUNCTION check_joining_date()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

IF NEW.joining_date > CURRENT_DATE THEN

RAISE EXCEPTION 'Joining date % cannot be in the future', NEW.joining_date;

ELSE

RAISE NOTICE 'Employee joining date is valid: %', NEW.joining_date;

END IF;

RETURN NEW;

END;

$$;

-- Trigger BEFORE INSERT on Employee

CREATE TRIGGER trg_check_joining_date

BEFORE INSERT ON Employee

FOR EACH ROW

EXECUTE FUNCTION check_joining_date();

Test

sql

INSERT INTO Employee VALUES (103, 'Rahul', 'BScCS', '2027-01-01');

-- ERROR: Joining date 2027-01-01 cannot be in the future


INSERT INTO Employee VALUES (104, 'Neha', 'BCA', '2025-01-15');

-- NOTICE: Employee joining date is valid: 2025-01-15

b) Trigger before inserting into Project Check: duration should be greater than zero

sql

-- Function for Project insertion validation

CREATE OR REPLACE FUNCTION check_project_duration()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

IF NEW.duration <= 0 THEN

RAISE EXCEPTION 'Project duration must be greater than 0. Entered: %', NEW.duration;

ELSE

RAISE NOTICE 'Project duration is valid: %', NEW.duration;

END IF;

RETURN NEW;

END;

$$;

-- Trigger BEFORE INSERT on Project

CREATE TRIGGER trg_check_project_duration

BEFORE INSERT ON Project

FOR EACH ROW

EXECUTE FUNCTION check_project_duration();

Test

sql

INSERT INTO Project VALUES (3, 'AI Research', 'Research', -5);

-- ERROR: Project duration must be greater than 0. Entered: -5

INSERT INTO Project VALUES (3, 'AI Research', 'Research', 18);

-- NOTICE: Project duration is valid: 18

c) Trigger before deleting an Employee record Display notice: “Employee record is being deleted”

sql

-- Function for Employee deletion notice

CREATE OR REPLACE FUNCTION employee_delete_notice()

RETURNS TRIGGER

LANGUAGE plpgsql

AS $$

BEGIN

RAISE NOTICE 'Employee record is being deleted. Employee No: %', OLD.eno;

RETURN OLD;

END;

$$;

-- Trigger BEFORE DELETE on Employee


CREATE TRIGGER trg_employee_delete_notice

BEFORE DELETE ON Employee

FOR EACH ROW

EXECUTE FUNCTION employee_delete_notice();

Test

sql

DELETE FROM Employee WHERE eno = 102;

-- NOTICE: Employee record is being deleted. Employee No: 102

SYBCS-DBMS-II-Error Handling

 Assignment 4: Handling errors and Exceptions


SET A

Project-Employee database

Consider the following database:

Project (pno int, pname char (30), ptype char (20), duration int)

Employee (empno int, ename char (20), joining_date date)

The relationship between Project and Employee is many to many with descriptive attribute

start_date.

Create the above database in PostGreSQL and insert sufficient records.

a. Write a stored function to accept project name as input and print the names of employees

working on the project. Also print the total number of employees working on that project.

Raise an exception for an invalid project name.

b. Write a stored function to accept empno as an input parameter from the user and count the

number of projects of a given employee. Raise an exception if the employee number is invalid.


1. Database Creation (PostgreSQL)

Since Project and Employee have a many-to-many relationship with descriptive attribute

start_date, a relationship table is required.

-- Project Table

CREATE TABLE Project (

pno INT PRIMARY KEY,

pname CHAR(30),

ptype CHAR(20),

duration INT

);

-- Employee Table

CREATE TABLE Employee (

empno INT PRIMARY KEY,

ename CHAR(20),

joining_date DATE

);

-- Relationship Table with descriptive attribute

CREATE TABLE Project_Employee (


pno INT,

empno INT,

start_date DATE,

PRIMARY KEY (pno, empno),

FOREIGN KEY (pno) REFERENCES Project(pno),

FOREIGN KEY (empno) REFERENCES Employee(empno)

);


2. Insert Sufficient Records

-- Insert into Project

INSERT INTO Project VALUES

(1, 'ERP System', 'Software', 12),

(2, 'Website Dev', 'Web', 6),

(3, 'AI Research', 'Research', 18);

-- Insert into Employee

INSERT INTO Employee VALUES

(101, 'Amit', '2020-01-10'),

(102, 'Sneha', '2019-07-15'),

(103, 'Rahul', '2021-03-20'),

(104, 'Neha', '2022-06-01');

-- Insert into Project_Employee

INSERT INTO Project_Employee VALUES

(1, 101, '2022-01-01'),

(1, 102, '2022-01-15'),

(2, 101, '2023-02-01'),

(2, 103, '2023-02-10'),

(3, 102, '2023-03-01'),

(3, 104, '2023-03-15');


3. Stored Functions

a) Stored function to accept project name

Display employee names and total count Raise exception for invalid project name

CREATE OR REPLACE FUNCTION employees_by_project(prj_name CHAR)

RETURNS VOID

LANGUAGE plpgsql

AS $$

DECLARE

rec RECORD;

emp_count INT;

prj_no INT;

emp_cursor CURSOR FOR

SELECT e.ename

FROM Employee e

JOIN Project_Employee pe ON e.empno = pe.empno

WHERE pe.pno = prj_no;

BEGIN

-- Check if project exists

SELECT pno INTO prj_no

FROM Project

WHERE pname = prj_name;

IF NOT FOUND THEN


RAISE EXCEPTION 'Invalid Project Name: %', prj_name;

END IF;

OPEN emp_cursor;

emp_count := 0;

LOOP

FETCH emp_cursor INTO rec;

EXIT WHEN NOT FOUND;

emp_count := emp_count + 1;

RAISE NOTICE 'Employee Name: %', rec.ename;

END LOOP;

CLOSE emp_cursor;

RAISE NOTICE 'Total Employees Working on % : %', prj_name, emp_count;

END;

$$;

Execution

SELECT employees_by_project('ERP System');


b) Stored function to accept empno

Count number of projects Raise exception for invalid employee number

CREATE OR REPLACE FUNCTION project_count_by_employee(e_no INT)

RETURNS INT

LANGUAGE plpgsql

AS $$

DECLARE

proj_count INT;

BEGIN

-- Validate employee

IF NOT EXISTS (SELECT 1 FROM Employee WHERE empno = e_no) THEN

RAISE EXCEPTION 'Invalid Employee Number: %', e_no;

END IF;

SELECT COUNT(*) INTO proj_count

FROM Project_Employee

WHERE empno = e_no;

RETURN proj_count;

END;

$$;

Execution

SELECT project_count_by_employee(101);


SET B

Person – Area database

Person (pno int, name varchar (20), birthdate date, income money) Area

(aid int, aname varchar (20), area_type varchar (5))

The person and area related to many to one relationship. The attribute ‘area_type’ can have values

either ‘urban’ or ‘rural’.


Create the above database in PostGreSQL and insert sufficient records.

a. Write a stored function that accepts the area name as an input parameter from the user

and displays the details of persons living in that area. Raise an exception if area name is invalid.

-- Area Table

CREATE TABLE Area (

aid INT PRIMARY KEY,

aname VARCHAR(20),

area_type VARCHAR(5)

CHECK (area_type IN ('urban', 'rural'))

);

-- Person Table

CREATE TABLE Person (

pno INT PRIMARY KEY,

name VARCHAR(20),

birthdate DATE,

income MONEY,

aid INT,

FOREIGN KEY (aid) REFERENCES Area(aid)

);

2. Insert Sufficient Records


-- Insert into Area

INSERT INTO Area VALUES

(1, 'Nashik', 'urban'),

(2, 'Lasalgaon', 'rural'),

(3, 'Pune', 'urban');

-- Insert into Person

INSERT INTO Person VALUES

(101, 'Amit', '1995-03-15', 75000, 1),

(102, 'Sneha', '1998-07-10', 52000, 2),

(103, 'Rahul', '1996-03-25', 98000, 3),

(104, 'Neha', '1997-12-05', 45000, 1),

(105, 'Suresh','1994-07-18', 60000, 3);

3. Stored Function

Accept area name and display details of persons living in that area Raise exception for invalid area name

sql

CREATE OR REPLACE FUNCTION persons_by_area(area_name VARCHAR)

RETURNS TABLE (

pno INT,

pname VARCHAR,

birthdate DATE,

income MONEY

)


LANGUAGE plpgsql

AS $$

DECLARE

area_id INT;

BEGIN

-- Validate area name

SELECT aid INTO area_id

FROM Area

WHERE aname = area_name;

IF NOT FOUND THEN

RAISE EXCEPTION 'Invalid Area Name: %', area_name;

END IF;

-- Return person details

RETURN QUERY

SELECT p.pno, p.name, p.birthdate, p.income

FROM Person p

WHERE p.aid = area_id;

END;

$$;

4. Execution

SELECT * FROM persons_by_area('Nashik');

SELECT * FROM persons_by_area('Mumbai');

Output:

ERROR: Invalid Area Name: Mumbai


SET C

Wholesaler – Product database

Consider the following entities and their relationships.

Wholesaler (w_no, w_name, address, city)

Product (product_no, product_name, rate)

Relation between Wholesaler and Product is Many to Many with quantity as descriptive attribute.

Create the above database in PostGreSQL and insert sufficient records.

a. Write a function to accept quantity from user. Quantity must be within range 50-200. If user

enters the quantity out of range, then raise a user defined exception “quantity_out_of _range”

otherwise enter the record in table.

b. Write a function which accept rate from user. If user enters rate less than or equal to zero then

raise an user defined exception “Invalid_Rate_Value” otherwise display message “Correct Input”.

c. Write a function to accept product name as parameter. If entered product name is not valid then

raise an user defined exception”Invalid_Product_Name” otherwise display product details of

Specified product.

-- Wholesaler Table

CREATE TABLE Wholesaler (

w_no INT PRIMARY KEY,


w_name VARCHAR(50),

address VARCHAR(100),

city VARCHAR(30)

);

-- Product Table

CREATE TABLE Product (

product_no INT PRIMARY KEY,

product_name VARCHAR(50),

rate NUMERIC(10,2)

);

-- Junction Table with descriptive attribute Quantity

CREATE TABLE Wholesaler_Product (

w_no INT,

product_no INT,

quantity INT,

PRIMARY KEY (w_no, product_no),

FOREIGN KEY (w_no) REFERENCES Wholesaler(w_no),

FOREIGN KEY (product_no) REFERENCES Product(product_no)

);

2. Insert Sample Records


-- Insert into Wholesaler

INSERT INTO Wholesaler VALUES

(1, 'ABC Traders', '123 Main Street', 'Mumbai'),

(2, 'XYZ Enterprises', '456 Park Avenue', 'Pune');

-- Insert into Product

INSERT INTO Product VALUES

(101, 'Laptop', 50000),

(102, 'Mobile', 15000),

(103, 'Printer', 8000);

-- Sample Junction Table Entry (quantity between 50-200)

INSERT INTO Wholesaler_Product VALUES

(1, 101, 100),

(1, 102, 150),

(2, 102, 50);

3. Stored Functions with User-Defined Exceptions

a) Function to accept quantity Must be between 50-200 Raise exception quantity_out_of_range if

invalid Otherwise insert record into Wholesaler_Product

sql

CREATE OR REPLACE FUNCTION insert_wholesaler_product(

w INT, p INT, q INT

)


RETURNS VOID

LANGUAGE plpgsql

AS $$

BEGIN

IF q < 50 OR q > 200 THEN

RAISE EXCEPTION 'quantity_out_of_range: %', q;

END IF;

-- Insert into Wholesaler_Product

INSERT INTO Wholesaler_Product (w_no, product_no, quantity)

VALUES (w, p, q);

RAISE NOTICE 'Record inserted successfully: Wholesaler %, Product %, Quantity %', w, p, q;

END;

$$;

Execution Examples

sql

-- Valid quantity

SELECT insert_wholesaler_product(2, 103, 100);

-- Invalid quantity

SELECT insert_wholesaler_product(2, 103, 30);

-- ERROR: quantity_out_of_range: 30

b) Function to accept rate If rate ≤ 0, raise Invalid_Rate_Value Otherwise display “Correct Input”

CREATE OR REPLACE FUNCTION validate_rate(r NUMERIC)

RETURNS VOID

LANGUAGE plpgsql

AS $$

BEGIN

IF r <= 0 THEN

RAISE EXCEPTION 'Invalid_Rate_Value: %', r;

ELSE

RAISE NOTICE 'Correct Input';

END IF;

END;

$$;

Execution Examples

sql

SELECT validate_rate(15000);

-- NOTICE: Correct Input

SELECT validate_rate(-500);

-- ERROR: Invalid_Rate_Value: -500

c) Function to accept product_name If product name does not exist, raise Invalid_Product_Name

Otherwise display product details

sql


CREATE OR REPLACE FUNCTION product_details_by_name(pname VARCHAR)

RETURNS TABLE (

product_no INT,

product_name VARCHAR,

rate NUMERIC

)

LANGUAGE plpgsql

AS $$

DECLARE

rec RECORD;

BEGIN

-- Check if product exists

SELECT * INTO rec

FROM Product

WHERE product_name = pname;

IF NOT FOUND THEN

RAISE EXCEPTION 'Invalid_Product_Name: %', pname;

END IF;

-- Return product details

RETURN QUERY

SELECT product_no, product_name, rate

FROM Product

WHERE product_name = pname;

END;

$$;

Execution Examples


SELECT * FROM product_details_by_name('Laptop');

SELECT * FROM product_details_by_name('Tablet');

-- ERROR: Invalid_Product_Name: Tablet


SET D

Student Teacher Database

Student (sno integer, s_name char(30), s_class char(10), s_addr Char(50))

Teacher (tno integer, t_name char (20), qualification char (15), experience integer)

The relationship is as follows:

Student-Teacher: Many to Many with descriptive attribute Subject.

a. Write a stored function to count the number of the teachers teaching to a student named “ ”. (Accept student name as input parameter). Raise an exception if student name does not exist.

b. Write a stored function to count the number of the students who are studying subject named “ ” (Accept subject name as input parameter). Display error message if subject name is not valid.

c. Write a stored function to display teacher details who have qualification as “ ” (Accept teacher’s  qualification as input parameter). Raise an exception for invalid qualification.


-- Student Table

CREATE TABLE Student (

sno INT PRIMARY KEY,

s_name CHAR(30),

s_class CHAR(10),

s_addr CHAR(50)

);

-- Teacher Table

CREATE TABLE Teacher (

tno INT PRIMARY KEY,

t_name CHAR(20),

qualification CHAR(15),

experience INT

);

-- Junction Table with descriptive attribute Subject

CREATE TABLE Student_Teacher (

sno INT,

tno INT,

subject CHAR(30),

PRIMARY KEY (sno, tno, subject),

FOREIGN KEY (sno) REFERENCES Student(sno),

FOREIGN KEY (tno) REFERENCES Teacher(tno)

);

2. Insert Sample Records

sql

-- Insert into Student

INSERT INTO Student VALUES

(1, 'Amit', 'BScCS', '123 Main Street'),

(2, 'Sneha', 'BScIT', '456 Park Avenue'),

(3, 'Rahul', 'BCA', '789 Oak Street');

-- Insert into Teacher

INSERT INTO Teacher VALUES

(101, 'Ramesh', 'MScCS', 10),

(102, 'Suresh', 'MCA', 8),

(103, 'Mahesh', 'BScCS', 5);

-- Insert into Student_Teacher

INSERT INTO Student_Teacher VALUES

(1, 101, 'DBMS'),

(1, 102, 'AI'),

(2, 101, 'DBMS'),

(2, 103, 'ComputerNet'),

(3, 102, 'AI');

3. Stored Functions


a) Count teachers teaching a student Accept student name as input Raise exception if student name does not exist

sql

CREATE OR REPLACE FUNCTION count_teachers_by_student(student_name CHAR)

RETURNS INT

LANGUAGE plpgsql

AS $$

DECLARE

student_id INT;

teacher_count INT;

BEGIN

-- Validate student

SELECT sno INTO student_id

FROM Student

WHERE s_name = student_name;

IF NOT FOUND THEN

RAISE EXCEPTION 'Student Name Not Found: %', student_name;

END IF;

-- Count teachers teaching this student

SELECT COUNT(DISTINCT tno) INTO teacher_count

FROM Student_Teacher

WHERE sno = student_id;

RETURN teacher_count;

END;

$$;

Execution Example

sql

SELECT count_teachers_by_student('Amit');

b) Count students studying a given subject Accept subject name as input Raise error if subject

name not found

sql

CREATE OR REPLACE FUNCTION count_students_by_subject(sub_name CHAR)

RETURNS INT

LANGUAGE plpgsql

AS $$

DECLARE

total_students INT;

BEGIN

-- Validate subject exists

IF NOT EXISTS (

SELECT 1 FROM Student_Teacher WHERE subject = sub_name

) THEN


RAISE EXCEPTION 'Invalid Subject Name: %', sub_name;

END IF;

-- Count students

SELECT COUNT(DISTINCT sno) INTO total_students

FROM Student_Teacher

WHERE subject = sub_name;

RETURN total_students;

END;

$$;

Execution Example

sql

SELECT count_students_by_subject('DBMS');

c) Display teacher details by qualification Accept teacher qualification as input Raise exception if

qualification not found

sql

CREATE OR REPLACE FUNCTION teachers_by_qualification(q CHAR)

RETURNS TABLE (

tno INT,

t_name CHAR(20),

qualification CHAR(15),

experience INT

)

LANGUAGE plpgsql

AS $$

BEGIN

-- Validate qualification exists

IF NOT EXISTS (SELECT 1 FROM Teacher WHERE qualification = q) THEN

RAISE EXCEPTION 'Invalid Qualification: %', q;

END IF;

-- Return teacher details

RETURN QUERY

SELECT tno, t_name, qualification, experience

FROM Teacher

WHERE qualification = q;

END;

$$;

Execution Example

sql

SELECT * FROM teachers_by_qualification('MCA');

SET E

Railway Reservation System Database

TRAIN: (train_no int, train_name varchar(20), depart_time time , arrival_time time, source_stn


varchar (20),dest_stn varchar (20), no_of_res_bogies int ,bogie_capacity int)

PASSENGER : (passenger_id int, passenger_name varchar(20), address varchar(30), age int

gender char)

Relationships:

Train _Passenger: Many to Many relationship named ticket with descriptive attributes as follows

TICKET: ( train_no int, passenger_id int, ticket_no int ,bogie_no int, no_of_berths int ,tdate date ,

ticket_amt decimal(7,2),status char)

Constraints: The status of a berth can be 'W' (waiting) or 'C' (confirmed).

a. Write a stored function to print the details of train wise confirmed bookings on date “ ” (Accept

date as input parameter).Raise an error in case of invalid date.

b. Write a stored function to accept date and passenger name and display no of berths reserved

and ticket amount paid by him. Raise exception if passenger name is invalid.

c. Write a stored function to display the ticket details of a train. (Accept train name as input

parameter).Raise an exception in case of invalid train name.

-- TRAIN Table

CREATE TABLE TRAIN (

train_no INT PRIMARY KEY,

train_name VARCHAR(20),

depart_time TIME,

arrival_time TIME,

source_stn VARCHAR(20),

dest_stn VARCHAR(20),

no_of_res_bogies INT,

bogie_capacity INT

);

-- PASSENGER Table

CREATE TABLE PASSENGER (

passenger_id INT PRIMARY KEY,

passenger_name VARCHAR(20),

address VARCHAR(30),

age INT,

gender CHAR

);

-- TICKET Table (Many-to-Many relationship)

CREATE TABLE TICKET (

train_no INT,

passenger_id INT,

ticket_no INT,

bogie_no INT,

no_of_berths INT,

tdate DATE,

ticket_amt DECIMAL(7,2),

status CHAR CHECK (status IN ('W', 'C')),

PRIMARY KEY (ticket_no),

FOREIGN KEY (train_no) REFERENCES TRAIN(train_no),


FOREIGN KEY (passenger_id) REFERENCES PASSENGER(passenger_id)

);

2. Insert Sample Records


-- Insert into TRAIN

INSERT INTO TRAIN VALUES

(101, 'Express1', '06:00', '12:00', 'Mumbai', 'Delhi', 10, 50),

(102, 'Express2', '08:00', '14:00', 'Pune', 'Mumbai', 8, 40);

-- Insert into PASSENGER

INSERT INTO PASSENGER VALUES

(1, 'Amit', 'Mumbai', 30, 'M'),

(2, 'Sneha', 'Pune', 25, 'F'),

(3, 'Rahul', 'Delhi', 28, 'M');

-- Insert into TICKET

INSERT INTO TICKET VALUES

(101, 1, 1001, 1, 2, '2026-01-25', 3000, 'C'),

(101, 2, 1002, 1, 1, '2026-01-25', 1500, 'C'),

(101, 3, 1003, 2, 1, '2026-01-25', 1500, 'W'),

(102, 1, 1004, 1, 1, '2026-01-26', 2000, 'C');

3. Stored Functions

a) Train-wise confirmed bookings on a given date

sql

CREATE OR REPLACE FUNCTION confirmed_bookings_by_date(b_date DATE)

RETURNS TABLE(

train_no INT,

train_name VARCHAR,

passenger_name VARCHAR,

ticket_no INT,

bogie_no INT,

no_of_berths INT,

ticket_amt DECIMAL(7,2)

)

LANGUAGE plpgsql

AS $$

BEGIN

-- Validate date

IF b_date IS NULL THEN

RAISE EXCEPTION 'Invalid Date Input';

END IF;

RETURN QUERY

SELECT t.train_no, t.train_name, p.passenger_name, tk.ticket_no, tk.bogie_no, tk.no_of_berths,

tk.ticket_amt

FROM TRAIN t

JOIN TICKET tk ON t.train_no = tk.train_no


JOIN PASSENGER p ON tk.passenger_id = p.passenger_id

WHERE tk.tdate = b_date AND tk.status = 'C';

END;

$$;

Execution Example

sql

SELECT * FROM confirmed_bookings_by_date('2026-01-25');

b) Berths and ticket amount for a passenger on a given date

sql

CREATE OR REPLACE FUNCTION berths_by_passenger(b_date DATE, pname VARCHAR)

RETURNS TABLE(

no_of_berths INT,

ticket_amt DECIMAL(7,2)

)

LANGUAGE plpgsql

AS $$

DECLARE

pid INT;

BEGIN

-- Validate passenger

SELECT passenger_id INTO pid

FROM PASSENGER

WHERE passenger_name = pname;

IF NOT FOUND THEN

RAISE EXCEPTION 'Invalid Passenger Name: %', pname;

END IF;

RETURN QUERY

SELECT SUM(no_of_berths), SUM(ticket_amt)

FROM TICKET

WHERE passenger_id = pid AND tdate = b_date;

END;

$$;

Execution Example

sql


SELECT * FROM berths_by_passenger('2026-01-25', 'Amit');

c) Display ticket details of a train by train name

sql

CREATE OR REPLACE FUNCTION ticket_details_by_train(tname VARCHAR)

RETURNS TABLE(

ticket_no INT,

passenger_name VARCHAR,

bogie_no INT,

no_of_berths INT,

tdate DATE,


ticket_amt DECIMAL(7,2),

status CHAR

)

LANGUAGE plpgsql

AS $$

DECLARE

tno INT;

BEGIN

-- Validate train name

SELECT train_no INTO tno

FROM TRAIN

WHERE train_name = tname;

IF NOT FOUND THEN

RAISE EXCEPTION 'Invalid Train Name: %', tname;

END IF;

RETURN QUERY

SELECT tk.ticket_no, p.passenger_name, tk.bogie_no, tk.no_of_berths, tk.tdate, tk.ticket_amt,

tk.status

FROM TICKET tk

JOIN PASSENGER p ON tk.passenger_id = p.passenger_id

WHERE tk.train_no = tno;

END;

$$;

Execution Example

sql

SELECT * FROM ticket_details_by_train('Express1');