Vanshita PST Merged Organized

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

AMITY UNIVERSITY

MADHYA PRADESH

CSE 723
LAB FILE
ADVANCED PROBLEM-SOLVING TECHNIQUES

Submitted To - Submitted By -
Dr. Deepak Motwani Vanshita Agrawal
Associate Professor A60205220157
AUMP Sem :- VII “B”
B.Tech (CSE)
INDEX
S.No Program Remarks
1 Search in a Sorted Rotated array.
2 Spiral matrix.
3 Balanced binary tree.
4 Reverse words in a string.
5 Linked List cycle 2.
6 Print all the nodes reachable from a given starting
node in a given digraph using Depth First Search
method.
7 Print all the nodes reachable from a given starting
node in a given digraph using Breadth First
Search method.
8 Implement 0/1 Knapsack problem using dynamic
programming.
9 Implement All Pair Shortest paths problem using
Floyd's algorithm.
10 Use divide and conquer method to recursively
implement Linear Search.
11 Dining-Philosophers problem.
12 Write a C/C++ program to simulate Bankers
algorithm for the purpose of deadlock avoidance.
13 Banker’s algorithm application
14 Write a C/C++ program to simulate producer-
consumer problem using semaphores.
15 Print FooBar Alternatively.
16 Different DDL and DML Commands with
Examples.
17 Concept of Key Constrains-Normalization.
18 Different Aggregate functions.
19 Concept of Joins.
20 Concept of Views.
21 Concept of Index.
22 Concept of Triggers.
23 Recyclable and Low-Fat Products.
24 Find Customer Referee.
25 Big Countries.
Q1.) Search in a Sorted Rotated array

Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

Output:
Q2.) Spiral matrix

Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]Code:

Output:
Q3.) Balanced binary tree

Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true

Example 2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false

Output:
Q4.) Reverse words in a string

Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:
Input: s = "a good example"
Output: "example good a"

Output:
Q5.) Linked List cycle 2

Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

Output:
Q6.) Print all the nodes reachable from a given starting node in a given
digraph using Depth First Search method.
Code:
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
void dfs(int node, vector<int> adj[], int vis[], vector<int> &ls) {
vis[node] = 1;
ls.push_back(node);
// traverse all its neighbours
for(auto it : adj[node]) {
// if the neighbour is not visited
if(!vis[it]) {
dfs(it, adj, vis, ls);
}
}
}
public:
// Function to return a list containing the DFS traversal of the graph.
vector<int> dfsOfGraph(int V, vector<int> adj[]) {
int vis[V] = {0};
int start = 0;
// create a list to store dfs
vector<int> ls;
// call dfs for starting node
dfs(start, adj, vis, ls);
return ls;
}
};
void addEdge(vector <int> adj[], int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
void printAns(vector <int> &ans) {
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
}
int main()
{
vector <int> adj[5];
addEdge(adj, 0, 2);
addEdge(adj, 2, 4);
addEdge(adj, 0, 1);
addEdge(adj, 0, 3);
Solution obj;
vector <int> ans = obj.dfsOfGraph(5, adj);
printAns(ans);
return 0;
}
Output:
Q7.) Print all the nodes reachable from a given starting node in a given
digraph using Breadth First Search method.
Code:
include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> bfsOfGraph(int V, vector<int> adj[]) {
int vis[V] = {0};
vis[0] = 1;
queue<int> q;
q.push(0);
vector<int> bfs;
while(!q.empty()) {
int node = q.front();
q.pop();
bfs.push_back(node);
for(auto it : adj[node]) {
if(!vis[it]) {
vis[it] = 1;
q.push(it);
}
}
}
return bfs;
}
};
void addEdge(vector <int> adj[], int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
void printAns(vector <int> &ans) {
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
}
int main()
{
vector <int> adj[6];
addEdge(adj, 0, 1);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 0, 4);
Solution obj;
vector <int> ans = obj.bfsOfGraph(5, adj);
printAns(ans);
return 0;
Output:
Q8.) Implement 0/1 Knapsack problem using dynamic programming.
Code:
#include<iostream>
using namespace std;

//function to recursive check every subset of items


