0% found this document useful (0 votes)
32 views

Lib DB operations

Uploaded by

HEMALAKSHMI D
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Lib DB operations

Uploaded by

HEMALAKSHMI D
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Open sidebar

Library DB Operations
Consider the following schema for a Library Database: BOOK (Book_id, Title, Publisher_Name,
Pub_Year, No_of_copies) BOOK_AUTHORS (Book_id, Author_Name) PUBLISHER (Name,
Address, Phone) Retrieve details of all books in the Book_id, title, name of publisher, authors
Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to
Jun2017. Delete a book in BOOK table. Update the contents of other tables to reflect this data
Manipulation operations. Create a view of all books and its number of copies that are currently
available in the Library. Write a Pl/SQL procedure to display the book details of particular
author. With sample output
1/1
ChatGPT

To address your request, I will provide SQL queries and a PL/SQL procedure that you can use to
perform the requested operations on the library database.

Please note that PL/SQL is a procedural language used in Oracle databases. If you're using a
different database system, you may need to adapt the syntax accordingly.

First, let's start with the SQL queries:

1. Retrieve details of all books in the Book_id, title, name of publisher, and authors:

sqlCopy code
SELECT b.Book_id, b.Title, p.Name AS Publisher_Name, ba.Author_Name
FROM BOOK b
JOIN BOOK_AUTHORS ba ON b.Book_id = ba.Book_id
JOIN PUBLISHER p ON b.Publisher_Name = p.Name;

2. Get the particulars of borrowers who have borrowed more than 3 books from Jan 2017 to
Jun 2017:

sqlCopy code
SELECT *
FROM Borrower
WHERE Borrower_id IN (
SELECT Borrower_id
FROM BorrowedBooks
WHERE Borrow_Date >= '2017-01-01' AND Borrow_Date <= '2017-06-30'
GROUP BY Borrower_id
HAVING COUNT(*) > 3
);

3. Delete a book in the BOOK table and update related tables:


sqlCopy code
DELETE FROM BOOK WHERE Book_id = <book_id>;
DELETE FROM BOOK_AUTHORS WHERE Book_id = <book_id>;

Next, let's create a view of all books and their number of copies that are currently available in the
library:

sqlCopy code
CREATE VIEW AvailableBooks AS
SELECT b.Book_id, b.Title, b.No_of_copies
FROM BOOK b
LEFT JOIN BorrowedBooks bb ON b.Book_id = bb.Book_id
GROUP BY b.Book_id, b.Title, b.No_of_copies
HAVING SUM(bb.Returned) = b.No_of_copies OR SUM(bb.Returned) IS NULL;

Now, let's write a PL/SQL procedure to display the book details of a particular author:

sqlCopy code
CREATE OR REPLACE PROCEDURE GetBooksByAuthor(author_name IN VARCHAR2) IS
BEGIN
FOR book_rec IN (
SELECT b.Book_id, b.Title, p.Name AS Publisher_Name
FROM BOOK b
JOIN BOOK_AUTHORS ba ON b.Book_id = ba.Book_id
JOIN PUBLISHER p ON b.Publisher_Name = p.Name
WHERE ba.Author_Name = author_name
) LOOP
DBMS_OUTPUT.PUT_LINE('Book ID: ' || book_rec.Book_id);
DBMS_OUTPUT.PUT_LINE('Title: ' || book_rec.Title);
DBMS_OUTPUT.PUT_LINE('Publisher: ' || book_rec.Publisher_Name);
DBMS_OUTPUT.NEW_LINE;
END LOOP;
END;
/

To run the PL/SQL procedure and see the output, you can execute the following anonymous
block:

sqlCopy code
BEGIN
GetBooksByAuthor('<author_name>');
END;

Make sure to replace <author_name> with the actual name of the author you're interested in.

That covers the retrieval, manipulation, and procedural operations you requested.

1/1

sample output for Create a table employee (S.No,Name, Desination,brach), a) Alter the table by
adding a column salary b) Copy the table employee as Emp c) Delete 2nd row from the table d)
Drop the table e) Demonstrate the triggers for automatic updation.
1/1
ChatGPT

Sure! I'll provide sample outputs for each step you mentioned:

a) Alter the table by adding a column salary:

sqlCopy code
ALTER TABLE employee ADD salary DECIMAL(10, 2);

Sample output: The table "employee" is altered to include the "salary" column.

b) Copy the table employee as Emp:

sqlCopy code
CREATE TABLE Emp AS SELECT * FROM employee;

Sample output: The table "employee" is copied to a new table called "Emp."

c) Delete the 2nd row from the table:

sqlCopy code
DELETE FROM employee WHERE S.No = 2;

Sample output: The 2nd row in the "employee" table is deleted.

d) Drop the table:

sqlCopy code
DROP TABLE employee;

Sample output: The table "employee" is dropped and no longer exists.

e) Demonstrate triggers for automatic updation: To demonstrate triggers, we need to define a


trigger and simulate a data update. Here's an example:

sqlCopy code
-- Step 1: Create the table with a trigger
CREATE TABLE employee (
S_No INT,
Name VARCHAR(50),
Designation VARCHAR(50),
Branch VARCHAR(50),
Salary DECIMAL(10, 2)
);

-- Step 2: Create a trigger to update the salary


CREATE OR REPLACE TRIGGER salary_update_trigger
BEFORE UPDATE ON employee
FOR EACH ROW
BEGIN
:NEW.Salary := :NEW.Salary * 1.1; -- Increase salary by 10%
END;
/

-- Step 3: Insert sample data


INSERT INTO employee (S_No, Name, Designation, Branch, Salary)
VALUES (1, 'John Doe', 'Manager', 'Head Office', 5000);

-- Step 4: Update the salary


UPDATE employee SET Salary = 6000 WHERE S_No = 1;

Sample output: After the update statement, the trigger is activated, and the salary is automatically
increased by 10%. So the new salary becomes 6600.

Please note that triggers are specific to the database system you are using. The example provided
above assumes an Oracle database.

1/1

Sample output for Create a table called Employee (Emp_no Emp_name, Emp_dept,Job Mgr.Sal)
a) By using the group by clause, display the Emp_name who belongs toEmp_dept="xxx" along
with salary b) Display lowest paid employee details under each department c) List the employee
names in descending order. d) Rename the column of Employee table using alter command e)
Insert row in employee table using Triggers.
1/1
ChatGPT

Based on the provided table structure, here are the sample outputs for each step:

a) By using the GROUP BY clause, display the Emp_name who belongs to Emp_dept = "xxx"
along with salary:

sqlCopy code
SELECT Emp_name, Salary
FROM Employee
WHERE Emp_dept = 'xxx'
GROUP BY Emp_name, Salary;

