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

Write SQL Queries

This document contains a series of SQL queries and relational algebra expressions for various database operations involving multiple tables such as account, branch, customer, loan, employee, and weather. The queries cover tasks like retrieving customer names with loans, finding employees based on company affiliation and pay rates, and filtering weather data based on temperature and conditions. Additionally, it includes relational algebra expressions to find suppliers of specific parts and tuple relational calculus for employee-related queries.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Write SQL Queries

This document contains a series of SQL queries and relational algebra expressions for various database operations involving multiple tables such as account, branch, customer, loan, employee, and weather. The queries cover tasks like retrieving customer names with loans, finding employees based on company affiliation and pay rates, and filtering weather data based on temperature and conditions. Additionally, it includes relational algebra expressions to find suppliers of specific parts and tuple relational calculus for employee-related queries.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Write SQL Queries for the following set of tables:

account(account_number, branch_name, balance)


branch (branch_name, branch_city, assets)
customer (customer_name customer_street, customer_city)
loan (loan_number, branch_name, amount)
depositor((customer_name, account_number)
borrower(customer_name, loan_number)
a. For all customers who have a loan from the bank, find their names
and loan numbers with the attribute loan_number replaced by
loan_id.
b. Find the names of all customers whose street address includes the
substring ‘Main’.
c. List loan data, ordered by decreasing amounts, then increasing loan
numbers.

SQL Queries:
a. For all customers who have a loan from the bank, find their names and loan numbers with the
attribute loan_number replaced by loan_id.
SELECT customer_name, loan_number AS loan_id
FROM borrower;
Explanation:
This query selects customer_name and renames loan_number to loan_id from the borrower table, which
contains all customers with loans.

b. Find the names of all customers whose street address includes the substring ‘Main’.
SELECT customer_name
FROM customer
WHERE customer_street LIKE '%Main%';
Explanation:
The LIKE operator with % wildcards checks if customer_street contains the substring "Main" anywhere in the
string.

c. List loan data, ordered by decreasing amounts, then increasing loan numbers.
SELECT *
FROM loan
ORDER BY amount DESC, loan_number ASC;
Explanation:
 ORDER BY amount DESC sorts loans by amount from highest to lowest.
 loan_number ASC sorts ties in amount by loan_number from smallest to largest (ascending is optional
but explicit).

B) Write SQL Queries for the following set of tables:


EMPLOYEE (FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS, SEX,
SALARY, #SUPERSSN, #DNO),
DEPARTMENT (DNAME, DNUMBER, #MGRSSN, MGRSTARTDATE),
DEPT_LOCATIONS (#DNUMBER, DLOCATION),
PROJECT (PNAME, PNUMBER, PLOCATION, #DNUM),
WORKS_ON (#ESSN, #PNO, HOURS),
DEPENDENT (#ESSN, DEPENDENT_NAME, SEX, BDATE,
RELATIONSHIP)
a. Retrieve the name and address of all employees who work for the
‘Research’ department
b. Retrieve the birthdate and address of the employee(s) whose name
is ‘Raj V Naik’
c. Retrieve all the attributes of an EMPLOYEE and the attributes of
the DEPARTMENT he or she works in for every employee of the
‘Research’ department
Below are example SQL queries that satisfy the requirements. (Note that some SQL dialects do not allow
column names starting with “#”. In practice, you might need to escape these names (for example, using double
quotes or square brackets) or rename them.)

a. Retrieve the name and address of all employees who work for the ‘Research’ department
Assuming that the foreign key in EMPLOYEE referencing the department is named #DNO and matches
DNUMBER in DEPARTMENT, you can write the query as follows:
SELECT e.FNAME, e.MINIT, e.LNAME, e.ADDRESS
FROM EMPLOYEE e
JOIN DEPARTMENT d ON e.#DNO = d.DNUMBER
WHERE d.DNAME = 'Research';
Alternatively, using the older implicit join syntax:
SELECT e.FNAME, e.MINIT, e.LNAME, e.ADDRESS
FROM EMPLOYEE e, DEPARTMENT d
WHERE e.#DNO = d.DNUMBER
AND d.DNAME = 'Research';

b. Retrieve the birthdate and address of the employee(s) whose name is ‘Raj V Naik’
Assuming that the employee's first name is stored in FNAME, middle initial in MINIT, and last name in
LNAME, you can use:
SELECT BDATE, ADDRESS
FROM EMPLOYEE
WHERE FNAME = 'Raj'
AND MINIT = 'V'
AND LNAME = 'Naik';
Note: If the employee’s full name is stored as a single field in another design, you would adjust the WHERE
clause accordingly.

c. Retrieve all the attributes of an EMPLOYEE and the attributes of the DEPARTMENT he or she
works in for every employee of the ‘Research’ department
You can join the two tables to get all the information. Using the explicit JOIN syntax:
SELECT *
FROM EMPLOYEE e
JOIN DEPARTMENT d ON e.#DNO = d.DNUMBER
WHERE d.DNAME = 'Research';
Or, if you prefer listing out all columns (which is a good practice in production to avoid ambiguity), you might
write:
SELECT e.FNAME, e.MINIT, e.LNAME, e.SSN, e.BDATE, e.ADDRESS, e.SEX, e.SALARY,
e.#SUPERSSN, e.#DNO,
d.DNAME, d.DNUMBER, d.#MGRSSN, d.MGRSTARTDATE
FROM EMPLOYEE e
JOIN DEPARTMENT d ON e.#DNO = d.DNUMBER
WHERE d.DNAME = 'Research';

These queries assume that the relationships between the tables are as described. Adjust column names or use
proper escaping as required by your SQL environment.
Consider the following relational schema.
Suppliers(sid, sname, address)
Parts(pid, pname, address)
Catalog(sid, pid, cost)

(i) Write relational algebra query to find the names of suppliers who supply
some red part
(ii) Write relational algebra query to find the sid of suppliers who supply
some red or green parts

We are given the following schema:


 Suppliers(sid, sname, address)
 Parts(pid, pname, address)
(Note: In many standard texts the Parts relation has an attribute “color” instead of “address”. Here,
since the question asks about “red” and “green” parts, we assume that the attribute pname actually
represents the part’s color or that pname is used to denote the color of the part. In any event, we will
use the condition pname=′red′pname = 'red' or pname=′green′pname = 'green' as required.)
 Catalog(sid, pid, cost)
Below are one acceptable set of relational algebra queries for the two parts.

(i) Find the names of suppliers who supply some red part
We need to:
1. Identify parts that are red.
2. Find the catalog entries for those red parts.
3. Get the corresponding supplier information, and finally,
4. Project the supplier names.
One correct relational algebra expression is:
πsname(Suppliers ⋈Suppliers.sid=Catalog.sid(Catalog ⋈Catalog.pid=Parts.pid σpname=′red′(Parts)))\
pi_{sname}\Bigl( Suppliers \ \bowtie_{Suppliers.sid = Catalog.sid} \Bigl( Catalog \ \bowtie_{Catalog.pid =
Parts.pid} \ \sigma_{pname = 'red'}(Parts) \Bigr) \Bigr)
Explanation:
 σpname=′red′(Parts)\sigma_{pname = 'red'}(Parts) selects all parts that are red.
 Joining with Catalog on pidpid gives the catalog entries for red parts.
 Joining with Suppliers on sidsid gives the supplier details.
 Finally, πsname\pi_{sname} projects only the supplier names.

(ii) Find the sid of suppliers who supply some red or green parts
Here, we want the supplier ids (sidsid) for those who supply either a red part or a green part. We can do this in
one of two equivalent ways. One way is to select the parts that are either red or green and then join with the
Catalog. Another way is to compute the union of the two separate cases. Both are acceptable.
Method 1 (Using a single selection):
πsid(Catalog ⋈Catalog.pid=Parts.pid σpname=′red′∨pname=′green′(Parts))\pi_{sid}\Bigl( Catalog \ \
bowtie_{Catalog.pid = Parts.pid} \ \sigma_{pname = 'red' \lor pname = 'green'}(Parts) \Bigr)
Explanation:
 σpname=′red′∨pname=′green′(Parts)\sigma_{pname = 'red' \lor pname = 'green'}(Parts) selects parts
that are either red or green.
 The join with Catalog finds the supplier–part pairs for those parts.
 πsid\pi_{sid} projects the supplier ids.
Method 2 (Using union):
πsid((σpname=′red′(Parts) ⋈Parts.pid=Catalog.pid Catalog) ∪ (σpname=′green′(Parts) ⋈Parts.pid=Catalog.pid
Catalog))\pi_{sid}\Bigl((\sigma_{pname = 'red'}(Parts) \ \bowtie_{Parts.pid = Catalog.pid} \ Catalog) \ \cup \
(\sigma_{pname = 'green'}(Parts) \ \bowtie_{Parts.pid = Catalog.pid} \ Catalog)\Bigr)
Explanation:
 The left part selects catalog entries for red parts.
 The right part selects catalog entries for green parts.
 Their union gives all catalog entries for red or green parts.
 Finally, projecting sidsid yields the desired result.

Any of the above formulations is a correct relational algebra expression for the given queries.
Consider the following employee database. Give expression in tuple rela-
tional calculus for each of the following queries.

employee(employee_name,street,city)
works(employee_name,company_name,salary)
company(company_name,city)
manages(employee_name,manager_name)

(i)Find the names of all employees who work for First Bank Corporation.

(ii)Find the names and cities of residence of all employees who work for
First Bank Corporation

(iii)Find all employees who live in the same city as that in which the com-
pany for which the work is located.

Below are one acceptable set of answers expressed in tuple relational calculus. In each case we use tuple
variables (for example, e for an employee tuple, w for a works tuple, etc.) and write the query as a set
comprehension. (You may use slightly different but equivalent notations.)

(i) Find the names of all employees who work for First Bank Corporation
We want to collect the employee names such that there is a tuple in works showing that the employee works
for “First Bank Corporation”. One correct expression is:
{ e.employee_name∣employee(e)∧∃w (
works(w)∧w.employee_name=e.employee_name∧w.company_name="First Bank Corporation") }\{\, e.\
text{employee\_name} \mid \text{employee}(e) \land \exists w\, (\, \text{works}(w) \land w.\text{employee\
_name} = e.\text{employee\_name} \land w.\text{company\_name} = \text{"First Bank Corporation"} ) \,\}

(ii) Find the names and cities of residence of all employees who work for First Bank Corporation
Now we want both the employee’s name and his/her city. We proceed similarly by joining the employee and
works relations:
{ (e.employee_name, e.city)∣employee(e)∧∃w (
works(w)∧w.employee_name=e.employee_name∧w.company_name="First Bank Corporation") }\{\, (e.\
text{employee\_name},\, e.\text{city}) \mid \text{employee}(e) \land \exists w\, (\, \text{works}(w) \land w.\
text{employee\_name} = e.\text{employee\_name} \land w.\text{company\_name} = \text{"First Bank
Corporation"} ) \,\}

(iii) Find all employees who live in the same city as that in which the company for which the work is
located
This query requires that for an employee e who works for some company c (via a tuple w in works), the
employee’s city (from employee) equals the city of the company (from company). One correct expression is:
{ e∣employee(e)∧∃w∃c (
works(w)∧company(c)∧w.employee_name=e.employee_name∧w.company_name=c.company_name∧e.city
=c.city) }\{\, e \mid \text{employee}(e) \land \exists w \exists c\, (\, \text{works}(w) \land \text{company}(c) \
land w.\text{employee\_name} = e.\text{employee\_name} \land w.\text{company\_name} = c.\text{company\
_name} \land e.\text{city} = c.\text{city} ) \,\}

Explanation
1. (i) and (ii):
o We start with a tuple from employee (variable e).
o We require the existence of a corresponding tuple w in works that relates the employee to the
company “First Bank Corporation.”
o In (i) we project just the employee name; in (ii) we project both the employee name and the city
from the employee tuple.
2. (iii):
o Again, we begin with a tuple e from employee.
o We then require that there exists a tuple w in works (linking an employee with a company) and
a tuple c in company such that:
 w matches e (i.e. the employee worked for the company),
 w’s company name matches c’s company name, and
 the city where e lives is the same as the city where the company c is located.
Any expressions equivalent to the above answers are correct.
Consider the following schema and solve following queries using SQL.

employee (emp_no, name, skill ,pay_rate)


position (posting_no, skill)
duty-allocation (posting_no, emp_no, day, shift)

(i) Get duty allocation details for emp_no 123461 for the month of april
1986.
(ii) Get employees whose rate of pay is more than or equal to the rate of pay
of employee ‘XYZ’.
(iii) Get the names and pay rates of employees with emp_no less than

123460 whose rate of pay is more than the rate of payoff atleast one em-
ployee with emp_no greater than or equal to 123460.

Below are one acceptable set of SQL queries for the given problems. In the examples below, it is assumed that
the attribute day in the duty_allocation table is of a date type. (Also, note that table names containing hyphens
—such as duty-allocation—are typically not allowed in SQL unless quoted; here we assume the table is
named duty_allocation.)

(i) Get duty allocation details for emp_no 123461 for the month of April 1986
Assuming that day is of date type, one way is to use the BETWEEN operator:
SELECT *
FROM duty_allocation
WHERE emp_no = 123461
AND day BETWEEN '1986-04-01' AND '1986-04-30';
Alternatively, if your SQL dialect supports date functions, you could write:
SELECT *
FROM duty_allocation
WHERE emp_no = 123461
AND EXTRACT(YEAR FROM day) = 1986
AND EXTRACT(MONTH FROM day) = 4;

(ii) Get employees whose rate of pay is more than or equal to the rate of pay of employee ‘XYZ’
This query uses a subquery to retrieve the pay rate for employee 'XYZ':
SELECT *
FROM employee
WHERE pay_rate >= (
SELECT pay_rate
FROM employee
WHERE name = 'XYZ'
);
Note: This assumes that the name 'XYZ' is unique in the employee table. If not, you may need to further
qualify the employee (for example, by emp_no) or handle multiple rows appropriately.

(iii) Get the names and pay rates of employees with emp_no less than 123460 whose rate of pay is more
than the rate of pay of at least one employee with emp_no greater than or equal to 123460
This query uses an EXISTS subquery to ensure that for each employee ee with emp_no < 123460, there exists
at least one other employee e2e2 (with emp_no ≥ 123460) such that ee’s pay rate is greater than e2e2’s pay
rate:
SELECT e.name, e.pay_rate
FROM employee e
WHERE e.emp_no < 123460
AND EXISTS (
SELECT 1
FROM employee e2
WHERE e2.emp_no >= 123460
AND e.pay_rate > e2.pay_rate
);

Any of the above SQL queries correctly addresses the corresponding parts of the problem.

Consider the following relational schema.

Weather (city, temperature, humidity, condition)


Location (city, country)
Write the following queries in SQL:
(i) Find all the tuples having temperature greater than that of Paris.
(ii) Find the names of those cities with temperature and condition whose
condition is neither Sunny nor Cloudy but temperature must be greater than
70.
(iii) Find all the cities with temperature, condition and humidity, whose hu-
midity is in the range of 63 to 79.

Below are the SQL queries for the given problems based on the schema:
 Weather(city, temperature, humidity, condition)
 Location(city, country)

(i) Find all the tuples having temperature greater than that of Paris
Assuming that the temperature for Paris is stored in the Weather table, you can use a subquery to compare
each tuple's temperature with that of Paris:
SELECT *
FROM Weather
WHERE temperature > (
SELECT temperature
FROM Weather
WHERE city = 'Paris'
);

(ii) Find the names of those cities with temperature and condition whose condition is neither Sunny nor
Cloudy but temperature must be greater than 70
Here, we need to select the city, temperature, and condition from Weather where the condition is not 'Sunny'
or 'Cloudy' and the temperature exceeds 70:
SELECT city, temperature, condition
FROM Weather
WHERE condition NOT IN ('Sunny', 'Cloudy')
AND temperature > 70;

(iii) Find all the cities with temperature, condition and humidity, whose humidity is in the range of 63 to
79
This query selects the desired columns from Weather and uses the BETWEEN operator to restrict humidity to
the range 63 to 79 (inclusive):
SELECT city, temperature, condition, humidity
FROM Weather
WHERE humidity BETWEEN 63 AND 79;

These queries should work correctly given the schema provided.

Here are the SQL statements to perform the requested updates:


(1) Insert a new student <Johnson, 25, 1, 'Math'> into the database:
INSERT INTO Student (name, s_no, class, major)
VALUES ('Johnson', 25, 1, 'Math');

(2) Change the credit_hours of the course "Data Science" to 4:


UPDATE Course
SET credit_hours = 4
WHERE c_name = 'Data Science';

(3) Delete the record for the student whose name is 'Smith' and whose student number is 17:
DELETE FROM Student
WHERE name = 'Smith' AND s_no = 17;

These SQL statements correctly perform the insert, update, and delete operations as required.

B) Write the SQL Queries for the following. CO3/3 6


DR. BABASAHEB AMBEDKAR TECHNOLOGICAL UNIVERSITY, LONERE
Regular & Supplementary Winter Examination-2023
Course: B. Tech
Branch : Computer Engineering / Computer Science and Engineering
Semester :V
Subject Code & Name: BTCOC501 Database Systems

Date:01-01-24

a) Creating, Using, showing and deleting databases.


b) To create BOOK table with Bkid, Title, Author, branch, cost and date of
publishing. (Assume proper data type for each column).
c) Write query to insert 2 valid rows of values into the BOOK table.
d) Write query to increase the length of Title and Author.
e) Write query to list books with cost less than 100.
f) Write query to list all books with title “RDBMS”.
C) Consider the following schema:
Suppliers (sid : integer, sname : string, address : string)
Parts (pid : integer, pname : string, color : string)
Catalog (sid : integer, pid : integer, cost : real)
Write query for the following
a) To create above tables
b) Find the name of suppliers who supply some red parts
c) Find the sids of suppliers who supply some red or green parts
d) Find the sids of suppliers who supply some red part or are at 221 packer
Ave
e) Find the sids of suppliers who supply some red part and some green part