int knapsack(int w[], int p[], int n, int M)
{
//In every pass, we can either include nth item or not

//if the capacity of knapsack is left to NIL, no value can be attained


if(M==0)
return 0;

//if no more items are left, no value can be attained


if(n==0)
return 0;

//if current item, weighs more than the capacity of knapsack, it can not be included
if(w[n-1]>M)
return knapsack(w,p,n-1,M);

//else select the maximum value of once including the current item and once not including
it
return max(knapsack(w,p,n-1,M),p[n-1]+knapsack(w,p,n-1,M-w[n-1]));
}

int main()
{ int i,n;
int M; //capacity of knapsack
cout<<"Enter the no. of items ";
cin>>n;

int w[n]; //weight of items


int p[n]; //value of items

cout<<"Enter the weight and price of all items"<<endl;


for(i=0;i<n;i++)
{
cin>>w[i]>>p[i];
}

cout<<"enter the capacity of knapsack ";


cin>>M;

cout<<"The maximum value of items that can be put into knapsack is


"<<knapsack(w,p,n,M);

return 0;
}
Output:
Q9.) Implement All Pair Shortest paths problem using Floyd's algorithm.
Code:
#include<stdio.h>
void floyd(int a[4][4], int n)
{
for(int k=0;k<n;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i][j]>a[i][k]+a[k][j])
{
a[i][j]=a[i][k]+a[k][j];
}
}
}
}
printf("All Pairs Shortest Path is :\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
int main()
{
int cost[4][4] = {{0, 3, 999, 4}, {8, 0, 2, 999}, {5, 999, 0, 1}, {2, 999, 999, 0}};
int n = 4;

floyd(cost,n);
}
Output:
Q10.) Use divide and conquer method to recursively implement Linear
Search.
Code:
include <iostream>
using namespace std;

void linearSearch(int a[],int n,int x,int index)


{
if(index >=n)
{
cout << "Not Found" << endl;
}
else if(a[index] == x)
{
cout << "Found" << endl;
}
else
{
return linearSearch(a,n,x,index+1);
}
}

int main()
{
int a[10] = {1,7,3,1,4,6,2,3,5,86}; //array
int x = 2; //element to search
int n=10; //size of array
int index=0; //index similar to i in for loop
linearSearch(a,n,x,index);
}
Output:
Q11.) Dining-Philosophers problem.
Code:
class DiningPhilosophers {
private:
mutex mtx[5];

public:
DiningPhilosophers() { }
void wantsToEat(int philosopher, function<void()> pickLeftFork, function<void()>
pickRightFork, function<void()> eat, function<void()> putLeftFork, function<void()>
putRightFork) {
int left = philosopher;
int right = (philosopher + 1) % 5;

if(philosopher % 2 == 0){
mtx[right].lock();
mtx[left].lock();
pickLeftFork(); pickRightFork();
}
else{
mtx[left].lock();
mtx[right].lock();
pickLeftFork(); pickRightFork();
}

eat(); putRightFork(); putLeftFork();


mtx[left].unlock();
mtx[right].unlock();
}
};
Output:
Q12.) Write a C/C++ program to simulate Bankers algorithm for the
purpose of deadlock avoidance.
Code:
#include<iostream>
using namespace std;

// Number of processes
const int P = 5;

// Number of resources
const int R = 3;

// Function to find the need of each process


void calculateNeed(int need[P][R], int maxm[P][R],
int allot[P][R])
{
// Calculating Need of each P
for (int i = 0 ; i < P ; i++)
for (int j = 0 ; j < R ; j++)

// Need of instance = maxm instance -


// allocated instance
need[i][j] = maxm[i][j] - allot[i][j];
}

// Function to find the system is in safe state or not


