Theory Coming Soon
Previous Job Question with ANSWER on SQL
Given Tables:
EMPLOYEES (ID, Name, DeptID)
DEPARTMENTS (DeptID, DeptName)
Objective:
To get the list of employee names who work in the IT department.
Logical Steps:
- Identify the DeptID of the department where DeptName is IT.
- Match this DeptID with the DeptID in the EMPLOYEES table.
- Select the Name of employees who belong to the IT department.
Pseudo-SQL Logic:
SELECT E.Name FROM EMPLOYEES E JOIN DEPARTMENTS D ON E.DeptID = D.DeptID WHERE D.DeptName = 'IT';
(i) Write an SQL query to display only StudentID, Name, and Marks for students scoring more than 80 marks.
(ii) Write an SQL query to count how many students scored more than 80 marks in each Department.CB, O(it-23), 2026
(i) SQL Query to Display StudentID, Name, and Marks for Students Scoring More Than 80 Marks
SELECT StudentID, Name, Marks
FROM STUDENTS
WHERE Marks > 80;
Explanation:
- SELECT chooses the required columns.
- FROM STUDENTS specifies the table name.
- WHERE Marks > 80 filters students who scored more than 80 marks.
(ii) SQL Query to Count Students Scoring More Than 80 Marks in Each Department
SELECT Department, COUNT(*) AS Total_Students
FROM STUDENTS
WHERE Marks > 80
GROUP BY Department;
Explanation:
- COUNT(*) counts the number of students.
- GROUP BY Department groups records department-wise.
- WHERE Marks > 80 considers only students scoring above 80.
(i) 80-এর বেশি Marks পাওয়া Student-দের StudentID, Name এবং Marks প্রদর্শনের SQL Query
SELECT StudentID, Name, Marks
FROM STUDENTS
WHERE Marks > 80;
ব্যাখ্যা:
- SELECT প্রয়োজনীয় column নির্বাচন করে।
- FROM STUDENTS table-এর নাম নির্দেশ করে।
- WHERE Marks > 80 80-এর বেশি marks পাওয়া student filter করে।
(ii) প্রতিটি Department-এ 80-এর বেশি Marks পাওয়া Student সংখ্যা গণনার SQL Query
SELECT Department, COUNT(*) AS Total_Students
FROM STUDENTS
WHERE Marks > 80
GROUP BY Department;
ব্যাখ্যা:
- COUNT(*) student সংখ্যা গণনা করে।
- GROUP BY Department department অনুযায়ী group তৈরি করে।
- WHERE Marks > 80 শুধুমাত্র 80-এর বেশি marks পাওয়া student বিবেচনা করে।
(a) Explain what ON DELETE CASCADE means in simple English.
(b) If you delete one Manager from the database, what will automatically happen to all Employees under that manager?
(c) Explain why this is very dangerous in a real banking systers. What is the best practice and how does it fix this danger?CB, SO(it-23), 2026
(a) Meaning of ON DELETE CASCADE
ON DELETE CASCADE means that if a record in the parent table is deleted, all related records in the child table will also be automatically deleted.
It maintains referential integrity automatically.
(b) Effect of deleting a Manager
If a Manager is deleted from the Managers table, then all Employees linked to that Manager via Foreign Key will also be automatically deleted from the Employees table.
(c) Why it is dangerous in banking system & best practice
Danger:
In a banking system, deleting one Manager accidentally could delete all related employee records or dependent data.
This can cause massive data loss, financial inconsistency, and system failure.
Example risk:
One wrong delete operation → many employee records permanently removed.
Best Practice:
Instead of ON DELETE CASCADE, use:
- ON DELETE RESTRICT or NO ACTION
- Soft delete (use a status field like “inactive” instead of deleting data)
How it fixes the problem:
– Prevents accidental mass deletion
– Keeps historical data safe
– Allows controlled data management and auditing
Database Concept: ON DELETE CASCADE
(a) ON DELETE CASCADE এর অর্থ
ON DELETE CASCADE মানে হলো parent table-এর কোনো record delete করলে তার সাথে সম্পর্কিত child table-এর সব record স্বয়ংক্রিয়ভাবে delete হয়ে যায়।
এটি referential integrity বজায় রাখে।
(b) Manager delete করলে কী হবে
যদি Managers table থেকে কোনো Manager delete করা হয়, তাহলে Foreign Key দিয়ে যুক্ত Employees table-এর সেই Manager-এর সব employee record স্বয়ংক্রিয়ভাবে delete হয়ে যাবে।
(c) Banking system-এ কেন বিপজ্জনক & best practice
বিপদ:
Banking system-এ ভুল করে একজন Manager delete করলে তার সাথে যুক্ত সব employee data delete হয়ে যেতে পারে।
এতে massive data loss, financial inconsistency এবং system failure হতে পারে।
Example risk:
এক ভুল delete operation → অনেক employee record permanently delete।
Best Practice:
ON DELETE CASCADE এর পরিবর্তে ব্যবহার করা উচিত:
- ON DELETE RESTRICT বা NO ACTION
- Soft delete (status field যেমন “inactive” ব্যবহার করা)
কিভাবে এটি সমস্যা সমাধান করে:
– ভুল করে mass deletion আটকায়
– পুরনো data নিরাপদ রাখে
– controlled data management এবং auditing সম্ভব করে
- Stage: Executes before GROUP BY and aggregate functions.
- Scope: Filters individual rows based on column values.
- Aggregate functions: Cannot use aggregate functions like COUNT(), SUM(), or AVG().
- Performance: Reduces the number of rows early, making aggregation faster.
SELECT dept, AVG(salary) FROM employees WHERE dept = 'Sales' GROUP BY dept;Here, WHERE filters rows where dept is ‘Sales’ first, then AVG is calculated only on those rows.2. HAVING ClauseThe HAVING clause filters groups of rows after grouping and aggregation have been completed. It operates on the result of aggregate functions.- Stage: Executes after GROUP BY and aggregate functions.
- Scope: Filters groups based on aggregate results.
- Aggregate functions: Can and typically does use aggregate functions.
- Performance: Works on already aggregated data, so it cannot reduce early row processing.
SELECT dept, AVG(salary) FROM employees GROUP BY dept HAVING AVG(salary) > 50000;Here, GROUP BY creates department groups, AVG calculates the average, and HAVING filters out groups where the average is too low.3. Execution Order in SQLSQL processes clauses in this order, not in the order they appear in the query:| Order | Clause | Action |
|---|---|---|
| 1 | FROM | Identify the source table |
| 2 | WHERE | Filter individual rows |
| 3 | GROUP BY | Group the filtered rows |
| 4 | Aggregate | Apply SUM, COUNT, AVG, etc. |
| 5 | HAVING | Filter grouped results |
| 6 | SELECT | Choose columns to display |
| 7 | ORDER BY | Sort the final output |
SELECT region, SUM(sales) AS total FROM orders WHERE region = 'Sales' GROUP BY region HAVING SUM(sales) > 100000;- WHERE region = ‘Sales’: Filters individual rows to only Sales region orders.
- GROUP BY region: Groups the remaining rows by region.
- SUM(sales): Calculates total sales per region.
- HAVING SUM(sales) > 100000: Keeps only regions where the total exceeds 100,000.
- Stage: GROUP BY এবং aggregate functions-এর আগে execute করে।
- Scope: Column values-এর উপর ভিত্তি করে individual rows filter করে।
- Aggregate functions: COUNT(), SUM(), AVG() এর মতো aggregate functions ব্যবহার করা যায় না।
- Performance: Early rows কমায়, aggregation faster করে।
SELECT dept, AVG(salary) FROM employees WHERE dept = 'Sales' GROUP BY dept;এখানে WHERE প্রথমে dept ‘Sales’ হওয়া rows filter করে, তারপর শুধু সেই rows-এর উপর AVG calculate করে।<2. HAVING ClauseHAVING clause groups of rows filter করে grouping এবং aggregation complete হওয়ার পর। এটি aggregate functions-এর result-এর উপর operate করে।<- Stage: GROUP BY এবং aggregate functions-এর পরে execute করে।
- Scope: Aggregate results-এর উপর ভিত্তি করে groups filter করে।
- Aggregate functions: ব্যবহার করতে পারে এবং সাধারণত করে।
- Performance: Already aggregated data-এর উপর কাজ করে, তাই early row processing reduce করতে পারে না।
SELECT dept, AVG(salary) FROM employees GROUP BY dept HAVING AVG(salary) > 50000;এখানে GROUP BY department groups তৈরি করে, AVG average calculate করে, এবং HAVING average কম হওয়া groups filter out করে।3. SQL-এ Execution OrderSQL query-তে যে order-এ clauses লেখা হয় সেই order-এ process করে না, বরং এই order-এ:| Order | Clause | Action |
|---|---|---|
| 1 | FROM | Source table identify করা |
| 2 | WHERE | Individual rows filter করা |
| 3 | GROUP BY | Filtered rows group করা |
| 4 | Aggregate | SUM, COUNT, AVG ইত্যাদি apply করা |
| 5 | HAVING | Grouped results filter করা |
| 6 | SELECT | Display-এর জন্য columns choose করা |
| 7 | ORDER BY | Final output sort করা |
SELECT region, SUM(sales) AS total FROM orders WHERE region = 'Sales' GROUP BY region HAVING SUM(sales) > 100000;- WHERE region = ‘Sales’: শুধু Sales region-এর orders filter করে individual rows থেকে।
- GROUP BY region: বাকি rows-কে region অনুযায়ী group করে।
- SUM(sales): প্রতিটি region-এর total sales calculate করে।
- HAVING SUM(sales) > 100000: শুধু সেই regions রাখে যেখানে total 100,000-এর বেশি।
SELECT d.dept_name, AVG(e.salary) AS average_salary FROM department d JOIN employee e ON d.dept_id = e.dept_id GROUP BY d.dept_name;
Cost: Implementing and maintaining a DBMS can be expensive due to the cost of software licenses, hardware, and skilled personnel needed to manage the system.
Complexity: DBMS systems are complex to design, implement, and manage. They require specialized knowledge, and the complexity can increase with the size and scale of the database.
Scalability: Some DBMSs may face challenges when scaling to handle very large amounts of data or high transaction volumes efficiently, especially with unstructured data.
Dependence on Technology: Organizations become dependent on the specific DBMS technology they use, which can cause problems if the vendor stops support or if migration to another system is needed.
Performance Issues: Under heavy loads or with complex queries, DBMS performance can degrade, leading to slower response times and potential bottlenecks.
Data Integration: Integrating data from multiple, heterogeneous sources into a single DBMS can be difficult and time-consuming, especially when data formats and structures differ.
Security: Although DBMSs provide security features, they can still be vulnerable to unauthorized access, hacking, and data breaches if not properly managed.
Data Loss: In cases of hardware failure, software bugs, or disasters, there is a risk of losing data if proper backup and recovery mechanisms are not in place.
১. ব্যয় (Cost):
DBMS বাস্তবায়ন ও রক্ষণাবেক্ষণ ব্যয়বহুল, কারণ এতে সফটওয়্যার লাইসেন্স, হার্ডওয়্যার এবং দক্ষ জনবলের প্রয়োজন হয় ।
২. জটিলতা (Complexity):
DBMS সিস্টেম ডিজাইন, বাস্তবায়ন ও পরিচালনা করা জটিল। এটি ব্যবহারের জন্য বিশেষ জ্ঞানের প্রয়োজন হয়, এবং ডেটাবেসের আকার ও পরিধি বাড়লে জটিলতাও বৃদ্ধি পায়।
৩. স্কেলযোগ্যতা (Scalability):
অনেক সময় DBMS বড় পরিমাণ ডেটা বা উচ্চ ট্রানজেকশন হ্যান্ডল করতে গিয়ে সমস্যার সম্মুখীন হয়, বিশেষ করে যদি ডেটা আনস্ট্রাকচার্ড হয়।
৪. প্রযুক্তির উপর নির্ভরতা (Dependence on Technology):
একটি প্রতিষ্ঠান নির্দিষ্ট DBMS প্রযুক্তির উপর নির্ভরশীল হয়ে পড়ে। ফলে, যদি সেই ভেন্ডর সাপোর্ট বন্ধ করে দেয় বা অন্য সিস্টেমে স্থানান্তর করতে হয়, তখন সমস্যা দেখা দিতে পারে।
৫. পারফরম্যান্স সমস্যা (Performance Issues):
DBMS-এ ভারী লোড বা জটিল কোয়েরি থাকলে সিস্টেমের পারফরম্যান্স কমে যেতে পারে, যার ফলে রেসপন্স টাইম বেড়ে যায় এবং বটলনেক তৈরি হয়।
৬. ডেটা ইন্টিগ্রেশন (Data Integration): বিভিন্ন উৎস থেকে ডেটা একত্র করা কঠিন ও সময়সাপেক্ষ, বিশেষ করে যখন ডেটার ফরম্যাট ও গঠন এক হয়না।
৭. নিরাপত্তা (Security):
DBMS-এ নিরাপত্তা ব্যবস্থা থাকলেও, সঠিকভাবে পরিচালনা না করলে এটি অননুমোদিত প্রবেশ, হ্যাকিং বা ডেটা চুরির ঝুঁকিতে থাকে।
৮. ডেটা হারানো (Data Loss):
হার্ডওয়্যার ত্রুটি, সফটওয়্যার বাগ বা প্রাকৃতিক দুর্যোগের কারণে ডেটা হারানোর আশঙ্কা থাকে যদি সঠিক ব্যাকআপ ও রিকভারি ব্যবস্থা না থাকে।
The features of SQL (RDBMS), NoSQL, and NewSQL,