Sample output: This query will display the Emp_name and Salary of employees who belong to
the department 'xxx'.

b) Display the lowest paid employee details under each department:

sqlCopy code
SELECT Emp_dept, Emp_name, Salary
FROM Employee e
WHERE Salary = (
SELECT MIN(Salary)
FROM Employee
WHERE Emp_dept = e.Emp_dept
)
ORDER BY Emp_dept;

Sample output: This query will display the lowest paid employee details (Emp_dept, Emp_name,
and Salary) for each department.

c) List the employee names in descending order:

sqlCopy code
SELECT Emp_name
FROM Employee
ORDER BY Emp_name DESC;

Sample output: This query will display the employee names in descending order.

d) Rename the column of the Employee table using the ALTER command:

sqlCopy code
ALTER TABLE Employee RENAME COLUMN Emp_no TO Employee_no;

Sample output: The column "Emp_no" in the "Employee" table is renamed to "Employee_no".

e) Insert a row in the Employee table using triggers: To demonstrate triggers, we need to define a
trigger and insert a row into the Employee table. Here's an example:

sqlCopy code
-- Step 1: Create the Employee table
CREATE TABLE Employee (
Emp_no INT,
Emp_name VARCHAR(50),
Emp_dept VARCHAR(50),
Job VARCHAR(50),
Mgr INT,
Sal DECIMAL(10, 2)
);

-- Step 2: Create a trigger to insert a default row


CREATE OR REPLACE TRIGGER insert_employee_trigger
BEFORE INSERT ON Employee
FOR EACH ROW
BEGIN
IF :NEW.Emp_no IS NULL THEN
:NEW.Emp_no := 1;
:NEW.Emp_name := 'John Doe';
:NEW.Emp_dept := 'Department';
:NEW.Job := 'Job Title';
:NEW.Mgr := 1;
:NEW.Sal := 5000;
END IF;
END;
/
-- Step 3: Insert a row (trigger will populate default values)
INSERT INTO Employee (Emp_no) VALUES (NULL);

Sample output: After the insert statement, the trigger is activated, and it populates the default
values for the new row.

Please note that triggers are specific to the database system you are using. The example provided
above assumes an Oracle database.

1/1

Save & Submit


Cancel
ChatGPT

To create an "Employee" database and write SQL triggers for insert, delete, and update
operations, you can follow these steps:

1. Create the "Employee" database:

sqlCopy code
CREATE DATABASE Employee;
USE Employee;

2. Create the "Employee" table:

sqlCopy code
CREATE TABLE Employee (
Emp_id INT PRIMARY KEY,
Emp_name VARCHAR(50),
Emp_dept VARCHAR(50),
Salary DECIMAL(10, 2)
);

3. Write a trigger for insert operation:

sqlCopy code
CREATE TRIGGER insert_employee_trigger
AFTER INSERT ON Employee
FOR EACH ROW
BEGIN
-- Perform actions when a new row is inserted into the Employee table
-- You can add your custom logic here
-- Example: INSERT INTO LogTable (Action, Timestamp) VALUES
('INSERT', NOW());
END;
/

4. Write a trigger for delete operation:


sqlCopy code
CREATE TRIGGER delete_employee_trigger
AFTER DELETE ON Employee
FOR EACH ROW
BEGIN
-- Perform actions when a row is deleted from the Employee table
-- You can add your custom logic here
-- Example: INSERT INTO LogTable (Action, Timestamp) VALUES
('DELETE', NOW());
END;
/

5. Write a trigger for update operation:

sqlCopy code
CREATE TRIGGER update_employee_trigger
AFTER UPDATE ON Employee
FOR EACH ROW
BEGIN
-- Perform actions when a row is updated in the Employee table
-- You can add your custom logic here
-- Example: INSERT INTO LogTable (Action, Timestamp) VALUES
('UPDATE', NOW());
END;
/

Please note that these trigger examples are placeholders where you can add your custom logic.
You can replace the comments with actual SQL statements or other actions you want to perform
during insert, delete, or update operations.

Remember to adjust the table structure, trigger names, and any additional actions based on your
specific requirements for the "Employee" database.

3/3

sample output for Create a Employee database and write SQL Triggers for insert, delete, and
update operations in a database table.
1/1
ChatGPT

To provide a sample output, I'll demonstrate a basic implementation of SQL triggers for insert,
delete, and update operations in the "Employee" database. Here's an example:

1. Create the "Employee" database:

sqlCopy code
CREATE DATABASE Employee;
USE Employee;

2. Create the "Employee" table:


sqlCopy code
CREATE TABLE Employee (
Emp_id INT PRIMARY KEY,
Emp_name VARCHAR(50),
Emp_dept VARCHAR(50),
Salary DECIMAL(10, 2)
);

3. Write a trigger for insert operation:

sqlCopy code
CREATE TRIGGER insert_employee_trigger
AFTER INSERT ON Employee
FOR EACH ROW
BEGIN
INSERT INTO AuditLog (Operation, Timestamp)
VALUES ('INSERT', NOW());
END;
/

4. Write a trigger for delete operation:

sqlCopy code
CREATE TRIGGER delete_employee_trigger
AFTER DELETE ON Employee
FOR EACH ROW
BEGIN
INSERT INTO AuditLog (Operation, Timestamp)
VALUES ('DELETE', NOW());
END;
/

5. Write a trigger for update operation:

sqlCopy code
CREATE TRIGGER update_employee_trigger
AFTER UPDATE ON Employee
FOR EACH ROW
BEGIN
INSERT INTO AuditLog (Operation, Timestamp)
VALUES ('UPDATE', NOW());
END;
/

Sample output: When an insert, delete, or update operation is performed on the "Employee"
table, the respective trigger will be triggered and insert a new row into the "AuditLog" table with
the operation type and timestamp.

For example, if you execute the following insert statement:

sqlCopy code
INSERT INTO Employee (Emp_id, Emp_name, Emp_dept, Salary)
VALUES (1, 'John Doe', 'Sales', 5000);
The "insert_employee_trigger" will be activated and insert a row into the "AuditLog" table like
this:

markdownCopy code
Operation | Timestamp
---------------------
INSERT | 2023-05-26 10:30:00

Similarly, triggers for delete and update operations will also log their respective actions into the
"AuditLog" table.

Please note that the "AuditLog" table mentioned in the triggers is not created in this example, but
you can create it with appropriate columns (e.g., Operation, Timestamp) to store the audit
information.

1/1

Simple sql query Create a table Supplier (Sup_No, Sup_Name ,Item_Supplied , Item_Price ,
City) Write sql query to display Suplier numbers and Supplier names whose name starts with ‘S’
Write sql query to add a new column called CONTACTNO. Write sql query to display supplier
numbers, Suplier names and item price for suppliers in Chennai in the ascending order of item
price. Create a view on the table which displays only supplier numbers and supplier names.
Demonstrate the procedure for the supplier table.
1/1
ChatGPT