Here are the SQL queries for each of the given tasks:

B) General SQL Queries


(a) Creating, Using, Showing, and Deleting Databases
-- Creating a new database
CREATE DATABASE LibraryDB;

-- Using the created database


USE LibraryDB;

-- Showing all databases


SHOW DATABASES;

-- Dropping a database (deleting)


DROP DATABASE LibraryDB;

(b) Creating the BOOK table


CREATE TABLE BOOK (
Bkid INT PRIMARY KEY,
Title VARCHAR(255),
Author VARCHAR(255),
Branch VARCHAR(100),
Cost DECIMAL(10,2),
Date_of_Publishing DATE
);

(c) Inserting two valid rows into the BOOK table


INSERT INTO BOOK (Bkid, Title, Author, Branch, Cost, Date_of_Publishing)
VALUES
(1, 'Database Management Systems', 'Raghu Ramakrishnan', 'CSE', 450.00, '2022-06-15'),
(2, 'RDBMS', 'Elmasri & Navathe', 'CSE', 550.00, '2021-09-10');

(d) Altering table to increase the length of Title and Author


ALTER TABLE BOOK
MODIFY Title VARCHAR(500),
MODIFY Author VARCHAR(500);

(e) Listing books with cost less than 100


SELECT * FROM BOOK WHERE Cost < 100;

