SQL INFO.
SQL is divided into several subsets, each serving a specific purpose for managing and manipulating
databases. Here's a comprehensive list of the subsets of SQL:
1. Data Query Language (DQL)
Used to retrieve data from a database.
Commands:
o SELECT
2. Data Definition Language (DDL)
Used to define and manage database structures and schemas.
Commands:
o CREATE
o ALTER
o DROP
o TRUNCATE
o RENAME
3. Data Manipulation Language (DML)
Used to manipulate data within database tables.
Commands:
o INSERT
o UPDATE
o DELETE
4. Data Control Language (DCL)
Used to control access to the database.
Commands:
o GRANT
o REVOKE
5. Transaction Control Language (TCL)
Used to manage database transactions.
Commands:
o COMMIT
o ROLLBACK
o SAVEPOINT
o SET TRANSACTION
6. Data Administration Commands
Not a formal subset, but related to managing database performance and user roles.
Commands:
o SHOW
o DESCRIBE (or DESC)
o EXPLAIN
Practical Example:
Scenario: You want to define a table, insert data, query it, and manage user permissions.
Use DDL to create a table.
Use DML to insert or update data.
Use DQL to retrieve data.
Use DCL to grant or revoke access.
Use TCL to commit or roll back changes.
1. DQL
Here’s the list of DQL topics:
1. SELECT Statement
2. Filtering Data (WHERE Clause)
3. Sorting Data (ORDER BY)
4. Limiting Rows (LIMIT and OFFSET)
5. Aggregate Functions:
o COUNT()
o SUM()
o AVG()
o MAX()
o MIN()
6. Grouping Data (GROUP BY)
7. Filtering Groups (HAVING)
8. Joins:
o INNER JOIN
o LEFT JOIN
o RIGHT JOIN
o FULL OUTER JOIN
9. Subqueries:
o In WHERE Clause
o In FROM Clause
10. Set Operations:
o UNION
o UNION ALL
11. Special Clauses:
o DISTINCT
o LIKE
o IN
o BETWEEN
Let me know if you'd like a detailed explanation of any topic!
DQL Subset Commands
DQL focuses on data retrieval, primarily revolving around the SELECT statement and its
accompanying clauses. Below are the commands and their subsets:
1. SELECT Command
Explanation: Used to fetch data from tables based on conditions or directly retrieve
all records.
Use Cases:
o Fetching specific rows or columns.
o Preparing data for analysis or reports.
Examples:
1. Fetch all rows and columns:
SELECT * FROM employees;
2. Fetch specific columns:
SELECT name, salary FROM employees;
3. Rename a column in the result:
SELECT name AS employee_name, salary AS monthly_salary FROM employees;
4. Use calculations:
SELECT name, salary * 12 AS annual_salary FROM employees;
5. Fetch distinct values:
SELECT DISTINCT department FROM employees;
Practice Questions:
1. Retrieve all employee names and their departments.
2. Fetch unique job titles from the employees table.
3. Calculate and display the yearly salary of all employees.
4. List the names of employees who work in the "HR" department.
5. Write a query to fetch all data from a table named students.
2. WHERE Clause
Explanation: Filters data based on specific conditions.
Use Cases:
o Narrowing down data to relevant rows.
o Applying logical and comparison operators.
Examples:
1. Filter rows with a condition:
SELECT * FROM employees WHERE department = 'Sales';
2. Combine multiple conditions:
SELECT * FROM employees WHERE salary > 50000 AND department = 'IT';
3. Use IN to match multiple values:
SELECT * FROM employees WHERE department IN ('Sales', 'Marketing');
4. Use BETWEEN for ranges:
SELECT * FROM employees WHERE age BETWEEN 25 AND 40;
5. Use LIKE for pattern matching:
SELECT * FROM employees WHERE name LIKE 'A%';
Practice Questions:
1. Write a query to find employees older than 30.
2. Retrieve records of employees who earn more than 60,000 but less than
1,00,000.
3. Fetch all products priced between 500 and 1500.
4. Find employees whose names start with the letter 'J'.
5. Write a query to exclude employees from the "Finance" department.
3. ORDER BY Clause
Explanation: Sorts the results in ascending or descending order.
Use Cases:
o Organizing data for readability.
o Sorting by numerical, textual, or date fields.
Examples:
1. Sort by one column (ascending by default):
SELECT * FROM employees ORDER BY salary;
2. Sort by one column in descending order:
SELECT * FROM employees ORDER BY salary DESC;
3. Sort by multiple columns:
SELECT * FROM employees ORDER BY department ASC, salary DESC;
4. Use expressions in sorting:
SELECT name, salary * 12 AS annual_salary FROM employees ORDER BY annual_salary DESC;
5. Sort by date:
SELECT * FROM employees ORDER BY joining_date ASC;
Practice Questions:
1. Sort all products by price in descending order.
2. Retrieve all employees sorted by their names alphabetically.
3. Write a query to sort students by their grades, highest first.
4. List all employees sorted by department, and then by salary within each
department.
5. Sort sales records by transaction date, newest first.
4. GROUP BY Clause
Explanation: Groups rows that have the same values into summary rows (e.g., sums,
averages).
Use Cases:
o Aggregating data based on categories.
o Summarizing numerical fields like SUM, AVG, etc.
Examples:
1. Group by a single column:
SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY
department;
2. Use multiple columns:
SELECT department, job_title, AVG(salary) FROM employees GROUP BY department,
job_title;
3. Combine with filtering:
SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department
HAVING avg_salary > 50000;
4. Group with a calculated field:
SELECT department, SUM(salary * 12) AS total_annual_salary FROM employees GROUP BY
department;
5. Combine with joins:
SELECT c.customer_id, SUM(o.amount) AS total_spent
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id;
Practice Questions:
1. Count the number of employees in each department.
2. Write a query to calculate the total salary of each department.
3. Fetch the average age of employees for each job title.
4. List all departments where the total salary exceeds 1,00,000.
5. Find the total sales made by each salesperson.
5. HAVING Clause
Explanation: Filters aggregated data after applying GROUP BY.
Use Cases:
o Applying conditions to grouped results.
o Filtering aggregates like sums or averages.
Examples:
1. Filter by aggregate value:
SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department
HAVING avg_salary > 50000;
2. Use multiple conditions:
SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY
department HAVING employee_count > 10 AND department != 'HR';
3. Use with aggregate functions:
SELECT job_title, MAX(salary) FROM employees GROUP BY job_title HAVING MAX(salary) >
70000;
4. Combine with subqueries:
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING total_salary > (SELECT AVG(salary) * 10 FROM employees);
5. Use with DISTINCT:
SELECT department, COUNT(DISTINCT job_title) AS unique_jobs
FROM employees
GROUP BY department
HAVING unique_jobs > 5;
Practice Questions:
1. Find all departments with an average salary above 60,000.
2. List job titles where the maximum salary exceeds 1,00,000.
3. Write a query to count employees in each department where the count
exceeds 15.
4. Fetch departments with a total salary less than 50,000.
5. Find customers who placed more than 10 orders.
Data for these operations: -
-- Create the employees table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(50),
department VARCHAR(50),
job_title VARCHAR(50),
salary DECIMAL(10, 2),
age INT,
joining_date DATE
);
-- Create the customers table
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(50),
city VARCHAR(50),
registration_date DATE
);
-- Create the orders table
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
amount DECIMAL(10, 2),
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
-- Insert data into the employees table
INSERT INTO employees (employee_id, name, department, job_title, salary, age,
joining_date)
VALUES
(1, 'Alice', 'HR', 'Manager', 60000, 35, '2020-01-15'),
(2, 'Bob', 'IT', 'Developer', 75000, 28, '2021-06-20'),
(3, 'Charlie', 'Sales', 'Salesperson', 50000, 30, '2019-09-01'),
(4, 'David', 'IT', 'Developer', 70000, 26, '2022-02-18'),
(5, 'Eve', 'Marketing', 'Executive', 55000, 29, '2018-12-12'),
(6, 'Frank', 'Sales', 'Manager', 85000, 40, '2017-11-03');
-- Insert data into the customers table
INSERT INTO customers (customer_id, name, city, registration_date)
VALUES
(1, 'John Doe', 'New York', '2021-05-01'),
(2, 'Jane Smith', 'Los Angeles', '2020-03-15'),
(3, 'Alice Johnson', 'Chicago', '2019-11-20'),
(4, 'Michael Brown', 'Houston', '2022-06-10');
-- Insert data into the orders table
INSERT INTO orders (order_id, customer_id, amount, order_date)
VALUES
(1, 1, 250.00, '2023-01-10'),
(2, 1, 400.00, '2023-03-15'),
(3, 2, 150.00, '2023-05-20'),
(4, 3, 300.00, '2023-07-25'),
(5, 4, 500.00, '2023-09-30');