bool isSafe(int processes[], int avail[], int maxm[][R],
int allot[][R])
{
int need[P][R];
// Function to calculate need matrix
calculateNeed(need, maxm, allot);

// Mark all processes as infinish


bool finish[P] = {0};

// To store safe sequence


int safeSeq[P];

// Make a copy of available resources


int work[R];
for (int i = 0; i < R ; i++)
work[i] = avail[i];

// While all processes are not finished


// or system is not in safe state.
int count = 0;
while (count < P)
{
// Find a process which is not finish and
// whose needs can be satisfied with current
// work[] resources.
bool found = false;
for (int p = 0; p < P; p++)
{
// First check if a process is finished,
// if no, go for next condition
if (finish[p] == 0)
{
// Check if for all resources of
// current P need is less
// than work
int j;
for (j = 0; j < R; j++)
if (need[p][j] > work[j])
break;

// If all needs of p were satisfied.


if (j == R)
{
// Add the allocated resources of
// current P to the available/work
// resources i.e.free the resources
for (int k = 0 ; k < R ; k++)
work[k] += allot[p][k];

// Add this process to safe sequence.


safeSeq[count++] = p;

// Mark this p as finished


finish[p] = 1;

found = true;
}
}
}

// If we could not find a next process in safe


// sequence.
if (found == false)
{
cout << "System is not in safe state";
return false;
}
}

// If system is in safe state then


// safe sequence will be as below
cout << "System is in safe state.\nSafe"
" sequence is: ";
for (int i = 0; i < P ; i++)
cout << safeSeq[i] << " ";

return true;
}

// Driver code
int main()
{
int processes[] = {0, 1, 2, 3, 4};

// Available instances of resources


int avail[] = {3, 3, 2};

// Maximum R that can be allocated


// to processes
int maxm[][R] = {{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}};

// Resources allocated to processes


int allot[][R] = {{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}};

// Check system is in safe state or not


isSafe(processes, avail, maxm, allot);

return 0;
}
Output:
Q13.) Banker’s algorithm application
Code:
class Solution {
public:
int totalMoney(int n) {
int dollarStart = 1;
int dollarEnd = 7;
int sevenPeriodSum = 28;
int total = 0;

while ((n - 7) > 0) {


total += sevenPeriodSum;

sevenPeriodSum -= dollarStart++;
sevenPeriodSum += ++dollarEnd;

n -= 7;
}

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


total += dollarStart;
++dollarStart;
}
return total;
}
};
Output:
Q14.) Write a C/C++ program to simulate producer-consumer problem
using semaphores.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

#define BUFFER_SIZE 5
#define MAX_ITEMS 20

int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int produced_count = 0;
int consumed_count = 0;

sem_t mutex;
sem_t full;
sem_t empty;

void* producer(void* arg) {


int item = 1;

while (produced_count < MAX_ITEMS) {


sem_wait(&empty);
sem_wait(&mutex);

buffer[in] = item;
printf("Produced: %d", item);
item++;
in = (in + 1) % BUFFER_SIZE;

produced_count++;

sem_post(&mutex);
sem_post(&full);
}

pthread_exit(NULL);
}

void* consumer(void* arg) {


while (consumed_count < MAX_ITEMS) {
sem_wait(&full);
sem_wait(&mutex);

int item = buffer[out];


printf("Consumed: %d", item);
out = (out + 1) % BUFFER_SIZE;

consumed_count++;

sem_post(&mutex);
sem_post(&empty);
}

pthread_exit(NULL);
}

int main() {
pthread_t producerThread, consumerThread;
sem_init(&mutex, 0, 1);
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFER_SIZE);

pthread_create(&producerThread, NULL, producer, NULL);


pthread_create(&consumerThread, NULL, consumer, NULL);

pthread_join(producerThread, NULL);
pthread_join(consumerThread, NULL);

sem_destroy(&mutex);
sem_destroy(&full);
sem_destroy(&empty);

return 0;
}

Output:
Q15.) Print FooBar Alternatively
Code:
class FooBar {
private:
int n;
mutex m;
condition_variable cv;
bool ready;
public:
FooBar(int n) {
this->n = n;
ready = false;
}
void foo(function<void()> printFoo) {

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


unique_lock<mutex> lck(m);
printFoo();
ready = true;
lck.unlock();
cv.notify_one();
lck.lock();
cv.wait(lck,[this]() {return ready == false;});
}
}

void bar(function<void()> printBar) {

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


unique_lock<mutex> lck(m);
cv.wait(lck,[this]() {return ready;});
printBar();
ready= false;
lck.unlock();
cv.notify_one();

}
}
};
Output:
Q16.) Different DDL and DML Commands with Examples.
Data Definition Language (DDL) Commands:
a.) CREATE:
Used to create database objects like tables, views, indexes, etc.
Example: Create a table named employees with columns id, name, and salary.
CREATE TABLE employees (

id INT PRIMARY KEY,

name VARCHAR(255),

salary DECIMAL(10, 2)

);