Sure! Here are the SQL queries to perform the requested operations on the "Supplier" table:

1. Write an SQL query to display Supplier numbers and Supplier names whose name starts
with 'S':

sqlCopy code
SELECT Sup_No, Sup_Name
FROM Supplier
WHERE Sup_Name LIKE 'S%';

2. Write an SQL query to add a new column called CONTACTNO:

sqlCopy code
ALTER TABLE Supplier
ADD COLUMN CONTACTNO VARCHAR(20);

3. Write an SQL query to display Supplier numbers, Supplier names, and item price for
suppliers in Chennai in ascending order of item price:

sqlCopy code
SELECT Sup_No, Sup_Name, Item_Price
FROM Supplier
WHERE City = 'Chennai'
ORDER BY Item_Price ASC;

4. Create a view on the table which displays only Supplier numbers and Supplier names:

sqlCopy code
CREATE VIEW SupplierView AS
SELECT Sup_No, Sup_Name
FROM Supplier;

5. Demonstrate a procedure for the Supplier table:

sqlCopy code
-- Create a procedure
CREATE PROCEDURE GetSupplierDetails AS
BEGIN
SELECT *
FROM Supplier;
END;

To execute the procedure, you can use the following SQL statement:

sqlCopy code
EXEC GetSupplierDetails;

Please note that the column names and table structure mentioned in the queries are assumed
based on the information provided. You may need to adjust them according to your actual table
structure.

1/1

With output
1/1
ChatGPT

Apologies for the confusion. Unfortunately, as an AI text-based model, I don't have the
capability to execute SQL queries or provide real-time output. However, I can provide you with
the expected output for each query based on the given sample data:

1. SQL query to display Supplier numbers and Supplier names whose name starts with 'S':

sqlCopy code
SELECT Sup_No, Sup_Name
FROM Supplier
WHERE Sup_Name LIKE 'S%';

Sample Output:

diffCopy code
Sup_No | Sup_Name
-------|----------
1 | Supplier1
3 | Supplier3

2. SQL query to add a new column called CONTACTNO:

sqlCopy code
ALTER TABLE Supplier
ADD COLUMN CONTACTNO VARCHAR(20);

No output will be displayed for this query. It simply adds a new column to the "Supplier" table.

3. SQL query to display Supplier numbers, Supplier names, and item price for suppliers in
Chennai in ascending order of item price:

sqlCopy code
SELECT Sup_No, Sup_Name, Item_Price
FROM Supplier
WHERE City = 'Chennai'
ORDER BY Item_Price ASC;

Sample Output:

diffCopy code
Sup_No | Sup_Name | Item_Price
-------|------------|-----------
2 | Supplier2 | 100.00
4 | Supplier4 | 150.00

4. Create a view on the table which displays only Supplier numbers and Supplier names:

sqlCopy code
CREATE VIEW SupplierView AS
SELECT Sup_No, Sup_Name
FROM Supplier;

No output will be displayed for this query. It creates a view named "SupplierView" that contains
the selected columns from the "Supplier" table.

5. Demonstrate a procedure for the Supplier table:

sqlCopy code
-- Create a procedure
CREATE PROCEDURE GetSupplierDetails AS
BEGIN
SELECT *
FROM Supplier;
END;

No output will be displayed for this query. It creates a stored procedure named
"GetSupplierDetails" that retrieves all the rows from the "Supplier" table.
To execute the procedure and view the output, you can use the following SQL statement:

sqlCopy code
EXEC GetSupplierDetails;

The output will be the result of the SELECT query inside the procedure, displaying all the rows
and columns from the "Supplier" table.

Please note that the actual output may differ based on the data in your specific "Supplier" table.

1/1

Simple query Create an XML database for the student profile and validate it using XML schema.
1/1
ChatGPT

To create an XML database for student profiles and validate it using an XML schema, you can
follow these steps:

1. Define the XML structure for the student profile. Here's an example:

xmlCopy code
<Students>
<Student>
<ID>123</ID>
<Name>John Doe</Name>
<Age>20</Age>
<Email>[email protected]</Email>
<Address>
<Street>123 Main Street</Street>
<City>New York</City>
<State>NY</State>
<ZipCode>12345</ZipCode>
</Address>
</Student>
<Student>
<ID>456</ID>
<Name>Jane Smith</Name>
<Age>22</Age>
<Email>[email protected]</Email>
<Address>
<Street>456 Oak Avenue</Street>
<City>Los Angeles</City>
<State>CA</State>
<ZipCode>98765</ZipCode>
</Address>
</Student>
<!-- Add more student profiles here -->
</Students>

2. Save the XML data into a file, such as "student_profiles.xml".


3. Define an XML schema to validate the student profile XML data. Here's an example
schema:

xmlCopy code
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Students">
<xs:complexType>
<xs:sequence>
<xs:element name="Student" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="ID" type="xs:string"/>
<xs:element name="Name" type="xs:string"/>
<xs:element name="Age" type="xs:integer"/>
<xs:element name="Email" type="xs:string"/>
<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="Street" type="xs:string"/>
<xs:element name="City" type="xs:string"/>
<xs:element name="State" type="xs:string"/>
<xs:element name="ZipCode" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

4. Save the XML schema into a file, such as "student_profiles.xsd".


5. Use an XML parser or an XML database management system that supports XML schema
validation to validate the "student_profiles.xml" file against the "student_profiles.xsd"
schema.

The specific process for validating XML against an XML schema may vary depending on the
tools or programming languages you are using. However, most XML parsers and databases
provide functions or methods for schema validation. You can refer to the documentation or
examples provided by the tool or library you are using to perform the validation.

Please note that the XML schema provided here is a simple example, and you may need to
modify it to match the specific structure and data types of your student profile XML data.

1/1

Create the tables SALESMAN (Salesman_id, Name, City, Commission), CUSTOMER


(Customer_id, Cust_Name, City, Grade,Salesman_id), ORDERS (Ord_No, Purchase_Amt,
Ord_Date, Customer_id, Salesman_id) Find the name and numbers of all salesmen who had
more than one customer. List all salesmen and indicate those who have and don’t have customers
in their cities (Use UNION operation.) Create a view that finds the salesman who has the
customer with the highest order of a day. Perform the DELETE operation by removing salesman
with id 1000. All his orders must also be deleted. Demonstrate the Triggers for the above table.
1/1
ChatGPT

Here's the implementation for the provided tasks using the given tables and sample data:

1. Create the tables:

sqlCopy code
CREATE TABLE SALESMAN (
Salesman_id INT PRIMARY KEY,
Name VARCHAR(50),
City VARCHAR(50),
Commission DECIMAL(10, 2)
);

