SQL 1732644814
SQL 1732644814
2. Using JOINS
Q: Retrieve a list of employees who have made sales. Include their names,
employee ID, and sale amount from employees and sales tables.
A:
SELECT e.employee_id, e.name, s.sale_amount
FROM employees e
INNER JOIN sales s ON e.employee_id = s.employee_id;
3. Aggregate Functions
Q: Write a query to find the maximum and minimum salary in each
department from the employees table.
A:
SELECT department_id, MAX(salary) AS max_salary, MIN(salary) AS
min_salary
FROM employees
GROUP BY department_id;
A:
SELECT employee_id, name,
CASE
WHEN salary > 100000 THEN 'High'
WHEN salary BETWEEN 50000 AND 100000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;
6. Date Filtering
Q: Write a query to fetch orders placed in the last 30 days from the orders
table.
A:
SELECT *
FROM orders
WHERE order_date >= DATEADD(day, -30, GETDATE());
7. Subqueries
Q: Retrieve all customers who have made more than 5 orders from the
customers and orders tables.
A:
SELECT customer_id, name
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(order_id) > 5
);
8. Using DISTINCT
Q: How would you find unique product names from the products table?
A:
SELECT DISTINCT product_name
FROM products;
9. Updating Records
Nitya CloudTech Pvt Ltd.
Q: Update the salary of all employees in the 'Sales' department by 10% in the
employees table.
A:
UPDATE employees
SET salary = salary * 1.1
WHERE department = 'Sales';
Q: Identify duplicate entries in the products table based on product name and
price.
A:
SELECT product_name, price, COUNT(*)
FROM products
GROUP BY product_name, price
HAVING COUNT(*) > 1;
A:
WITH EmployeeHierarchy AS (
SELECT employee_id, manager_id, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.manager_id, eh.level + 1
FROM employees e
JOIN EmployeeHierarchy eh ON e.manager_id = eh.employee_id
)
SELECT * FROM EmployeeHierarchy;