b.) ALTER:
Used to modify the structure of existing database objects.
Example: Add a new column department to the employees table.
ALTER TABLE employees ADD COLUMN department VARCHAR(50);

c.) DROP
Used to delete database objects like tables, views, indexes, etc.
Example: Delete the employees table.
DROP TABLE employees;

d.) TRUNCATE:
Used to remove all rows from a table but keep the table structure for reuse.
Example: Truncate all data from the employees table.
TRUNCATE TABLE employees;

Data Manipulation Language (DML) Commands:


a.) SELECT
Used to retrieve data from one or more tables.
Example: Retrieve all columns from the employees table.
SELECT * FROM employees;

b.) INSERT
Used to insert new rows of data into a table.
Example: Insert a new employee into the employees table.
INSERT INTO employees (id, name, salary) VALUES (1, 'John Doe', 50000);

c.) UPDATE
Used to modify existing data in a table.
Example: Update the salary of employee with ID 1.
UPDATE employees SET salary = 55000 WHERE id = 1;

d.) DELETE
Used to delete rows from a table.
Example: Delete the employee with ID 1 from the employees table.
DELETE FROM employees WHERE id = 1;
Q17.) Concept of Key Constrains-Normalization.
Key Constraints and Normalization:
In the context of database normalization, key constraints are rules applied to the keys (like
primary keys and foreign keys) to ensure data integrity and relationships between tables.
Let's consider a scenario where we have a denormalized table:
StudentID StudentName CourseID CourseName Instructor
1 Alice 101 Math 101 Prof. Smith
1 Alice 102 English 101 Prof. Johnson
2 Bob 101 Math 101 Prof. Smith
2 Bob 103 History 101 Prof. Davis

Steps for Normalization:


1. Identify Dependencies:
Identify functional dependencies and remove repeated groups of data.
2. Create Separate Tables:
Create separate tables for distinct entities (e.g., Students, Courses).
Table : Students
StudentID StudentName
1 Alice
2 Bob

Table : Courses
CourseID CourseName Instructor
101 Math 101 Prof. Smith
102 English 101 Prof. Johnson
103 History 101 Prof. Davis

3.) Define Primary Keys


Assign primary keys to uniquely identify each record in each table.
Table : Students
StudentID (PK) StudentName
1 Alice
2 Bob

Table: Courses
CourseID (PK) CourseName Instructor
101 Math 101 Prof. Smith
102 English 101 Prof. Johnson
103 History 101 Prof. Davis

3. Establish Relationships with Foreign Keys:


Use foreign keys to establish relationships between tables.
Table: StudentCourses
StudentID (PK) CourseID (FK)
1 101
1 102
2 101
2 103

Key Constraints:
Primary Key Constraint:
The primary key in each table ensures that each record is uniquely identified.
Foreign Key Constraint:
The foreign key in the StudentCourses table establishes a relationship between the Students and
Courses tables. It ensures referential integrity.
ALTER TABLE StudentCourses

ADD CONSTRAINT FK_StudentID FOREIGN KEY (StudentID) REFERENCES Students(StudentID);

ALTER TABLE StudentCourses

ADD CONSTRAINT FK_CourseID FOREIGN KEY (CourseID) REFERENCES Courses(CourseID);

These constraints enforce rules on the relationships between tables, helping maintain data
integrity. The primary key constraint ensures uniqueness, and the foreign key constraint ensures
that values in the StudentCourses table correspond to valid values in the Students and Courses
tables.
Q18.) Different Aggregate functions.
Aggregate functions in SQL perform a calculation on a set of values and return a single value.
They are often used in combination with the GROUP BY clause to operate on subsets of data.
Here are some common aggregate functions:
a. COUNT():
Counts the number of rows in a result set.
Example: Count the number of students in a table.
SELECT COUNT(*) FROM students;

b. SUM():
Calculates the sum of values in a numeric column.
Example: Calculate the total salary of all employees.
SELECT SUM(salary) FROM employees;
c. AVG():
Calculates the average (mean) of values in a numeric column.
Example: Calculate the average age of employees.
SELECT AVG(age) FROM employees;
d. MIN():
Returns the smallest value in a column.
Example: Find the minimum salary in the employees table.
SELECT MIN(salary) FROM employees;