Given the following two tables (Students and Marks) in a database, write down the output of the given SQL queries and write down the SQL queries for the outputs:
ii) SELECT StudentName From Students S JOIN Marks M ON S.Studentld = M.StudentId GROUP BY S.Studentld, S.StudentName HAVING SUM (Mark)>=200;
iii)List all the students name and number of subjects they have completed.
iv)List all the students who have not completed any subject.
v) List all the subject names. [Ministry of Food, Network/Website Manager(ICT),2024]
-- i) Query:
SELECT COUNT(*)
FROM Students S
LEFT JOIN Marks M
ON S.StudentId = M.StudentId;
-- Output:
-- 10
--
-- Explanation:
-- Student 1 -> 3 rows
-- Student 2 -> 3 rows
-- Student 3 -> 3 rows
-- Student 4 -> 1 row (no marks, but LEFT JOIN keeps it)
-- Total = 3 + 3 + 3 + 1 = 10
-- ii) Query:
SELECT StudentName
FROM Students S
JOIN Marks M
ON S.StudentId = M.StudentId
GROUP BY S.StudentId, S.StudentName
HAVING SUM(Mark) >= 200;
-- Output:
-- Mr. A
-- Mr. B
--
-- Explanation:
-- Mr. A = 70 + 50 + 80 = 200
-- Mr. B = 90 + 60 + 70 = 220
-- Mr. C = 30 + 70 + 60 = 160
-- iii) List all the students name and number of subjects they have completed
SELECT S.StudentName, COUNT(M.Subject) AS NumberOfSubjects
FROM Students S
LEFT JOIN Marks M
ON S.StudentId = M.StudentId
GROUP BY S.StudentId, S.StudentName;
-- Output:
-- Mr. A 3
-- Mr. B 3
-- Mr. C 3
-- Mr. D 0
-- iv) List all the students who have not completed any subject
SELECT S.StudentName
FROM Students S
LEFT JOIN Marks M
ON S.StudentId = M.StudentId
WHERE M.StudentId IS NULL;
-- Output:
-- Mr. D
-- v) List all the subject names
SELECT DISTINCT Subject
FROM Marks;
-- Output:
-- Math
-- Bengali
-- Physics
See the following Table:
Employees(EMP_ID, EMP_Name, Manager_ID, Dept_ID);
Departments(Dept_ID, Salary, Dept_Name, Emp_ID); Submarine Cables ,AM (Engineering), 2024
SELECT e.EMP_Name AS Employee,
m.EMP_Name AS Manager
FROM Employees e
LEFT JOIN Employees m
ON e.Manager_ID = m.EMP_ID;
SELECT e.EMP_Name, d.Dept_Name, d.Salary
FROM Employees e
JOIN Departments d
ON e.EMP_ID = d.Emp_ID
ORDER BY d.Dept_ID, d.Salary DESC;
Movies (mid, title, year)
People (pid, name)
Genres (gid, genre)
HasRole (pid, mid, role)
Has Genre (gid, mid)
SELECT COUNT(*)
FROM Movies, Genres, HasGenre
WHERE Movies.mid = HasGenre.mid
AND HasGenre.gid = Genres.gid
AND Genres.genre = “romantic comedy”;
We need to retrieve sid from table R and uid from table Q, where the two tables are related through the common column tid.
SELECT R.sid, Q.uid FROM R JOIN Q ON R.tid = Q.tid;
Explanation:
R.sid: Selects thesidfrom tableR.Q.uid: Selects theuidfrom tableQ.- The
JOINconnectsRandQthrough theirtidcolumns, which establish the relationship between the two tables.
Here, we need to select A from table S and C from table U, connecting them through the relations R and Q.
SELECT S.A, U.C FROM S JOIN R ON S.sid = R.sid JOIN Q ON R.tid = Q.tid JOIN U ON Q.uid = U.uid;
Explanation:
S.A: Selects theA-valuefrom theStable (which corresponds tosid).- The first
JOINconnects tableSwith tableRthroughsid. - The second
JOINconnectsRandQontid. - Finally,
Qis connected toUviauid, allowing us to selectCfromU.
Sales(sales_id, salesman, region, sale_amount, sale_date) ,
Write an SQL query to display the region, average sale amount, and total number of sales for each region where: The average sale amount exceeds BDT 50,000 and the total number of sales in that region is at least 5.CB, SO(it), 2025
SQL Query
The following query displays the region, average sale amount, and total number of sales for each region where the average sale amount is greater than BDT 50,000 and the total number of sales is at least 3.
SELECT region,
AVG(sale_amount) AS avg_sale_amount,
COUNT(*) AS total_sales
FROM Sales
GROUP BY region
HAVING AVG(sale_amount) > 50000
AND COUNT(*) >= 3;
SQL Query
নিচের query টি প্রতিটি region অনুযায়ী average sale amount এবং total sales সংখ্যা দেখায়, যেখানে average sale amount BDT 50,000 এর বেশি এবং ঐ region এ মোট sales কমপক্ষে 3টি।
SELECT region,
AVG(sale_amount) AS avg_sale_amount,
COUNT(*) AS total_sales
FROM Sales
GROUP BY region
HAVING AVG(sale_amount) > 50000
AND COUNT(*) >= 3;
CB, SO(IT), 2024Inner Join:
An Inner Join returns only the rows that have matching values in both tables.
SELECT Customers.ID, Customers.FirstName, Orders.OrderID, Orders.Amount FROM Customers INNER JOIN Orders ON Customers.ID = Orders.CustomerID;
Result Set:
| ID | First Name | Order ID | Amount |
|---|---|---|---|
| 3 | Belal | 2 | 500 |
| 5 | Helal | 4 | 800 |
Left Join (or Left Outer Join):
A Left Join returns all rows from the left table (Customers), and the matched rows from the right table (Orders). If there is no match, the result is NULL on the right side.
SELECT Customers.ID, Customers.FirstName, Orders.OrderID, Orders.Amount FROM Customers LEFT JOIN Orders ON Customers.ID = Orders.CustomerID;
Result Set:
| ID | First Name | Order ID | Amount |
|---|---|---|---|
| 1 | Rahim | NULL | NULL |
| 2 | Karim | NULL | NULL |
| 3 | Belal | 2 | 500 |
| 4 | Rony | NULL | NULL |
| 5 | Helal | 4 | 800 |
Right Join (or Right Outer Join):
A Right Join returns all rows from the right table (Orders), and the matched rows from the left table (Customers). If there is no match, the result is NULL on the left side.
SELECT Customers.ID, Customers.FirstName, Orders.OrderID, Orders.Amount FROM Customers RIGHT JOIN Orders ON Customers.ID = Orders.CustomerID;
Result Set:
| ID | First Name | Order ID | Amount |
|---|---|---|---|
| NULL | NULL | 1 | 200 |
| 3 | Belal | 2 | 500 |
| NULL | NULL | 3 | 300 |
| 5 | Helal | 4 | 800 |
| NULL | NULL | 5 | 150 |
Full Join (or Full Outer Join):
A Full Join returns all rows when there is a match in either the left (Customers) or right (Orders) table. Rows without a match in one of the tables will have NULLs in the corresponding columns.
SELECT Customers.ID, Customers.FirstName, Orders.OrderID, Orders.Amount FROM Customers FULL OUTER JOIN Orders ON Customers.ID = Orders.CustomerID;
Result Set:
| ID | First Name | Order ID | Amount |
|---|---|---|---|
| 1 | Rahim | NULL | NULL |
| 2 | Karim | NULL | NULL |
| 3 | Belal | 2 | 500 |
| 4 | Rony | NULL | NULL |
| 5 | Helal | 4 | 800 |
| NULL | NULL | 1 | 200 |
| NULL | NULL | 3 | 300 |
| NULL | NULL | 5 | 150 |
Below tables are given, Employee (employee_id, name, salary, department) Leave (employee_id, date, reason, no_leaves) Holiday (Date, description) Rupali Bank, ANE, 2022