(f) Listing all books with Title = "RDBMS"


SELECT * FROM BOOK WHERE Title = 'RDBMS';

C) Queries on Suppliers, Parts, and Catalog Schema


(a) Creating Suppliers, Parts, and Catalog tables
CREATE TABLE Suppliers (
sid INT PRIMARY KEY,
sname VARCHAR(255),
address VARCHAR(255)
);

CREATE TABLE Parts (


pid INT PRIMARY KEY,
pname VARCHAR(255),
color VARCHAR(50)
);

CREATE TABLE Catalog (


sid INT,
pid INT,
cost DECIMAL(10,2),
FOREIGN KEY (sid) REFERENCES Suppliers(sid),
FOREIGN KEY (pid) REFERENCES Parts(pid)
);

(b) Find the names of suppliers who supply some red part
SELECT DISTINCT S.sname
FROM Suppliers S
JOIN Catalog C ON S.sid = C.sid
JOIN Parts P ON C.pid = P.pid
WHERE P.color = 'red';

(c) Find the sids of suppliers who supply some red or green parts
SELECT DISTINCT C.sid
FROM Catalog C
JOIN Parts P ON C.pid = P.pid
WHERE P.color IN ('red', 'green');

(d) Find the sids of suppliers who supply some red part OR are located at "221 Packer Ave"
SELECT DISTINCT S.sid
FROM Suppliers S
LEFT JOIN Catalog C ON S.sid = C.sid
LEFT JOIN Parts P ON C.pid = P.pid
WHERE P.color = 'red' OR S.address = '221 Packer Ave';
(e) Find the sids of suppliers who supply some red part AND some green part
SELECT DISTINCT C1.sid
FROM Catalog C1
JOIN Parts P1 ON C1.pid = P1.pid
WHERE P1.color = 'red'
AND EXISTS (
SELECT 1 FROM Catalog C2
JOIN Parts P2 ON C2.pid = P2.pid
WHERE C1.sid = C2.sid AND P2.color = 'green'
);