e. MAX():
Returns the largest value in a column.
Example: Find the maximum salary in the employees table.
SELECT MAX(salary) FROM employees;

f. GROUP_CONCAT() (or STRING_AGG() in some databases):


Concatenates values from multiple rows into a single string.
Example: Concatenate the names of all employees in a department.
SELECT department, GROUP_CONCAT(name) AS employee_names FROM employees GROUP BY
department;

g. GROUP BY:
Groups rows that have the same values in specified columns into summary rows.
Example: Count the number of students in each department.
SELECT department, COUNT(*) AS student_count FROM students GROUP BY department;

h. HAVING:
Filters the results of a GROUP BY query based on a condition.
Example: Count the number of students in each department, but only show departments with
more than 10 students.
SELECT department,COUNT(*) AS student_count FROM students GROUP BY department HAVING
COUNT(*) >10;

These aggregate functions are powerful tools for summarizing and analyzing data in SQL queries.
They are often used in combination to provide insightful information about a dataset. Keep in
mind that syntax and available functions may vary slightly between different database
management systems.
Q19.) Concept of Joins.
In relational databases, the concept of joins is fundamental to retrieving data from multiple tables
based on some related columns. Joins allow you to combine rows from two or more tables based
on a related column between them. There are several types of joins, each serving a specific
purpose:
1. INNER JOIN:
Returns only the rows where there is a match in both tables.
Syntax:
SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;

Example: Retrieve a list of students and their courses.


SELECT Students.StudentID, Students.StudentName, Courses.CourseName

FROM Students

INNER JOIN StudentCourses ON Students.StudentID = StudentCourses.StudentID

INNER JOIN Courses ON StudentCourses.CourseID = Courses.CourseID;

2. LEFT (OUTER) JOIN:


Returns all rows from the left table and the matched rows from the right table. If there is no
match, NULL values are returned for columns from the right table.
Syntax:
SELECT columns FROM table1 LEFT JOIN table2 ON table1.column = table2.column;

Example: Retrieve a list of all students and their courses, even if they are not enrolled in any.
SELECT Students.StudentID, Students.StudentName, Courses.CourseName

FROM Students

LEFT JOIN StudentCourses ON Students.StudentID = StudentCourses.StudentID

LEFT JOIN Courses ON StudentCourses.CourseID = Courses.CourseID;

3. RIGHT (OUTER) JOIN:


Returns all rows from the right table and the matched rows from the left table. If there is no
match, NULL values are returned for columns from the left table.
Syntax:
SELECT columns FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;

Example: Retrieve a list of all courses and the students enrolled in each.
SELECT Students.StudentID, Students.StudentName, Courses.CourseName

FROM Students

RIGHT JOIN StudentCourses ON Students.StudentID = StudentCourses.StudentID

RIGHT JOIN Courses ON StudentCourses.CourseID = Courses.CourseID;

4. FULL (OUTER) JOIN:


Returns all rows when there is a match in either the left or the right table. If there is no match,
NULL values are returned for columns from the table without a match.
Syntax:
SELECT columns FROM table1 FULL JOIN table2 ON table1.column = table2.column;

Example: Retrieve a list of all students and all courses, showing enrollment where available.
SELECT Students.StudentID, Students.StudentName, Courses.CourseName

FROM Students

FULL JOIN StudentCourses ON Students.StudentID = StudentCourses.StudentID

FULL JOIN Courses ON StudentCourses.CourseID = Courses.CourseID;

Joins are powerful tools for combining data from different tables based on relationships, enabling
complex queries and analysis across related datasets. Understanding the relationships between
tables and choosing the appropriate join type is crucial for constructing effective SQL queries.
Q20.) Concept of Views.
In a relational database, a view is a virtual table based on the result of a SELECT query. It does
not store the data itself but provides a way to represent the data stored in one or more tables in a
predefined manner. Views are used for various purposes, including simplifying complex queries,
enforcing security, and providing a logical layer of abstraction over the underlying data.
Here are key concepts related to views:
a. Creation of Views:
Views are created using the CREATE VIEW statement, which consists of a SELECT query that
defines the virtual table.
Syntax:
CREATE VIEW view_name AS SELECT column1, column2, ... FROM table1 WHERE condition;