SELECT employee_id, COUNT(employee_id)
FROM Leave
GROUP BY employee_id;
SELECT *
FROM employee
WHERE employee_id IN (
SELECT employee_id
FROM leave
GROUP BY employee_id
HAVING COUNT(employee_id) > 5
);
SELECT d.department_name, AVG(e.salary) AS average_salary
FROM employees e
JOIN department d ON e.department_id = d.department_id
WHERE e.salary > (SELECT AVG(salary) FROM employees)
GROUP BY d.department_name
HAVING COUNT(*) > 2
ORDER BY average_salary DESC;
SELECT d.department_name, AVG(e.salary) AS average_salary
This clause selects the department name and calculates the average salary of employees in each department.
FROM employees e
This clause specifies the employees table as the main data source and uses e as an alias.
JOIN department d ON e.department_id = d.department_id
This join links employees with their departments using the common department_id.
WHERE e.salary > (SELECT AVG(salary) FROM employees)
This condition filters employees whose salary is higher than the overall average salary of all employees.
GROUP BY d.department_name
This clause groups records by department name to calculate aggregate values.
HAVING COUNT(*) > 2
This condition ensures that only departments with more than two employees are included.
ORDER BY average_salary DESC
This clause sorts the result in descending order based on average salary.
SELECT d.department_name, AVG(e.salary) AS average_salary
এই clause department-এর নাম দেখায় এবং প্রতিটি department-এর employee-দের average salary হিসাব করে।
FROM employees e
এই clause employees table-কে data source হিসেবে ব্যবহার করে এবং e alias ব্যবহার করে।
JOIN department d ON e.department_id = d.department_id
এই JOIN clause department_id ব্যবহার করে employee-দের তাদের department-এর সাথে যুক্ত করে।
WHERE e.salary > (SELECT AVG(salary) FROM employees)
এই condition শুধুমাত্র সেই employee-দের নির্বাচন করে যাদের salary সব employee-এর overall average salary-এর চেয়ে বেশি।
GROUP BY d.department_name
এই clause department অনুযায়ী data group করে aggregate calculation করতে সাহায্য করে।
HAVING COUNT(*) > 2
এই clause নিশ্চিত করে যে শুধুমাত্র ২ জনের বেশি employee থাকা department গুলো result-এ আসবে।
ORDER BY average_salary DESC
এই clause average salary অনুযায়ী descending order-এ result সাজায়।
SELECT department_name, AVG(salary) AS average_salary
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE salary > (
SELECT AVG(salary)
FROM employees
WHERE department_id = d.department_id
)
GROUP BY department_name
HAVING COUNT(*) > 2
ORDER BY average_salary DESC; Rupali , ANE, 2023
Explanation of SQL Query Clauses
SELECT Clause: The SELECT clause specifies which columns or calculated values will appear in the result.
department_nameselects the department name from thedepartmentstable.AVG(salary) AS average_salarycalculates the average salary of selected employees and renames it asaverage_salary.
FROM Clause: The FROM clause specifies the tables used in the query.
employees eselects the employees table with aliase.JOIN departments d ON e.department_id = d.department_idjoins employees with departments usingdepartment_id.
WHERE Clause: The WHERE clause filters rows before grouping.
salary > (SELECT AVG(salary) FROM employees WHERE department_id = d.department_id)selects employees whose salary is greater than the average salary of their department.
GROUP BY Clause: The GROUP BY clause groups rows to perform aggregate calculations.
GROUP BY department_namegroups employees by department name.
HAVING Clause: The HAVING clause filters groups after aggregation.
HAVING COUNT(*) > 2selects only departments with more than two qualifying employees.
ORDER BY Clause: The ORDER BY clause sorts the final result.
ORDER BY average_salary DESCsorts departments by average salary in descending order.
SQL Query Clause-এর ব্যাখ্যা
SELECT Clause: SELECT clause নির্ধারণ করে কোন column বা calculated value result-এ দেখানো হবে।
department_namedepartmentstable থেকে department-এর নাম নির্বাচন করে।AVG(salary) AS average_salaryemployee-দের average salary হিসাব করে এবং নাম দেয়average_salary।
FROM Clause: FROM clause নির্ধারণ করে কোন table থেকে data নেওয়া হবে।
employees eemployees table ব্যবহার করে, যেখানেeহলো alias।JOIN departments d ON e.department_id = d.department_iddepartment_id ব্যবহার করে দুইটি table যুক্ত করে।
WHERE Clause: WHERE clause grouping-এর আগে row filter করে।
salary > (SELECT AVG(salary) FROM employees WHERE department_id = d.department_id)শুধুমাত্র সেই employee নির্বাচন করে যাদের salary তাদের department-এর average salary-এর চেয়ে বেশি।
GROUP BY Clause: GROUP BY clause aggregate calculation করার জন্য data group করে।
GROUP BY department_namedepartment অনুযায়ী employee group করে।
HAVING Clause: HAVING clause aggregation-এর পরে group filter করে।
HAVING COUNT(*) > 2শুধুমাত্র সেই department দেখায় যেখানে ২ জনের বেশি qualifying employee আছে।
ORDER BY Clause: ORDER BY clause final result sort করে।
ORDER BY average_salary DESCaverage salary অনুযায়ী descending order-এ result দেখায়।
Write SQL command from the following tables.
Employee (ename, street, city)
Works (ename, cname, salary, joindate)
Company (cname, city)
Manages (ename, mname) 6 Bank & FI, AP, 2021
SELECT e.ename, e.street, e.city
FROM Employee e, Works w
WHERE e.ename = w.ename
AND w.cname = 'First Corporation Bank'
AND w.salary > 30000;
SELECT e.ename
FROM Employee e, Works w, Company c
WHERE e.city = c.city
AND w.cname = c.cname
AND e.ename = w.ename
AND e.city = w.city;
UPDATE Works
SET salary = salary + salary * 0.1
WHERE cname = 'First Century Bank';
SELECT cname
FROM Works
GROUP BY cname
HAVING SUM(salary) < 100000;
Previous Job Question with ANSWER on SQL
- ☆1Structure Query LanguageAn institute wants to create a database table named STUDENT to store student information. The table should include the columns Roll Number, Name, Department, Email, and Admission Date. Specify the most appropriate SQL data type for each column and identify which column should be defined as the Primary Key, giving a brief justification for your choice.CB, O(IT-24), 26 | Officer (IT)
Table Structure with Appropriate SQL Data Types
Column Name SQL Data Type Reason RollNumber INT Stores numeric roll numbers efficiently. Name VARCHAR(100) Stores student names of variable length. Department VARCHAR(50) Stores department names such as CSE, EEE, BBA, etc. Email VARCHAR(100) Stores email addresses of varying lengths. AdmissionDate DATE Stores only the admission date in YYYY-MM-DD format. Primary Key
RollNumber should be defined as the Primary Key because it uniquely identifies each student record, does not allow duplicate values, and cannot contain NULL values.
Sample SQL Statement
CREATE TABLE STUDENT ( RollNumber INT PRIMARY KEY, Name VARCHAR(100), Department VARCHAR(50), Email VARCHAR(100), AdmissionDate DATE );
- ☆2Structure Query LanguageWhat happened after executing the following SQL Statement:
CREATE TABLE t (Val INT);
INSERT INTO t(val) VALUES (1,2,2,3,
"null", "null",4,5);
SELECT COUNT (val)
FROM t;
SELECT COUNT DISTICT (val)
FROM t;CB, SO(IT), 22 | Senior Officer (IT)CREATE TABLE: A table
tis created with one columnvalof typeINTEGER.INSERT INTO: The values
1, 2, 2, 3, NULL, NULL, 4, 5are inserted into the columnval.SELECT COUNT(val): This query counts all non-NULL values in the
valcolumn.Total non-NULL values:
1, 2, 2, 3, 4, 5Result: 6
SELECT COUNT(DISTINCT val): This query counts only the unique non-NULL values in the
valcolumn.Unique values:
1, 2, 3, 4, 5Result: 5
- ☆3Structure Query LanguageGiven Student(sid, name, dept) and Course(sid, cid, cname, marks), Find the student name, department, course name, and marks where marks are greater than 80.
Find department-wise and subject-wise students where marks are not less than 30.ICB, AP, 26 | Assistant ProgrammerWe are given two relations: Student(sid, name, dept) and Course(sid, cid, cname, marks). The common attribute sid is used to join both tables.
1. Students with marks greater than 80:
This query retrieves high-performing students by applying a selection condition on marks.
SELECT S.name, S.dept, C.cname, C.marks
FROM Student S
JOIN Course C ON S.sid = C.sid
WHERE C.marks > 80;2. Department-wise and subject-wise students (marks ≥ 30):
This query filters moderately passed students and organizes output by department and course.
SELECT S.dept, C.cname, S.name, C.marks
FROM Student S
JOIN Course C ON S.sid = C.sid
WHERE C.marks >= 30;Conclusion: JOIN operation is essential to combine student identity with course performance data.
SQL Solution
১. Marks 80 এর বেশি:
SELECT S.name, S.dept, C.cname, C.marks
FROM Student S
JOIN Course C ON S.sid = C.sid
WHERE C.marks > 80;২. Department-wise ও subject-wise (marks ≥ 30):
SELECT S.dept, C.cname, S.name, C.marks
FROM Student S
JOIN Course C ON S.sid = C.sid
WHERE C.marks >= 30; - ☆4Structure Query LanguageConsider the following relation:
Employee (EmpID, Name, Department, Salary)
Write an SQL query to retrieve the Department, the total number of employees, and the average salary for each department. The output should display one record for each department.Combined Bank, SO(IT-24), 26 | Senior Officer (IT)SELECT Department, COUNT(EmpID) AS TotalEmployees, AVG(Salary) AS AverageSalary FROM Employee GROUP BY Department;Explanation
Department → Displays the department name.
COUNT(EmpID) → Counts the total number of employees in each department.
AVG(Salary) → Calculates the average salary of employees in each department.
GROUP BY Department → Groups all employees by department and returns one record for each department. - ☆5Structure Query LanguageWrite an SQL query to retrieve the department name and the average salary from two tables named Department and Employee.Islami, QA(Engineer), 25 | Bank
SELECT d.dept_name, AVG(e.salary) AS average_salary FROM department d JOIN employee e ON d.dept_id = e.dept_id GROUP BY d.dept_name;
- ☆6Structure Query Language
7. Write SQL command from the following tables.
(a) Find name, street, city who work for First Corporation Bank and earn more than 30000
Employee (ename, street, city)
Works (ename, cname, salary, joindate)
Company (cname, city)
Manages (ename, mname)
(b) Find name of all employees, who live in the same city and company for which they work.
(c) Give all employees of First Century Bank 10 percent salary raise.
(d) Find the company with payroll less than 100000.6 Bank & FI, AP, 21 | Assistant Programmera) answer:SELECT cname FROM Works GROUP BY cname HAVING SUM(salary) < 100000;
b)answer:SELECT e.ename FROM Employee e, Works w, Company c WHERE e.city = c.city AND w.cname = c.cname AND e.ename = w.ename AND e.city = w.city;
c)answer:UPDATE Works SET salary = salary + salary * 0.1 WHERE cname = 'First Century Bank';
d)answer:SELECT cname FROM Works GROUP BY cname HAVING SUM(salary) < 100000;
- ☆7Structure Query LanguageA transaction consists of a sequence of query and/or update statements. SQL statement must be required to end the transaction. List the SQL statements, required to end the transaction and also write their functions.CB, O(IT), 20 | Officer (IT)
A Transaction is a sequence of one or more SQL statements executed as a single logical unit of work. A transaction must be terminated using SQL transaction control statements.
SQL Statements to End a Transaction
SQL Statement Function COMMIT Permanently saves all changes made during the current transaction to the database. ROLLBACK Undoes all changes made during the current transaction since the last COMMIT or SAVEPOINT. SAVEPOINT Creates a checkpoint within a transaction so that the transaction can be rolled back to that point if needed. ROLLBACK TO SAVEPOINT Restores the transaction to a previously created SAVEPOINT without cancelling the entire transaction. COMMIT saves the transaction permanently, ROLLBACK cancels the transaction, and SAVEPOINT allows partial rollback within a transaction.
- ☆8Structure Query LanguageConsider the following relation:
Sales(sales_id, salesman, region, sale_amount, sale_date) ,
Write an SQL query to display the region, average sale amount, and total number of sales for each region where: The average sale amount exceeds BDT 50,000 and the total number of sales in that region is at least 5.Combined Bank, SO-IT, 25 | Senior Officer (IT)SQL Query
The following query displays the region, average sale amount, and total number of sales for each region where the average sale amount is greater than BDT 50,000 and the total number of sales is at least 3.SELECT region,
AVG(sale_amount) AS avg_sale_amount,
COUNT(*) AS total_sales
FROM Sales
GROUP BY region
HAVING AVG(sale_amount) > 50000
AND COUNT(*) >= 3;
SQL Query
নিচের query টি প্রতিটি region অনুযায়ী average sale amount এবং total sales সংখ্যা দেখায়, যেখানে average sale amount BDT 50,000 এর বেশি এবং ঐ region এ মোট sales কমপক্ষে 3টি।SELECT region,
AVG(sale_amount) AS avg_sale_amount,
COUNT(*) AS total_sales
FROM Sales
GROUP BY region
HAVING AVG(sale_amount) > 50000
AND COUNT(*) >= 3;
- ☆9Structure Query Language
Below tables are given,
Employee (employee_id, name, salary, department)
Leave (employee_id, date, reason, no_leaves)
Holiday (Date, description)
(i) Write mapping cardinality between 'Employee' and 'Holiday' table.
(ii) Write query to show all employee's leave count.
(iii) Write query to show employees who are in 'HR' department and have taken at least 5 leaves.Rupali, ANE, 21 |(i)
(ii)SELECT employee_id, COUNT(employee_id) FROM Leave GROUP BY employee_id;
iii)SELECT * FROM employee WHERE employee_id IN ( SELECT employee_id FROM leave GROUP BY employee_id HAVING COUNT(employee_id) > 5 );
- ☆10Structure Query LanguageDatabase Query: Four table is given.(table missing)
a) Write a query for find the Publisher name which location is 'Dhaka' and which book is published after 1980 year.Sonali, O(it), 21 | Officer (IT)Apprx..
SELECT p_name FROM publication WHERE loc = 'dhaka' AND p_date > 1980;
- ☆11Structure Query LanguageWrite a query to change the type of Book name 'Science' to 'Computer Science' which branch name is 'Dhaka' citySonali, O(it), 21 | Officer (IT)
Apprx..
UPDATE BOOK SET Book_name = 'Computer Science' WHERE Book_name = 'Science';
- ☆12Structure Query LanguageA database contains a table named Hospital(HospitalID, HospitalName, Specialization, PatientCount). Write an SQL query to display the names of the five hospitals that specialize in accident treatment and have treated the highest number of patients.[assume]Combined Bank, ADA-23, 26 | ADA
SELECT HospitalName
FROM Hospital
WHERE Specialization = 'Accident Treatment'
ORDER BY PatientCount DESC
LIMIT 5;Explanation:
- WHERE filters hospitals specializing in accident treatment.
- ORDER BY PatientCount DESC sorts hospitals from highest to lowest patient count.
- LIMIT 5 returns the top five hospitals.
- ☆13Structure Query LanguageA developer writes the SQL statement SELECT EmployeeName, Salary FROM Employees WHERE Salary > AVG(Salary);, but the query generates an error. Identify the problem and write a corrected SQL query.[assume]Combined Bank, ADA-23, 26 | ADA
Problem Identification: The query is incorrect because AVG(Salary) is an aggregate function and cannot be used directly in the WHERE clause. Aggregate functions must be computed using a subquery.
Incorrect Query:
SELECT EmployeeName, Salary
FROM Employees
WHERE Salary > AVG(Salary);Why it fails:
- WHERE clause is evaluated before aggregation.
- AVG(Salary) requires grouped or subquery context.
Correct Query:
SELECT EmployeeName, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);Explanation:
- The subquery calculates the average salary first.
- Main query compares each employee salary with the computed average.
- ☆14Structure Query LanguageFrom an Employee table, write SQL statements according to the following question:
(a) Find out the employees who join on the same date.
(b) Find those employees whose salary is greater than 8,000 and less than 25,000.Dwasa,AME,25 | OtherSQL Queries for the Employee TableAssume the Employee table contains the following columns:
- employee_id — Employee ID
- employee_name — Employee Name
- join_date — Joining Date
- salary — Employee Salary
(a) Find the employees who joined on the same date.
First, identify the joining dates that occur more than once, then retrieve the employees having those dates:
SELECT * FROM Employee WHERE join_date IN ( SELECT join_date FROM Employee GROUP BY join_date HAVING COUNT(*) > 1 );Explanation:
- GROUP BY join_date → Groups employees according to their joining date.
- HAVING COUNT(*) > 1 → Selects dates on which more than one employee joined.
- The outer query displays all employees whose joining date matches those dates.
(b) Find employees whose salary is greater than 8,000 and less than 25,000.
SELECT * FROM Employee WHERE salary > 8000 AND salary < 25000;
Explanation:
- salary > 8000 → The salary must be greater than 8,000.
- salary < 25000 → The salary must be less than 25,000.
- AND → Both conditions must be true.
Alternative for (b):
SELECT * FROM Employee WHERE salary BETWEEN 8001 AND 24999;
Important: BETWEEN is inclusive. Therefore, for the exact condition greater than 8,000 and less than 25,000, using > 8000 and < 25000 is clearer and safer.
- ☆15Structure Query LanguageYou have tables EMPLOYEES (ID, Name, DeptID) and DEPARTMENTS (DeptID, DeptName). Write pseudo-SQL logic to get employee names who work in 'IT'.Combined Bank, O(IT-22), 26 | Officer (IT)Given Tables: EMPLOYEES (ID, Name, DeptID) DEPARTMENTS (DeptID, DeptName)Objective: To get the list of employee names who work in the IT department.Logical Steps:
- Identify the DeptID of the department where DeptName is IT.
- Match this DeptID with the DeptID in the EMPLOYEES table.
- Select the Name of employees who belong to the IT department.
SELECT E.Name FROM EMPLOYEES E JOIN DEPARTMENTS D ON E.DeptID = D.DeptID WHERE D.DeptName = 'IT' - ☆16Structure Query LanguageFour queries(table client, salesman, sale, order etc) (unable to collect this question)SB & JB, ADA, 22 | ADA
- ☆17Structure Query LanguageOthersLet a database has two tables, Customers and Orders. The following figure shows the partial data of these two tables. Based on this partial data, explain Inner, Left, Right and Full join. Show the result set of each join operation
Combined Bank, SO(IT), 24 | Senior Officer (IT)Inner Join:
An Inner Join returns only the rows that have matching values in both tables.
SELECT Customers.ID, Customers.FirstName, Orders.OrderID, Orders.Amount FROM Customers INNER JOIN Orders ON Customers.ID = Orders.CustomerID;Result Set:
ID First Name Order ID Amount 3 Belal 2 500 5 Helal 4 800 Left Join (or Left Outer Join):
A Left Join returns all rows from the left table (Customers), and the matched rows from the right table (Orders). If there is no match, the result is NULL on the right side.
SELECT Customers.ID, Customers.FirstName, Orders.OrderID, Orders.Amount FROM Customers LEFT JOIN Orders ON Customers.ID = Orders.CustomerID;Result Set:
ID First Name Order ID Amount 1 Rahim NULL NULL 2 Karim NULL NULL 3 Belal 2 500 4 Rony NULL NULL 5 Helal 4 800 Right Join (or Right Outer Join):
A Right Join returns all rows from the right table (Orders), and the matched rows from the left table (Customers). If there is no match, the result is NULL on the left side.
SELECT Customers.ID, Customers.FirstName, Orders.OrderID, Orders.Amount FROM Customers RIGHT JOIN Orders ON Customers.ID = Orders.CustomerID;Result Set:
ID First Name Order ID Amount NULL NULL 1 200 3 Belal 2 500 NULL NULL 3 300 5 Helal 4 800 NULL NULL 5 150 Full Join (or Full Outer Join):
A Full Join returns all rows when there is a match in either the left (Customers) or right (Orders) table. Rows without a match in one of the tables will have NULLs in the corresponding columns.
SELECT Customers.ID, Customers.FirstName, Orders.OrderID, Orders.Amount FROM Customers FULL OUTER JOIN Orders ON Customers.ID = Orders.CustomerID;Result Set:
ID First Name Order ID Amount 1 Rahim NULL NULL 2 Karim NULL NULL 3 Belal 2 500 4 Rony NULL NULL 5 Helal 4 800 NULL NULL 1 200 NULL NULL 3 300 NULL NULL 5 150 - ☆18Structure Query LanguageOthersExplain the distinct filtering behaviors of a WHERE clause versus a HAVING clause withing a SQL statement containing an aggregate execution layout.RAKUB, ANSE, 26 | AME/ANE/AE
WHERE vs HAVING Clause in SQL
In SQL, both WHERE and HAVING are used to filter data, but they operate at different stages of query execution and serve different purposes. Understanding their behavior is essential when working with aggregate functions like SUM, COUNT, AVG, MIN, and MAX.
1. WHERE Clause
The WHERE clause filters individual rows before any grouping or aggregation takes place. It works directly on raw table data.
- Stage: Executes before GROUP BY and aggregate functions
- Scope: Filters individual rows based on column values
- Aggregate functions: Cannot be used directly in WHERE
- Performance: Reduces row count early, improving efficiency of later operations
Example:
Select only employees from the Sales department before calculating average salary.
SELECT dept, AVG(salary) FROM employees WHERE dept = 'Sales' GROUP BY dept;Here, WHERE first filters rows where dept = 'Sales', and then AVG is calculated on the filtered dataset.
2. HAVING Clause
The HAVING clause filters groups of rows after grouping and aggregation are completed. It works on aggregated results.
- Stage: Executes after GROUP BY and aggregation
- Scope: Filters grouped results
- Aggregate functions: Can be used in HAVING
- Performance: Works after aggregation, so it cannot reduce initial row processing
Example:
Show only departments where the average salary is greater than 50,000.
SELECT dept, AVG(salary) FROM employees GROUP BY dept HAVING AVG(salary) > 50000;Here, GROUP BY creates department groups, AVG calculates the average, and HAVING filters groups based on the aggregated value.
3. Execution Order in SQL
Order Clause Action 1 FROM Identify source table 2 WHERE Filter individual rows 3 GROUP BY Group filtered rows 4 Aggregate Apply SUM, COUNT, AVG, etc. 5 HAVING Filter grouped results 6 SELECT Select columns for output 7 ORDER BY Sort final output 4. Combined Example
Find departments in the Sales region where total sales exceed 100,000.
SELECT region, SUM(sales) AS total FROM orders WHERE region = 'Sales' GROUP BY region HAVING SUM(sales) > 100000;- WHERE region = 'Sales': Filters individual rows belonging to Sales region
- GROUP BY region: Groups remaining rows by region
- SUM(sales): Computes total sales per group
- HAVING SUM(sales) > 100000: Filters groups based on aggregated result
SQL-এ WHERE vs HAVING Clause
SQL-এ WHERE এবং HAVING উভয়ই data filter করতে ব্যবহৃত হয়, তবে তারা query execution-এর ভিন্ন stage-এ কাজ করে এবং ভিন্ন purpose serve করে। Aggregate functions (SUM, COUNT, AVG, MIN, MAX) ব্যবহার করার ক্ষেত্রে তাদের পার্থক্য খুব গুরুত্বপূর্ণ।
1. WHERE Clause
WHERE clause individual rows filter করে, grouping বা aggregation হওয়ার আগেই। এটি raw table data-এর উপর কাজ করে।
- Stage: GROUP BY এবং aggregate functions-এর আগে execute হয়
- Scope: Individual row-level filtering
- Aggregate functions: WHERE-এর মধ্যে সরাসরি ব্যবহার করা যায় না
- Performance: Early filtering হওয়ায় processing cost কমে যায়
Example:
Average salary calculate করার আগে শুধু Sales department-এর employees select করা।
SELECT dept, AVG(salary) FROM employees WHERE dept = 'Sales' GROUP BY dept;এখানে WHERE প্রথমে Sales department-এর rows filter করে, তারপর সেই filtered data-এর উপর AVG calculate করা হয়।
2. HAVING Clause
HAVING clause groups of rows filter করে, grouping এবং aggregation complete হওয়ার পরে। এটি aggregate result-এর উপর কাজ করে।
- Stage: GROUP BY এবং aggregation-এর পরে execute হয়
- Scope: Group-level filtering
- Aggregate functions: ব্যবহার করা যায়
- Performance: Aggregation-এর পরে কাজ করে, তাই early filtering করে না
Example:
শুধু সেই departments দেখানো যেখানে average salary 50,000-এর বেশি।
SELECT dept, AVG(salary) FROM employees GROUP BY dept HAVING AVG(salary) > 50000;এখানে GROUP BY আগে department অনুযায়ী groups তৈরি করে, তারপর HAVING সেই groups filter করে যাদের average salary 50,000-এর বেশি।
3. SQL Execution Order
Order Clause Action 1 FROM Source table identify করা 2 WHERE Individual rows filter করা 3 GROUP BY Rows group করা 4 Aggregate SUM, COUNT, AVG ইত্যাদি apply করা 5 HAVING Grouped results filter করা 6 SELECT Final output columns select করা 7 ORDER BY Final result sort করা 4. Combined Example
Sales region-এর সেই departments খুঁজুন যেখানে total sales 100,000-এর বেশি।
SELECT region, SUM(sales) AS total FROM orders WHERE region = 'Sales' GROUP BY region HAVING SUM(sales) > 100000;- WHERE region = 'Sales': individual rows থেকে শুধু Sales region filter করে
- GROUP BY region: filtered rows group করে
- SUM(sales): প্রতিটি group-এর total sales calculate করে
- HAVING SUM(sales) > 100000: শুধু সেই groups রাখে যাদের total sales 100,000-এর বেশি
- ☆19Structure Query LanguageSQLAnalize the following code:
SELECT d.department_name, AVG(e.salary) AS average_salary
FROM employees e
JOIN department d ON e.department_id = d.department_id
WHERE e.salary > (SELECT AVG(salary) FROM employees)
GROUP BY d.department_name
HAVING COUNT(*) > 2
ORDER BY average_salary DESC;CB, O(IT), 23 | Officer (IT)SELECT d.department_name, AVG(e.salary) AS average_salaryThis clause selects the department name and calculates the average salary of employees in each department.
FROM employees eThis clause specifies the
employeestable as the main data source and useseas an alias.JOIN department d ON e.department_id = d.department_idThis join links employees with their departments using the common
department_id.WHERE e.salary > (SELECT AVG(salary) FROM employees)This condition filters employees whose salary is higher than the overall average salary of all employees.
GROUP BY d.department_nameThis clause groups records by department name to calculate aggregate values.
HAVING COUNT(*) > 2This condition ensures that only departments with more than two employees are included.
ORDER BY average_salary DESCThis clause sorts the result in descending order based on average salary.
SELECT d.department_name, AVG(e.salary) AS average_salaryএই clause department-এর নাম দেখায় এবং প্রতিটি department-এর employee-দের average salary হিসাব করে।
FROM employees eএই clause
employeestable-কে data source হিসেবে ব্যবহার করে এবংealias ব্যবহার করে।JOIN department d ON e.department_id = d.department_idএই JOIN clause
department_idব্যবহার করে employee-দের তাদের department-এর সাথে যুক্ত করে।WHERE e.salary > (SELECT AVG(salary) FROM employees)এই condition শুধুমাত্র সেই employee-দের নির্বাচন করে যাদের salary সব employee-এর overall average salary-এর চেয়ে বেশি।
GROUP BY d.department_nameএই clause department অনুযায়ী data group করে aggregate calculation করতে সাহায্য করে।
HAVING COUNT(*) > 2এই clause নিশ্চিত করে যে শুধুমাত্র ২ জনের বেশি employee থাকা department গুলো result-এ আসবে।
ORDER BY average_salary DESCএই clause average salary অনুযায়ী descending order-এ result সাজায়।
- ☆20Structure Query LanguageSQL
Suppose we have a relational database with five tables. table key Attributes S(sid, A)Sid T(tid, B) Tid U(uid, C) Uid R(sid, tid, D) sid, tid Q(tid, uid, E) tid, uid Here R implements a many-to-many relationship between the entities implemented with tables S and T, and Q implements a many-to-many relationship between the entities implemented with tables T and U.
(a) Write an SQL query that returns all records of the form sid, uid where sid is the key of an S- record and uid is the key of a U-record and these two records are related through the relations R and Q. Use SELECT and not SELECT DISTINCT in your query.
(b) Write an SQL query that returns records of the form A, C where the A-value is from an S- record and the C-value is from a U-record and these two records are related through the relations R and Q. Use SELECT and not SELECT DISTINCT in your query.CB, AP, 23 | Assistant Programmera) answer:We need to retrieve sid from table R and uid from table Q, where the two tables are related through the common column tid.
SELECT R.sid, Q.uid FROM R JOIN Q ON R.tid = Q.tid;
Explanation:
- R.sid: Selects the sid from table R.
- Q.uid: Selects the uid from table Q.
- The JOIN connects R and Q through their tid columns, which establish the relationship between the two tables.
b) answer:Here, we need to select A from table S and C from table U, connecting them through the relations R and Q.
SELECT S.A, U.C FROM S JOIN R ON S.sid = R.sid JOIN Q ON R.tid = Q.tid JOIN U ON Q.uid = U.uid;
Explanation:
- S.A: Selects the A-value from the S table (which corresponds to sid).
- The first JOIN connects table S with table R through sid.
- The second JOIN connects R and Q on tid.
- Finally, Q is connected to U via uid, allowing us to select C from U.
- ☆21Structure Query LanguageSQLWhat is the full meaning of SQL? List of the aggregate function. Write SQL Query of a table and its output.CB, AP, 20 | Assistant Programmer
- ☆22Structure Query LanguageMiscConsider a STUDENTS table with the following attributes: StudentID, Name, Department, and Marks.
(i) Write an SQL query to display only StudentID, Name, and Marks for students scoring more than 80 marks.
(ii) Write an SQL query to count how many students scored more than 80 marks in each Department.Combined Bank, O(IT-23), 26 | Officer (IT)(i) SQL Query to Display StudentID, Name, and Marks for Students Scoring More Than 80 Marks
SELECT StudentID, Name, Marks FROM STUDENTS WHERE Marks > 80;Explanation:
- SELECT chooses the required columns.
- FROM STUDENTS specifies the table name.
- WHERE Marks > 80 filters students who scored more than 80 marks.
(ii) SQL Query to Count Students Scoring More Than 80 Marks in Each Department
SELECT Department, COUNT(*) AS Total_Students FROM STUDENTS WHERE Marks > 80 GROUP BY Department;Explanation:
- COUNT(*) counts the number of students.
- GROUP BY Department groups records department-wise.
- WHERE Marks > 80 considers only students scoring above 80.
(i) 80-এর বেশি Marks পাওয়া Student-দের StudentID, Name এবং Marks প্রদর্শনের SQL Query
SELECT StudentID, Name, Marks FROM STUDENTS WHERE Marks > 80;ব্যাখ্যা:
- SELECT প্রয়োজনীয় column নির্বাচন করে।
- FROM STUDENTS table-এর নাম নির্দেশ করে।
- WHERE Marks > 80 80-এর বেশি marks পাওয়া student filter করে।
(ii) প্রতিটি Department-এ 80-এর বেশি Marks পাওয়া Student সংখ্যা গণনার SQL Query
SELECT Department, COUNT(*) AS Total_Students FROM STUDENTS WHERE Marks > 80 GROUP BY Department;ব্যাখ্যা:
- COUNT(*) student সংখ্যা গণনা করে।
- GROUP BY Department department অনুযায়ী group তৈরি করে।
- WHERE Marks > 80 শুধুমাত্র 80-এর বেশি marks পাওয়া student বিবেচনা করে।
- ☆23Structure Query LanguagesqlConsider you are given a database of a pet society with the following relations:
Animals (ID: integer, Name: string, PrevOwner: string, DateAdmitted: date, Type: string)
Adopter (PSIN: integer, Name: string, Address: string, OtherAnimals: integer)
Adoption (AnimalID: integer, PSIN: integer, AdoptDate: date, chipNo: integer)
Give an SQL query that lists the total number of adoptions on June 30, 2024, for each animal type.Combined Bank, O(IT), 24 | Officer (IT)SELECT A.Type AS AnimalType, COUNT(*) AS TotalAdoptions FROM Animals A JOIN Adoption AD ON A.ID = AD.AnimalID WHERE AD.AdoptDate = '2024-06-30' GROUP BY A.Type;
- ☆24Structure Query LanguageSqlAnalyze the output of the following SQL :
SELECT department_name, AVG(salary) AS average_salary
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE salary > (
SELECT AVG(salary)
FROM employees
WHERE department_id = d.department_id
)
GROUP BY department_name
HAVING COUNT(*) > 2
ORDER BY average_salary DESC;Rupali, ANE, 23 | AME/ANE/AEExplanation of SQL Query Clauses
SELECT Clause: The SELECT clause specifies which columns or calculated values will appear in the result.
department_nameselects the department name from thedepartmentstable.AVG(salary) AS average_salarycalculates the average salary of selected employees and renames it asaverage_salary.
FROM Clause: The FROM clause specifies the tables used in the query.
employees eselects the employees table with aliase.JOIN departments d ON e.department_id = d.department_idjoins employees with departments usingdepartment_id.
WHERE Clause: The WHERE clause filters rows before grouping.
salary > (SELECT AVG(salary) FROM employees WHERE department_id = d.department_id)selects employees whose salary is greater than the average salary of their department.
GROUP BY Clause: The GROUP BY clause groups rows to perform aggregate calculations.
GROUP BY department_namegroups employees by department name.
HAVING Clause: The HAVING clause filters groups after aggregation.
HAVING COUNT(*) > 2selects only departments with more than two qualifying employees.
ORDER BY Clause: The ORDER BY clause sorts the final result.
ORDER BY average_salary DESCsorts departments by average salary in descending order.
SQL Query Clause-এর ব্যাখ্যা
SELECT Clause: SELECT clause নির্ধারণ করে কোন column বা calculated value result-এ দেখানো হবে।
department_namedepartmentstable থেকে department-এর নাম নির্বাচন করে।AVG(salary) AS average_salaryemployee-দের average salary হিসাব করে এবং নাম দেয়average_salary।
FROM Clause: FROM clause নির্ধারণ করে কোন table থেকে data নেওয়া হবে।
employees eemployees table ব্যবহার করে, যেখানেeহলো alias।JOIN departments d ON e.department_id = d.department_iddepartment_id ব্যবহার করে দুইটি table যুক্ত করে।
WHERE Clause: WHERE clause grouping-এর আগে row filter করে।
salary > (SELECT AVG(salary) FROM employees WHERE department_id = d.department_id)শুধুমাত্র সেই employee নির্বাচন করে যাদের salary তাদের department-এর average salary-এর চেয়ে বেশি।
GROUP BY Clause: GROUP BY clause aggregate calculation করার জন্য data group করে।
GROUP BY department_namedepartment অনুযায়ী employee group করে।
HAVING Clause: HAVING clause aggregation-এর পরে group filter করে।
HAVING COUNT(*) > 2শুধুমাত্র সেই department দেখায় যেখানে ২ জনের বেশি qualifying employee আছে।
ORDER BY Clause: ORDER BY clause final result sort করে।
ORDER BY average_salary DESCaverage salary অনুযায়ী descending order-এ result দেখায়।
MCQ on SQL
📘 uncategorized
1. Which of the following is an essential process in which intelligent methods are applied to extract data patterns?
2. What is the use of data cleaning?
3. Which of the following provides the ability to query information from the database and insert, delete, and modify tuples?
4. The system may manage a high degree of interaction between processes and is very useful for high-speed and real-time processing.
5. The SQL statement
SELECT COUNT(*) FROM employee
WHERE SALARY > ALL (SELECT SALARY FROM EMPLOYEE)
prints:
WHERE SALARY > ALL (SELECT SALARY FROM EMPLOYEE)
6. Which command is correct to delete the values from the student table?
7. In a relational database, which property ensures that a transaction is all-or-nothing?
8. Which database is NoSQL?
9. Which of the following SQL commands are part of Data Definition Language (DDL)?
10. Which of the following is known as a minimal super key?
11. What does ACID stand for in database transactions?
12. SQL applies predicates after grouping in the ______ clause.
13. To remove duplicate rows from the results of an SQL SELECT statement, the __________ qualifier must be included.
14. What does a COMMIT statement do to a CURSOR?
15. Which tool could be used for detecting vulnerability through SQL Injection?
16. In SQL, the __________ command is used to recompile a view.
17. A primary key must also be:
18. The __________ clause is used to list the attributes desired in the result of a query.
19. What is the mounting of a file system?
20. The subset of a super key is a candidate key under what condition?
21. CREATE TABLE employee (name VARCHAR, id INTEGER). What type of statement is this?
22. In the First Normal Form (1NF), a composite attribute is converted to:
23. A graph having an edge from each vertex to every other vertex is called:
24. Why do we need to normalize a database?
25. If you are assigned to remove partial dependency from a database, which technique will you use?
26. In an Entity-Relationship (ER) diagram, a many-to-many relationship corresponds to a __________ in an actual database.
27. In a database, a field can store __________.
28. Consider the following table named 'Course'. What is the main anomaly in the table?
| Course Title | Content: |
| Web Programming | Python,CSS,JS |


