SQL Cheat Sheet & Interview Prep
1) Mini SQL Cheat Sheet
SELECT column1, column2 FROM table_name;
SELECT * FROM employees WHERE department = 'Sales';
SELECT * FROM employees ORDER BY salary DESC;
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
SELECT e.name, d.name
FROM employees e
INNER JOIN departments d ON e.department_id = d.id;
SELECT name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
INSERT INTO employees (name, salary) VALUES ('John Doe', 60000);
UPDATE employees SET salary = salary * 1.1 WHERE department = 'HR';
DELETE FROM employees WHERE id = 5;
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10,2),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(id)
);
2) Common SQL Interview Questions
1) Write a query to find the second highest salary in a table.
2) Find all employees who earn more than the average salary.
3) How do you remove duplicate rows from a result?
4) Difference between INNER JOIN and LEFT JOIN.
5) What is the difference between WHERE and HAVING?
6) Explain primary key vs. unique key.
7) How would you find employees who do not belong to any department?
8) What are ACID properties?
9) How do you handle NULLs in queries?
10) Write a query to count employees per department, sorted by count descending.
3) Sample Tables & Practice Exercises
Sample Tables:
Table: employees
| id | name | salary | department_id |
|----|------|--------|----------------|
| 1 | John | 50000 | 1 |
| 2 | Jane | 60000 | 1 |
| 3 | Bob | 45000 | 2 |
| 4 | Alice| 70000 | NULL |
Table: departments
| id | name |
|----|------|
| 1 | HR |
| 2 | IT |
| 3 | Sales|
Practice Exercises:
1) List all employees and their department names (include employees with no department).
2) Find employees who earn more than $50,000.
3) Find the highest salary in each department.
4) Count the number of employees in each department.
5) Show employees who do not belong to any department.
6) Add a new employee named Emma in IT with a salary of $55,000.
7) Increase salaries by 10% for employees in HR.
8) Delete all employees with salary less than $40,000.