b. Querying Views:
Once a view is created, it can be queried like a regular table using the SELECT statement.
Syntax:
SELECT * FROM view_name; Updating Views:

In many databases, views can be updatable, meaning you can perform INSERT, UPDATE, and
DELETE operations on the view, and the changes will be reflected in the underlying base tables,
subject to certain conditions.
The ability to update views depends on the complexity of the view and the underlying tables.
c. Simplifying Complex Queries:
Views can simplify complex queries by encapsulating logic, aggregations, or joins into a single
named entity.
Example: Create a view that combines data from multiple tables and filters rows based on a
condition, and then query the view instead of writing the complex SQL every time.
d. Security and Abstraction:
Views can be used to restrict access to certain columns or rows of a table. Users can be granted
permissions to query a view without having direct access to the underlying tables.
This provides a layer of abstraction, allowing changes to the underlying table structure without
affecting applications that use the view.
e. Materialized Views (Optional):
Some databases support materialized views, which are physical copies of the result set of a query.
Unlike regular views, materialized views store the data, and their contents are periodically
refreshed.

Example:
Let's consider a simplified example where we create a view to represent the total salary of
employees in a department:
CREATE VIEW DepartmentSalaries AS

SELECT DepartmentID, SUM(Salary) AS TotalSalary

FROM Employees

GROUP BY DepartmentID;

Now, you can query the DepartmentSalaries view to get the total salary for each department:
SELECT * FROM DepartmentSalaries;

In this example, the view simplifies the process of obtaining departmental salary information
without having to write the aggregation logic every time you need the data.
Views provide a way to organize and simplify database interactions while offering control over
access and security. They are a valuable tool in database design and management.
Q21.) Concept of Index
In the context of databases, an index is a data structure that improves the speed of data retrieval
operations on a database table. The primary purpose of an index is to provide a quick and efficient
way to locate specific rows in a table based on the values in one or more columns. Without an
index, the database management system (DBMS) would need to scan the entire table to find the
required data, which could be slow and resource-intensive, especially for large tables.
Here are key concepts related to indexes:
1. Structure:
An index is typically implemented as a separate structure that contains a sorted or hashed subset
of the data in the table.
The index structure includes pointers to the corresponding rows in the actual table.
2. Key:
The column or set of columns on which an index is created is called the "key" of the index.
Indexes can be created on single columns or on combinations of multiple columns.
3. Types of Indexes:
a. Clustered Index:
Defines the physical order of data rows in a table based on the order of the index key.
The actual table data is reorganized to match the order of the clustered index.
b. Non-Clustered Index:
Does not affect the physical order of data rows in the table.
Instead, it creates a separate structure that provides a mapping between the values in the
indexed columns and the corresponding rows in the table.
c. Unique Index:
Ensures that the indexed columns have unique values across all rows in the table.
A primary key constraint is essentially a unique index.
d. Composite Index:
Created on multiple columns to improve queries that involve those columns.
4. Considerations:
Trade-offs:
While indexes improve read performance, they can slow down write operations (INSERT,
UPDATE, DELETE), as the indexes need to be maintained.
Indexes consume additional storage space.
Selectivity:
The selectivity of an index is a measure of how unique the values in the indexed column(s) are.
High selectivity is generally desirable for an index to be effective.
Choosing Columns:
Carefully select columns for indexing based on the queries that are frequently executed.
Example:
Consider a table Employees with columns EmployeeID, FirstName, LastName, and Salary.
Creating an index on the EmployeeID column might look like this:
CREATE INDEX idx_EmployeeID ON Employees(EmployeeID);

Now, queries that involve the EmployeeID column are likely to be faster due to the presence of
the index.
-- Query using the index
SELECT * FROM Employees WHERE EmployeeID = 101;