CREATE TABLE CUSTOMER (


Customer_id INT PRIMARY KEY,
Cust_Name VARCHAR(50),
City VARCHAR(50),
Grade INT,
Salesman_id INT,
FOREIGN KEY (Salesman_id) REFERENCES SALESMAN(Salesman_id)
);

CREATE TABLE ORDERS (


Ord_No INT PRIMARY KEY,
Purchase_Amt DECIMAL(10, 2),
Ord_Date DATE,
Customer_id INT,
Salesman_id INT,
FOREIGN KEY (Customer_id) REFERENCES CUSTOMER(Customer_id),
FOREIGN KEY (Salesman_id) REFERENCES SALESMAN(Salesman_id)
);

2. Find the name and numbers of all salesmen who had more than one customer:

sqlCopy code
SELECT s.Name, COUNT(c.Customer_id) AS Num_Customers
FROM SALESMAN s
JOIN CUSTOMER c ON s.Salesman_id = c.Salesman_id
GROUP BY s.Salesman_id
HAVING COUNT(c.Customer_id) > 1;

3. List all salesmen and indicate those who have and don't have customers in their cities
(Use UNION operation):

sqlCopy code
SELECT s.Name, s.City, 'Has Customers' AS Status
FROM SALESMAN s
WHERE EXISTS (SELECT 1 FROM CUSTOMER c WHERE s.Salesman_id = c.Salesman_id)
UNION
SELECT s.Name, s.City, 'No Customers' AS Status
FROM SALESMAN s
WHERE NOT EXISTS (SELECT 1 FROM CUSTOMER c WHERE s.Salesman_id =
c.Salesman_id);

4. Create a view that finds the salesman who has the customer with the highest order of a
day:

sqlCopy code
CREATE VIEW Salesman_Highest_Order AS
SELECT o.Salesman_id, MAX(o.Purchase_Amt) AS Highest_Order
FROM ORDERS o
GROUP BY o.Salesman_id;

5. Perform the DELETE operation by removing the salesman with id 1000. All his orders
must also be deleted:

sqlCopy code
DELETE FROM ORDERS WHERE Salesman_id = 1000;
DELETE FROM CUSTOMER WHERE Salesman_id = 1000;
DELETE FROM SALESMAN WHERE Salesman_id = 1000;

6. Demonstrate the triggers for the above tables. Here's an example of a trigger that logs an
entry whenever a new order is inserted:

sqlCopy code
CREATE TRIGGER insert_order_trigger
AFTER INSERT ON ORDERS
FOR EACH ROW
BEGIN
INSERT INTO OrderLog (Ord_No, Action, Timestamp)
VALUES (NEW.Ord_No, 'INSERT', NOW());
END;

You can create additional triggers for other operations (update, delete) on the tables as needed.

Note: For the triggers, you'll need to create the necessary log tables (e.g., "OrderLog") to store
the trigger actions and timestamps. The table structures for the log tables are not provided in the
question, so please adjust them based on your requirements.

Please note that the table structures and sample data are not provided in the question, so the
actual output may vary based on your specific data.

1/1

Create the tables CUSTOMER (C_ID, Name, Address, City, Mobile_No) and ORDER (C_ID,
P_ID, P_Name, P_COST), List the names and addresses of all the customers who have ordered
products of costmore than 500. List the names of all the products ordered whose cost is 1,000 or
more. List the product names which are ordered by customers of "City = Delhi". Add column
"Email_id" in the CUSTOMER table. Demonstrate the user defined function for the above
tables.
1/1
ChatGPT

Here's the implementation for the provided tasks using the given tables:

1. Create the tables:

sqlCopy code
CREATE TABLE CUSTOMER (
C_ID INT PRIMARY KEY,
Name VARCHAR(50),
Address VARCHAR(100),
City VARCHAR(50),
Mobile_No VARCHAR(20)
);

CREATE TABLE ORDERS (


C_ID INT,
P_ID INT,
P_Name VARCHAR(50),
P_COST DECIMAL(10, 2),
FOREIGN KEY (C_ID) REFERENCES CUSTOMER(C_ID)
);

2. List the names and addresses of all the customers who have ordered products of cost
more than 500:

sqlCopy code
SELECT c.Name, c.Address
FROM CUSTOMER c
JOIN ORDERS o ON c.C_ID = o.C_ID
WHERE o.P_COST > 500;

3. List the names of all the products ordered whose cost is 1,000 or more:

sqlCopy code
SELECT P_Name
FROM ORDERS
WHERE P_COST >= 1000;

4. List the product names which are ordered by customers of "City = Delhi":

sqlCopy code
SELECT P_Name
FROM ORDERS o
JOIN CUSTOMER c ON o.C_ID = c.C_ID
WHERE c.City = 'Delhi';

5. Add a column "Email_id" in the CUSTOMER table:


sqlCopy code
ALTER TABLE CUSTOMER
ADD COLUMN Email_id VARCHAR(50);

6. Demonstrate a user-defined function for the above tables. Here's an example of a function
that calculates the total number of orders placed by a customer:

sqlCopy code
CREATE FUNCTION GetOrderCountByCustomer(CustID INT)
RETURNS INT
BEGIN
DECLARE orderCount INT;

SELECT COUNT(*) INTO orderCount


FROM ORDERS
WHERE C_ID = CustID;

RETURN orderCount;
END;

You can create additional user-defined functions based on your requirements.

Please note that the table structures and sample data are not provided in the question, so the
actual output may vary based on your specific data. Also, make sure to adjust the column names
and data types based on your requirements.

1/1

Simple query for Create a table Account (Account_No, Cust_Name, Branch_Name,


Account_Balance, Account_Type) Select an appropriate primary key. Display the Cust_Name
and Account_No of the customers of "Branch = XXXXX". Display the names and account types
of all the customers whose account balance is more than 10,000. Add column Cust_Date_of
Birth in the ACCOUNT table. Display Account_No, Cust_Name and Branch of all the customers
whose account balance is less than 1,000. Write a procedure for the above Database.
1/1
ChatGPT

Here's the implementation for the provided tasks using the given table structure:

1. Create the table:

sqlCopy code
CREATE TABLE Account (
Account_No INT PRIMARY KEY,
Cust_Name VARCHAR(50),
Branch_Name VARCHAR(50),
Account_Balance DECIMAL(10, 2),
Account_Type VARCHAR(50)
);
2. Display the Cust_Name and Account_No of the customers of "Branch = XXXXX":

sqlCopy code
SELECT Cust_Name, Account_No
FROM Account
WHERE Branch_Name = 'XXXXX';

3. Display the names and account types of all the customers whose account balance is more
than 10,000:

sqlCopy code
SELECT Cust_Name, Account_Type
FROM Account
WHERE Account_Balance > 10000;

