0% found this document useful (0 votes)
4 views5 pages

SQL Basic Queries

Uploaded by

mukesh.khanijo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

SQL Basic Queries

Uploaded by

mukesh.khanijo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

================================================================================

SQL BASIC QUERIES & JOINS - MID-LEVEL DEVELOPER INTERVIEW QUESTIONS


================================================================================

Q1. BASIC SELECT QUERIES


------------------------
Question: Write a query to find all employees who work in the 'IT' department and
have a salary greater than $50,000.

Table: employees (id, name, department, salary, hire_date)

Solution:
```sql
SELECT id, name, department, salary, hire_date
FROM employees
WHERE department = 'IT' AND salary > 50000
ORDER BY salary DESC;
```

Key Points:
- Use WHERE clause for filtering
- Use AND for multiple conditions
- ORDER BY for sorting results

Q2. JOIN OPERATIONS


-------------------
Question: Write a query to get employee names along with their department names.
Tables: employees (id, name, department_id, salary), departments (id, name,
location)

Solution:
```sql
-- Using INNER JOIN
SELECT e.name as employee_name, d.name as department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.id
ORDER BY e.name;

-- Using LEFT JOIN (includes employees without departments)


SELECT e.name as employee_name, d.name as department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.id
ORDER BY e.name;
```

Key Points:
- INNER JOIN returns only matching records
- LEFT JOIN returns all records from left table
- Use table aliases for cleaner code

Q3. AGGREGATION FUNCTIONS


-------------------------
Question: Calculate the average salary by department and show only departments with
average salary above $60,000.

Solution:
```sql
SELECT
d.name as department_name,
AVG(e.salary) as avg_salary,
COUNT(e.id) as employee_count
FROM employees e
JOIN departments d ON e.department_id = d.id
GROUP BY d.id, d.name
HAVING AVG(e.salary) > 60000
ORDER BY avg_salary DESC;
```

Key Points:
- GROUP BY groups results by specified columns
- HAVING filters grouped results
- WHERE filters individual rows before grouping

Q4. SUBQUERIES
--------------
Question: Find employees who earn more than the average salary of all employees.

Solution:
```sql
-- Using subquery in WHERE clause
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC;

-- Alternative using CTE (Common Table Expression)


WITH avg_salary AS (
SELECT AVG(salary) as avg_sal FROM employees
)
SELECT e.name, e.salary
FROM employees e, avg_salary
WHERE e.salary > avg_salary.avg_sal
ORDER BY e.salary DESC;
```

Q5. STRING FUNCTIONS


--------------------
Question: Find employees whose names start with 'J' and contain 'ohn' anywhere in
their name.

Solution:
```sql
SELECT name, department, salary
FROM employees
WHERE name LIKE 'J%' AND name LIKE '%ohn%'
ORDER BY name;

-- Alternative using REGEXP


SELECT name, department, salary
FROM employees
WHERE name REGEXP '^J.*ohn.*'
ORDER BY name;
```

Q6. DATE FUNCTIONS


------------------
Question: Find employees hired in the last 2 years and calculate their tenure in
months.
Solution:
```sql
SELECT
name,
hire_date,
DATEDIFF(CURRENT_DATE, hire_date) as days_employed,
TIMESTAMPDIFF(MONTH, hire_date, CURRENT_DATE) as months_employed
FROM employees
WHERE hire_date >= DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR)
ORDER BY hire_date DESC;
```

Q7. CASE STATEMENTS


-------------------
Question: Categorize employees by salary ranges: Low (< 50000), Medium (50000-
80000), High (> 80000).

Solution:
```sql
SELECT
name,
salary,
CASE
WHEN salary < 50000 THEN 'Low'
WHEN salary BETWEEN 50000 AND 80000 THEN 'Medium'
ELSE 'High'
END as salary_category
FROM employees
ORDER BY salary DESC;
```

Q8. LIMIT AND OFFSET


--------------------
Question: Get the top 5 highest-paid employees with pagination (show next 5).

Solution:
```sql
-- Top 5 highest paid
SELECT name, salary, department
FROM employees
ORDER BY salary DESC
LIMIT 5;

-- Next 5 (pagination)
SELECT name, salary, department
FROM employees
ORDER BY salary DESC
LIMIT 5 OFFSET 5;
```

PRACTICAL EXERCISES:
====================

Exercise 1: Employee Database


----------------------------
```sql
-- Create tables
CREATE TABLE departments (
id INT PRIMARY KEY,
name VARCHAR(50),
location VARCHAR(100)
);

CREATE TABLE employees (


id INT PRIMARY KEY,
name VARCHAR(100),
department_id INT,
salary DECIMAL(10,2),
hire_date DATE,
FOREIGN KEY (department_id) REFERENCES departments(id)
);

-- Insert sample data


INSERT INTO departments VALUES
(1, 'IT', 'New York'),
(2, 'HR', 'Los Angeles'),
(3, 'Sales', 'Chicago');

INSERT INTO employees VALUES


(1, 'John Smith', 1, 75000, '2022-01-15'),
(2, 'Jane Doe', 2, 65000, '2021-03-20'),
(3, 'Bob Johnson', 1, 80000, '2020-11-10'),
(4, 'Alice Brown', 3, 70000, '2022-06-05');
```

Exercise 2: E-commerce Queries


-----------------------------
```sql
-- Tables: products, orders, order_items, customers

-- Find top-selling products


SELECT
p.name,
SUM(oi.quantity) as total_sold,
SUM(oi.quantity * oi.price) as total_revenue
FROM products p
JOIN order_items oi ON p.id = oi.product_id
GROUP BY p.id, p.name
ORDER BY total_sold DESC
LIMIT 10;

-- Find customers with most orders


SELECT
c.name,
COUNT(o.id) as order_count,
SUM(o.total_amount) as total_spent
FROM customers c
JOIN orders o ON c.id = o.customer_id
GROUP BY c.id, c.name
ORDER BY order_count DESC;
```

COMMON MISTAKES TO AVOID:


=========================

1. Forgetting to use GROUP BY with aggregate functions


2. Using HAVING instead of WHERE for row-level filtering
3. Not using table aliases in complex queries
4. Forgetting to handle NULL values
5. Using SELECT * in production queries
6. Not considering query performance

PERFORMANCE TIPS:
=================

1. Always use WHERE clauses before JOINs when possible


2. Use appropriate indexes on frequently queried columns
3. Limit result sets using LIMIT
4. Use EXPLAIN to understand query execution plans
5. Avoid subqueries when JOINs would be more efficient
6. Use appropriate data types for columns

You might also like