These SQL queries should correctly perform the required database operations. 🚀 Let me know if you
need any modifications!

B) Write Relational Algebra Queries for following.


Note: Consider Relational Table - Account( Acno, AcName, Br_name,
Amount).
a) To display all tuples from Accounts table.
b) To display Acno, AcName from accounts.
c) To display the tuples for the account whose amount>25000 and
Br_name=”Dharashiv)
d) To display Acno, AcName, Amount From Account where the
amount>50000

Here are the Relational Algebra Queries for the given tasks based on the Account table schema:
Schema:
 Account (Acno, AcName, Br_name, Amount)

(a) To display all tuples from the Account table


📌 Relational Algebra Expression:
πAcno,AcName,Brname,Amount(Account)\pi_{Acno, AcName, Br_name, Amount} (Account)
Alternatively, using the selection operator:
σtrue(Account)\sigma_{true} (Account)
(This retrieves all tuples as no condition is applied.)

(b) To display Acno, AcName from the Account table


📌 Relational Algebra Expression:
πAcno,AcName(Account)\pi_{Acno, AcName} (Account)
(Projection is used to retrieve only the required attributes.)

(c) To display the tuples for the account where Amount > 25000 and Br_name = "Dharashiv"
📌 Relational Algebra Expression:
σAmount>25000∧Br_name=′Dharashiv′(Account)\sigma_{Amount > 25000 \land Br\_name =
'Dharashiv'} (Account)
(Selection is used to filter based on the given conditions.)

(d) To display Acno, AcName, Amount from Account where Amount > 50000
📌 Relational Algebra Expression:
πAcno,AcName,Amount(σAmount>50000(Account))\pi_{Acno, AcName, Amount} (\sigma_{Amount
> 50000} (Account))
(First, selection filters records with Amount > 50000, then projection retrieves only the required
attributes.)

These relational algebra expressions correctly retrieve the required information from the Account table.
🚀 Let me know if you need further clarifications!

You might also like