4. Add column Cust_Date_of_Birth in the Account table:

sqlCopy code
ALTER TABLE Account
ADD COLUMN Cust_Date_of_Birth DATE;

5. Display Account_No, Cust_Name, and Branch of all the customers whose account
balance is less than 1,000:

sqlCopy code
SELECT Account_No, Cust_Name, Branch_Name
FROM Account
WHERE Account_Balance < 1000;

6. Write a procedure for the above database. Here's an example of a procedure that retrieves
customer details based on the account balance:

sqlCopy code
CREATE PROCEDURE GetCustomersByBalance (balance DECIMAL(10, 2))
BEGIN
SELECT Account_No, Cust_Name, Branch_Name
FROM Account
WHERE Account_Balance < balance;
END;

You can modify the procedure based on your specific requirements.

To execute the procedure and view the output, you can use the following SQL statement:

sqlCopy code
CALL GetCustomersByBalance(1000);

The output will be the result of the SELECT query inside the procedure, displaying the
Account_No, Cust_Name, and Branch_Name of customers whose account balance is less than
1,000.
Please note that the actual output may vary based on the data in your specific "Account" table.

1/1

Create table as Bank ( S.No,Cust_Name, Acc_No, Balance, Branch), Select with where clause.
Select with comparison operator. Update the balance in the second row. Select with between in
the field balance. Write a trigger when balance is below 1000.
1/1
ChatGPT

Here's the implementation for the provided tasks using the given table structure:

1. Create the table:

sqlCopy code
CREATE TABLE Bank (
S_No INT PRIMARY KEY,
Cust_Name VARCHAR(50),
Acc_No INT,
Balance DECIMAL(10, 2),
Branch VARCHAR(50)
);

2. Select with the WHERE clause:

sqlCopy code
SELECT Cust_Name, Balance
FROM Bank
WHERE Branch = 'XXXXX';

Replace 'XXXXX' with the desired branch name.

3. Select with a comparison operator:

sqlCopy code
SELECT Cust_Name, Balance
FROM Bank
WHERE Balance > 10000;

This query will retrieve the Cust_Name and Balance of customers with a balance greater than
10,000.

4. Update the balance in the second row:

sqlCopy code
UPDATE Bank
SET Balance = 5000
WHERE S_No = 2;

This query updates the balance to 5000 for the row with S_No = 2.
5. Select with BETWEEN in the field balance:

sqlCopy code
SELECT Cust_Name, Balance
FROM Bank
WHERE Balance BETWEEN 1000 AND 5000;

This query will retrieve the Cust_Name and Balance of customers with a balance between 1000
and 5000.

6. Write a trigger when the balance is below 1000:

sqlCopy code
CREATE TRIGGER balance_trigger
BEFORE UPDATE ON Bank
FOR EACH ROW
BEGIN
IF NEW.Balance < 1000 THEN
-- Perform desired actions or raise an error
-- Here, you can write your desired logic or actions when the balance is
below 1000.
-- For example, you can log the event, send a notification, or prevent
the update.
END IF;
END;

This trigger will be executed before any UPDATE operation on the Bank table, and it will check
if the new balance value is below 1000. You can add your own logic or actions inside the IF
statement.

Please note that the table structure and sample data are not provided in the question, so the actual
output and behavior may vary based on your specific data.

1/1

In simple query to Consider the schema for College Database: STUDENT (RegNo, StudName,
Address, Phone, Gender) SUBJECT (Subcode, Title, Sem, Credits) MARKS (RegNo, Subcode,
Test1, Test2, Test3, Finalmark) Compute the total number of male and female students in each
semester and in each section. Calculate the Finalmark (average of best two test marks) and
update the corresponding table for all students. Categorize students based on the following
criterion: If Finalmark = 81 to 100 then CAT = ‘Outstanding’ If Finalmark = 51 to 80 then CAT
= ‘Average’ If Finalmark < 51 then CAT = ‘Weak Create a view of Test3 marks of particular
student in all subjects. Demonstrate the procedure for the above Database
1/1
ChatGPT

Here's the implementation for the provided tasks using the given schema:
1. Compute the total number of male and female students in each semester and in each
section:

sqlCopy code
SELECT s.Sem, s.Section, s.Gender, COUNT(*) AS Total_Students
FROM STUDENT s
GROUP BY s.Sem, s.Section, s.Gender;

2. Calculate the Finalmark (average of best two test marks) and update the corresponding
table for all students:

sqlCopy code
UPDATE MARKS m
SET Finalmark = (m.Test1 + m.Test2 + m.Test3 - LEAST(m.Test1, m.Test2,
m.Test3)) / 2;

This query updates the Finalmark column in the MARKS table for all students by calculating the
average of the best two test marks.

3. Categorize students based on the Finalmark criterion:

sqlCopy code
UPDATE MARKS
SET CAT = CASE
WHEN Finalmark >= 81 THEN 'Outstanding'
WHEN Finalmark >= 51 THEN 'Average'
ELSE 'Weak'
END;

This query updates the CAT column in the MARKS table based on the Finalmark value,
categorizing students as 'Outstanding', 'Average', or 'Weak'.

4. Create a view of Test3 marks of a particular student in all subjects:

sqlCopy code
CREATE VIEW Student_Test3_Marks AS
SELECT m.RegNo, m.Subcode, m.Test3
FROM MARKS m
WHERE m.RegNo = 'XXXXX';

Replace 'XXXXX' with the specific RegNo of the student.

5. Demonstrate the procedure for the above database. Here's an example of a procedure that
calculates the average Finalmark for all students:

sqlCopy code
CREATE PROCEDURE CalculateAverageFinalMarks ()
BEGIN
DECLARE totalStudents INT;
DECLARE sumFinalMarks DECIMAL(10, 2);
DECLARE averageFinalMarks DECIMAL(10, 2);
SELECT COUNT(*) INTO totalStudents FROM MARKS;
SELECT SUM(Finalmark) INTO sumFinalMarks FROM MARKS;
SET averageFinalMarks = sumFinalMarks / totalStudents;

SELECT averageFinalMarks;
END;

To execute the procedure and view the output, you can use the following SQL statement:

sqlCopy code
CALL CalculateAverageFinalMarks();

The output will be the average Finalmark calculated for all the students in the MARKS table.

Please note that the table structures and sample data are not provided in the question, so the
actual output may vary based on your specific data.

1/1

Consider the following schema for a Library Database: BOOK (Book_id, Title, Publisher_Name,
Pub_Year, No_of_copies) BOOK_AUTHORS (Book_id, Author_Name) PUBLISHER (Name,
Address, Phone) Retrieve details of all books in the Book_id, title, name of publisher, authors
Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to
Jun2017. Delete a book in BOOK table. Update the contents of other tables to reflect this data
Manipulation operations. Create a view of all books and its number of copies that are currently
available in the Library. Write a Pl/SQL procedure to display the book details of particular
author.
1/1
ChatGPT

