Basic SQL Queries

Task: Retrieve all columns from the employees table.

SELECT * FROM employees;

Task: Retrieve only the name and position columns from the employees table.

SELECT name, position FROM employees;

Task: List all employees with a salary greater than 50,000.

SELECT * FROM employees WHERE salary > 50000;

Task: Sort employees by salary in descending order.

SELECT * FROM employees ORDER BY salary DESC;

Task: Find all distinct position values in the employees table.

SELECT DISTINCT position FROM employees;

Data Manipulation

Task: Add a new employee to the employees table.

INSERT INTO employees (name, position, salary)
VALUES ('John Doe', 'Developer', 60000);

Task: Update the salary of John Doe to 70,000.

UPDATE employees
SET salary = 70000
WHERE name = 'John Doe';

Task: Remove employees with a salary less than 30,000.

DELETE FROM employees
WHERE salary < 30000;

Relational Queries (JOIN)

Task: Join employees and departments tables to list employee names and their department names.

SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.id;

Task: List all employees and their departments, including those without a department.

SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.id;

Grouping and Functions

Task: Calculate the total salary of all employees.

SELECT SUM(salary) AS total_salary FROM employees;

Task: Calculate the average salary for each position.

SELECT position, AVG(salary) AS average_salary
FROM employees
GROUP BY position;

Task: Count the number of employees in each department.

SELECT departments.department_name, COUNT(employees.id) AS employee_count
FROM departments
LEFT JOIN employees
ON departments.id = employees.department_id
GROUP BY departments.department_name;

Task: Retrieve the highest salary and the employee who earns it.

SELECT name, MAX(salary) AS highest_salary
FROM employees;

Advanced SQL

Task: Find employees who earn more than the average salary.

SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

Task: List employees whose salaries are between 40,000 and 80,000.

SELECT * FROM employees
WHERE salary BETWEEN 40000 AND 80000;

Task: Find employees whose names start with “John.”

SELECT * FROM employees
WHERE name LIKE 'John%';

Practice Tips

CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), position VARCHAR(50), salary DECIMAL(10, 2), department_id INT ); 

INSERT INTO employees (name, position, salary, department_id) VALUES ('Alice', 'Manager', 80000, 1), ('Bob', 'Developer', 60000, 2), ('Charlie', 'Intern', 30000, NULL);

…………

Thank you for your time; sharing is caring! 🌍

…………

Leave a Reply

Your email address will not be published. Required fields are marked *