Indexes are crucial for optimizing database performance, but their usage should be carefully
considered based on the specific characteristics and workload of the database.
Q22.) Concept of Triggers.
In the context of databases, a trigger is a set of instructions or code that is automatically executed
("triggered") in response to certain events on a particular table or view. These events include data
manipulation language (DML) events like INSERT, UPDATE, DELETE, or data definition
language (DDL) events like CREATE, ALTER, or DROP. Triggers are used to enforce business
rules, maintain data integrity, or automate certain tasks when changes occur in the database.
Here are key concepts related to triggers:
a. Event and Timing:
Event: The type of operation that triggers the execution of the trigger (e.g., INSERT, UPDATE,
DELETE).
Timing: Triggers can be classified based on when they are executed relative to the triggering
event:
BEFORE: Executed before the triggering event.
AFTER: Executed after the triggering event.
b. Type of Triggers:
i. Row-Level Triggers:
Operate on each row affected by the triggering event.
ii. Statement-Level Triggers:
Operate once for each triggering event, regardless of the number of rows affected.
The choice between row-level and statement-level triggers depends on the specific requirements
of the task.
c. Purpose of Triggers
Enforcing Business Rules:
Triggers can be used to enforce complex business rules that are not easily represented by
constraints.
Auditing and Logging:
Triggers can be used to log changes to specific tables for auditing purposes.
Data Validation:
Triggers can validate data before it is inserted or updated in the database.
Automating Tasks:
Triggers can automate tasks such as sending notifications or updating related tables.

d. Syntax:
The syntax for creating a trigger varies between database management systems (DBMS), but a
general structure might look like this:
CREATE [OR REPLACE] TRIGGER trigger_name [BEFORE | AFTER] [INSERT | UPDATE | DELETE]
ON table_name [FOR EACH ROW] [WHEN (condition)] BEGIN

-- Trigger logic or actions

END;

Example:
Consider a scenario where you want to log changes to an Employees table in an audit table
EmployeeAudit. You could use an AFTER INSERT OR UPDATE trigger to achieve this:
CREATE OR REPLACE TRIGGER trg_AuditEmployeeChanges

AFTER INSERT OR UPDATE ON Employees

FOR EACH ROW

BEGIN

INSERT INTO EmployeeAudit (EmployeeID, Action, ActionDate)

VALUES (:NEW.EmployeeID, 'INSERT/UPDATE', SYSDATE);

END;

This trigger logs each insertion or update in the Employees table into the EmployeeAudit table,
recording the EmployeeID, action, and the date of the action.
Caution:
While triggers provide powerful capabilities, they should be used judiciously as they can
introduce complexity and potential performance overhead.
Poorly designed triggers can lead to unexpected behaviors or performance issues.
Triggers play a crucial role in database management systems by providing a mechanism for
automatically responding to changes in the data. When used appropriately, triggers contribute to
maintaining data integrity and enforcing business rules within the database.
Q23.) Recyclable and Low-Fat Products.
Poorly designed triggers can lead to unexpected behaviors or performance issues.
product_id is the primary key (column with unique values) for this table.
low_fats is an ENUM (category) of type ('Y', 'N') where 'Y' means this product is low fat and 'N'
means it is not.
recyclable is an ENUM (category) of types ('Y', 'N') where 'Y' means this product is recyclable and 'N'
means it is not.

Write a solution to find the ids of products that are both low fat and recyclable.
Return the result table in any order.
The result format is in the following example.
SOLUTION :--
select product_id from Products
where low_fats ='Y' and recyclable = 'Y'
Q24.) Find Customer Referee.
In SQL, id is the primary key column for this table.
Each row of this table indicates the id of a customer, their name, and the id of the customer who
referred them.

Find the names of the customer that are not referred by the customer with id = 2.
Return the result table in any order.
The result format is in the following example.

SOLUTION :--
SELECT name FROM Customer
WHERE referee_id !=2 or referee_id is null
Q25.) Big Countries.
name is the primary key (column with unique values) for this table.
Each row of this table gives information about the name of a country, the continent to which it
belongs, its area, the population, and its GDP value.

A country is big if:


• it has an area of at least three million (i.e., 3000000 km2), or
• it has a population of at least twenty-five million (i.e., 25000000).
Write a solution to find the name, population, and area of the big countries.
Return the result table in any order.
The result format is in the following example.
SOLUTION :--
SELECT name, population, area
FROM World
WHERE population >= 25000000 OR area >= 3000000;

You might also like