Here's the implementation for the provided tasks using the given schema:

1. Retrieve details of all books including Book_id, title, name of publisher, and authors:

sqlCopy code
SELECT b.Book_id, b.Title, p.Name AS Publisher_Name, ba.Author_Name
FROM BOOK b
JOIN BOOK_AUTHORS ba ON b.Book_id = ba.Book_id
JOIN PUBLISHER p ON b.Publisher_Name = p.Name;

2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan
2017 to Jun 2017:

sqlCopy code
SELECT b.Borrower_Name, COUNT(*) AS Total_Borrowed
FROM BORROWED_BOOKS b
WHERE b.Borrow_Date BETWEEN '2017-01-01' AND '2017-06-30'
GROUP BY b.Borrower_Name
HAVING COUNT(*) > 3;
Replace 'BORROWED_BOOKS' with the actual table name for tracking borrowed books.

3. Delete a book in the BOOK table and update the contents of other tables to reflect this
data manipulation:

sqlCopy code
DELETE FROM BOOK
WHERE Book_id = 'XXXXX';

DELETE FROM BOOK_AUTHORS


WHERE Book_id = 'XXXXX';

-- Update other tables as necessary to remove references to the deleted book.

Replace 'XXXXX' with the specific Book_id of the book you want to delete. Make sure to
update any other tables that reference the BOOK table to remove the corresponding entries.

4. Create a view of all books and its number of copies that are currently available in the
Library:

sqlCopy code
CREATE VIEW Available_Books AS
SELECT b.Book_id, b.Title, b.No_of_copies
FROM BOOK b
WHERE b.No_of_copies > 0;

This view will display the Book_id, Title, and No_of_copies for books that have more than 0
copies available.

5. Write a PL/SQL procedure to display the book details of a particular author:

sqlCopy code
CREATE OR REPLACE PROCEDURE GetBookDetailsByAuthor (
author_name IN VARCHAR2
)
IS
BEGIN
FOR rec IN (SELECT b.Book_id, b.Title, p.Name AS Publisher_Name
FROM BOOK b
JOIN BOOK_AUTHORS ba ON b.Book_id = ba.Book_id
JOIN PUBLISHER p ON b.Publisher_Name = p.Name
WHERE ba.Author_Name = author_name)
LOOP
DBMS_OUTPUT.PUT_LINE('Book ID: ' || rec.Book_id || ', Title: ' ||
rec.Title || ', Publisher: ' || rec.Publisher_Name);
END LOOP;
END;

You can execute the procedure and view the output using the following PL/SQL block:

sqlCopy code
BEGIN
GetBookDetailsByAuthor('John Doe');
END;

Replace 'John Doe' with the specific author name you want to retrieve the book details for. The
output will be displayed using the DBMS_OUTPUT.PUT_LINE statement inside the procedure.

Please note that the table structures and sample data are not provided in the question, so the
actual output may vary based on your specific data.

1/1

Create a table employee (S.No,Name,Desination,brach), Alter the table by adding a column


salary Copy the table employee as Emp Delete 2nd row from the table Drop the table
Demonstrate the triggers for automatic updation.
1/1
ChatGPT

Here's the implementation for the provided tasks:

1. Create the table 'employee':

sqlCopy code
CREATE TABLE employee (
S_No INT,
Name VARCHAR(50),
Designation VARCHAR(50),
Branch VARCHAR(50)
);

2. Alter the table by adding a column 'salary':

sqlCopy code
ALTER TABLE employee
ADD Salary DECIMAL(10, 2);

3. Copy the table 'employee' as 'Emp':

sqlCopy code
CREATE TABLE Emp AS
SELECT *
FROM employee;

4. Delete the 2nd row from the table 'employee':

sqlCopy code
DELETE FROM employee
WHERE S_No = 2;

5. Drop the table 'employee':


sqlCopy code
DROP TABLE employee;

6. Demonstrate triggers for automatic updation: Triggers can be used to automatically


update data in response to certain events, such as INSERT, UPDATE, or DELETE
operations. Here's an example of a trigger that updates the 'last_updated' column of the
'employee' table whenever a row is modified:

sqlCopy code
CREATE TRIGGER update_last_updated
BEFORE UPDATE ON employee
FOR EACH ROW
BEGIN
:NEW.last_updated := CURRENT_TIMESTAMP;
END;

This trigger sets the 'last_updated' column to the current timestamp before each UPDATE
operation on the 'employee' table. You can modify the trigger to include your desired logic or
actions.

Note: In the trigger example above, I assumed the existence of a column named 'last_updated' in
the 'employee' table. You can modify the trigger based on your specific column names and
requirements.

Please ensure to adjust the table and column names based on your needs and to handle the data
accordingly.

1/1

Create a table called Employee (Emp_no Emp_name, Emp_dept,Job ,Mgr ,Sal) By using the
group by clause, display the Emp_name who belongs to Emp_dept=”xxx” along with salary
Display lowest paid employee details under each department List the employee names in
descending order. Rename the column of Employee table using alter command Insert row in
employee table using Triggers.
1/1
ChatGPT

Here's the implementation for the provided tasks:

1. Create the table 'Employee':

sqlCopy code
CREATE TABLE Employee (
Emp_no INT,
Emp_name VARCHAR(50),
Emp_dept VARCHAR(50),
Job VARCHAR(50),
Mgr INT,
Sal DECIMAL(10, 2)
);
2. Using the GROUP BY clause, display the Emp_name who belongs to Emp_dept="xxx"
along with salary:

sqlCopy code
SELECT Emp_name, Sal
FROM Employee
WHERE Emp_dept = 'xxx'
GROUP BY Emp_name, Sal;

3. Display the lowest paid employee details under each department:

sqlCopy code
SELECT Emp_dept, Emp_name, Sal
FROM Employee
WHERE (Emp_dept, Sal) IN (
SELECT Emp_dept, MIN(Sal)
FROM Employee
GROUP BY Emp_dept
);

4. List the employee names in descending order:

sqlCopy code
SELECT Emp_name
FROM Employee
ORDER BY Emp_name DESC;

5. Rename the column of the Employee table using ALTER command:

sqlCopy code
ALTER TABLE Employee
RENAME COLUMN Emp_name TO Employee_name;

This renames the 'Emp_name' column to 'Employee_name' in the 'Employee' table.

6. Insert a row into the Employee table using Triggers: Triggers are used to automatically
perform actions when certain events occur, such as INSERT, UPDATE, or DELETE
operations. Here's an example of a trigger that inserts a row into the 'Employee' table
whenever a new employee is added to the 'New_Employee' table:

sqlCopy code
CREATE TRIGGER insert_employee_trigger
AFTER INSERT ON New_Employee
FOR EACH ROW
BEGIN
INSERT INTO Employee (Emp_no, Employee_name, Emp_dept, Job, Mgr, Sal)
VALUES (:NEW.Emp_no, :NEW.Employee_name, :NEW.Emp_dept, :NEW.Job, :NEW.Mgr,
:NEW.Sal);
END;
This trigger captures the inserted values from the 'New_Employee' table and inserts them into the
'Employee' table. You can modify the trigger to fit your specific requirements and table
structures.

Note: In the trigger example above, I assumed the existence of a table named 'New_Employee'
with columns matching the 'Employee' table. You can modify the trigger and table names to
match your specific scenario.

Please ensure to adjust the table and column names based on your needs and to handle the data
accordingly.

1/1

Consider the following tables namely “DEPARTMENTS” and “EMPLOYEES” Departments


(dept _no , dept_ name , dept_location ), Employees ( emp_id , emp_name ,
emp_salary,dept_no). Develop a query to grant some privileges of employees table into
departments table Develop a query to revoke all privileges of employees table from departments
table Develop a query to revoke some privileges of employees table from departments table
Write a query to implement the save point. Demonstrate the user defined procedure for the above
employee database
1/1
ChatGPT

To perform the tasks as described, here's the implementation for each query:

1. Grant some privileges of the Employees table into the Departments table:

sqlCopy code
GRANT SELECT, INSERT, UPDATE ON Employees TO Departments;

This query grants the SELECT, INSERT, and UPDATE privileges on the Employees table to the
Departments table.

2. Revoke all privileges of the Employees table from the Departments table:

sqlCopy code
REVOKE ALL PRIVILEGES ON Employees FROM Departments;

This query revokes all privileges on the Employees table from the Departments table.

3. Revoke some privileges of the Employees table from the Departments table:

sqlCopy code
REVOKE INSERT, UPDATE ON Employees FROM Departments;

This query revokes the INSERT and UPDATE privileges on the Employees table from the
Departments table.
4. Implement a savepoint:

sqlCopy code
SAVEPOINT my_savepoint;

This query sets a savepoint named 'my_savepoint' in the transaction. You can use this savepoint
to roll back the transaction to a specific point if needed.

5. Demonstrate a user-defined procedure for the Employee database: To demonstrate a user-


defined procedure, here's an example of a procedure that retrieves employee details based
on their department:

sqlCopy code
CREATE OR REPLACE PROCEDURE GetEmployeesByDepartment (
department_name IN VARCHAR2
)
IS
BEGIN
FOR rec IN (SELECT emp_id, emp_name, emp_salary
FROM Employees
WHERE dept_no = (
SELECT dept_no
FROM Departments
WHERE dept_name = department_name
))
LOOP
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || rec.emp_id || ', Name: ' ||
rec.emp_name || ', Salary: ' || rec.emp_salary);
END LOOP;
END;

You can execute the procedure and view the output using the following PL/SQL block:

sqlCopy code
BEGIN
GetEmployeesByDepartment('IT');
END;

Replace 'IT' with the specific department name you want to retrieve the employee details for.
The output will be displayed using the DBMS_OUTPUT.PUT_LINE statement inside the
procedure.

Note: The above examples assume that you have the necessary privileges to perform the
specified actions. Make sure to adjust the table and column names based on your database
structure and handle the data accordingly.

1/1

Create the following tables, Event (eventid, name, description,city) Participant (playerid, name,
eventid, gender, year) Prizes (prizeid, prize-money, eventid, rank,year) Winners (prizeid,
playerid) Choose appropriate primary keys and foreign keys for the tables. Playerid should
contain at least one digit character. Retrieve the name of events where all prize winners are
females Create a non-updatable view to retrieve the names of all participants who won 1st prizes
along with their event names Write a trigger to make sure that for every new event created, 3
prizes are created in prizes table. (1st prize - 1500, 2nd - 1000, 3rd 500)
1/1
ChatGPT

Here's the implementation for the provided tasks:

1. Create the tables with appropriate primary keys and foreign keys:

sqlCopy code
CREATE TABLE Event (
eventid INT PRIMARY KEY,
name VARCHAR(50),
description VARCHAR(100),
city VARCHAR(50)
);

CREATE TABLE Participant (


playerid VARCHAR(10) PRIMARY KEY,
name VARCHAR(50),
eventid INT,
gender VARCHAR(10),
year INT,
FOREIGN KEY (eventid) REFERENCES Event(eventid)
);

CREATE TABLE Prizes (


prizeid INT PRIMARY KEY,
prize_money DECIMAL(10, 2),
eventid INT,
rank INT,
year INT,
FOREIGN KEY (eventid) REFERENCES Event(eventid)
);

CREATE TABLE Winners (


prizeid INT,
playerid VARCHAR(10),
FOREIGN KEY (prizeid) REFERENCES Prizes(prizeid),
FOREIGN KEY (playerid) REFERENCES Participant(playerid)
);

2. Retrieve the name of events where all prize winners are females:

sqlCopy code
SELECT e.name
FROM Event e
WHERE NOT EXISTS (
SELECT *
FROM Winners w
INNER JOIN Participant p ON w.playerid = p.playerid
WHERE w.prizeid IN (
SELECT prizeid
FROM Prizes
WHERE eventid = e.eventid
) AND p.gender <> 'Female'
);

3. Create a non-updatable view to retrieve the names of all participants who won 1st prizes
along with their event names:

sqlCopy code
CREATE VIEW Winners_1st_Prize AS
SELECT p.name AS participant_name, e.name AS event_name
FROM Participant p
INNER JOIN Winners w ON p.playerid = w.playerid
INNER JOIN Prizes pz ON w.prizeid = pz.prizeid
INNER JOIN Event e ON pz.eventid = e.eventid
WHERE pz.rank = 1;

This view retrieves the names of participants and their corresponding event names who won the
1st prize.

4. Write a trigger to ensure that for every new event created, 3 prizes are created in the
prizes table:

sqlCopy code
CREATE OR REPLACE TRIGGER Create_Prizes
AFTER INSERT ON Event
FOR EACH ROW
BEGIN
INSERT INTO Prizes (prizeid, prize_money, eventid, rank, year)
VALUES (:NEW.eventid, 1500, :NEW.eventid, 1, EXTRACT(YEAR FROM SYSDATE));

INSERT INTO Prizes (prizeid, prize_money, eventid, rank, year)


VALUES (:NEW.eventid + 1, 1000, :NEW.eventid, 2, EXTRACT(YEAR FROM
SYSDATE));

INSERT INTO Prizes (prizeid, prize_money, eventid, rank, year)


VALUES (:NEW.eventid + 2, 500, :NEW.eventid, 3, EXTRACT(YEAR FROM
SYSDATE));
END;

This trigger automatically creates three prizes with different ranks and prize money for each new
event inserted into the Event table. The prizeids are incremented based on the eventid of the
newly inserted event.

Note: The above examples assume that you have the necessary privileges to perform the
specified actions. Make sure to adjust the table and column names based on your database
structure and handle the data accordingly.

1/1
Consider the schema for Movie Database: ACTOR (Act_id, Act_Name, Act_Gender)
DIRECTOR (Dir_id, Dir_Name, Dir_Phone) MOVIES (Mov_id, Mov_Title, Mov_Year,
Mov_Lang, Dir_id) MOVIE_CAST (Act_id, Mov_id, Role) List the titles of all movies directed
by ‘XXXX’. Find the movie names where one or more actors acted in two or more movies. List
all actors who acted in a movie before 2010 and also in a movie after 2015 (use JOIN operation).
Create a view of movies with a particular actor with director. Demonstrate the User defined
function for the movie database.
1/1
ChatGPT

To address your requirements, here's the implementation for each task:

1. List the titles of all movies directed by 'XXXX':

sqlCopy code
SELECT Mov_Title
FROM MOVIES
WHERE Dir_id = (
SELECT Dir_id
FROM DIRECTOR
WHERE Dir_Name = 'XXXX'
);

Replace 'XXXX' with the name of the director you want to search for. This query retrieves the
titles of all movies directed by the specified director.

2. Find the movie names where one or more actors acted in two or more movies:

sqlCopy code
SELECT Mov_Title
FROM MOVIES
WHERE Mov_id IN (
SELECT Mov_id
FROM MOVIE_CAST
GROUP BY Mov_id
HAVING COUNT(DISTINCT Act_id) >= 2
);

This query retrieves the movie names where one or more actors have acted in two or more
movies.

3. List all actors who acted in a movie before 2010 and also in a movie after 2015:

sqlCopy code
SELECT DISTINCT Act_Name
FROM ACTOR
WHERE Act_id IN (
SELECT Act_id
FROM MOVIE_CAST
WHERE Mov_id IN (
SELECT Mov_id
FROM MOVIES
WHERE Mov_Year < 2010
)
) AND Act_id IN (
SELECT Act_id
FROM MOVIE_CAST
WHERE Mov_id IN (
SELECT Mov_id
FROM MOVIES
WHERE Mov_Year > 2015
)
);

This query retrieves the names of all actors who have acted in a movie before 2010 and also in a
movie after 2015.

4. Create a view of movies with a particular actor with director:

sqlCopy code
CREATE VIEW Movie_Actor_Director AS
SELECT m.Mov_Title, a.Act_Name, d.Dir_Name
FROM MOVIES m
JOIN MOVIE_CAST mc ON m.Mov_id = mc.Mov_id
JOIN ACTOR a ON mc.Act_id = a.Act_id
JOIN DIRECTOR d ON m.Dir_id = d.Dir_id;

This view combines movie titles, actor names, and director names in a single view.

5. Demonstrate a user-defined function for the movie database: Here's an example of a user-
defined function that calculates the average rating for a movie based on its reviews:

sqlCopy code
CREATE FUNCTION CalculateAverageRating (mov_id INT)
RETURNS DECIMAL(4, 2)
AS
BEGIN
DECLARE @AverageRating DECIMAL(4, 2);

SELECT @AverageRating = AVG(Rating)


FROM REVIEWS
WHERE Mov_id = @mov_id;

RETURN @AverageRating;
END;

You can call this function by providing the movie ID as an argument, and it will return the
average rating for that movie.

Note: The above examples assume that you have the necessary tables and data in your Movie
Database. Make sure to adjust the table and column names based on your database structure and
handle the data accordingly.
1/1

Consider the schema for College Database: STUDENT (RegNo, StudName, Address, Phone,
Gender) SUBJECT (Subcode, Title, Sem, Credits) MARKS (RegNo, Subcode, Test1, Test2,
Test3, Finalmark) Compute the total number of male and female students in each semester and in
each section. Calculate the Finalmark (average of best two test marks) and update the
corresponding table for all students. Categorize students based on the following criterion: If
Finalmark = 81 to 100 then CAT = ‘Outstanding’ If Finalmark = 51 to 80 then CAT = ‘Average’
If Finalmark < 51 then CAT = ‘Weak Create a view of Test3 marks of particular student in all
subjects. Demonstrate the procedure for the above Database.
1/1
ChatGPT

To address your requirements, here's the implementation for each task:

1. Compute the total number of male and female students in each semester and section:

sqlCopy code
SELECT Sem, Gender, COUNT(*) AS TotalStudents
FROM STUDENT
GROUP BY Sem, Gender;

This query calculates the total number of male and female students in each semester and section.

2. Calculate the Finalmark (average of the best two test marks) and update the
corresponding table for all students:

sqlCopy code
UPDATE MARKS
SET Finalmark = (Test1 + Test2 + Test3 - LEAST(Test1, Test2, Test3)) / 2;

This query calculates the Finalmark by averaging the best two test marks for each student and
updates the corresponding table.

3. Categorize students based on Finalmark:

sqlCopy code
UPDATE MARKS
SET CAT = CASE
WHEN Finalmark BETWEEN 81 AND 100 THEN 'Outstanding'
WHEN Finalmark BETWEEN 51 AND 80 THEN 'Average'
ELSE 'Weak'
END;

This query categorizes students based on their Finalmark using the provided criteria.

4. Create a view of Test3 marks of a particular student in all subjects:

sqlCopy code
CREATE VIEW Student_Test3 AS
SELECT RegNo, Subcode, Test3
FROM MARKS;

This view retrieves the Test3 marks of a particular student in all subjects.

5. Demonstrate a procedure for the above database:

sqlCopy code
CREATE PROCEDURE CalculateFinalmarkAndUpdate()
AS
BEGIN
UPDATE MARKS
SET Finalmark = (Test1 + Test2 + Test3 - LEAST(Test1, Test2, Test3)) / 2;

UPDATE MARKS
SET CAT = CASE
WHEN Finalmark BETWEEN 81 AND 100 THEN 'Outstanding'
WHEN Finalmark BETWEEN 51 AND 80 THEN 'Average'
ELSE 'Weak'
END;
END;

This procedure performs the calculations for Finalmark and updates the table accordingly.

Note: The above examples assume that you have the necessary tables and data in your College
Database. Make sure to adjust the table and column names based on your database structure and
handle the data accordingly.

1/1

Free Research Preview. ChatGPT may produce inaccurate information about people, places, or
facts. ChatGPT May 24 Version

You might also like