SQL
SQL
Answer:
SQL (Structured Query Language) is a programming language used to
communicate with and manage data in relational databases. It allows
users to perform operations such as querying, updating, inserting, and
deleting data. SQL is also used to define and manipulate database
structures.
Types of SQL Commands:
1. DDL (Data Definition Language): Defines the database structure.
o Example: CREATE, ALTER, DROP
o CREATE TABLE employees (id INT, name VARCHAR(50));
2. DML (Data Manipulation Language): Manipulates data within
tables.
o Example: INSERT, UPDATE, DELETE
o INSERT INTO employees (id, name) VALUES (1, 'John');
3. DCL (Data Control Language): Controls access to data.
o Example: GRANT, REVOKE
o GRANT SELECT ON employees TO user;
4. TCL (Transaction Control Language): Manages transactions.
o Example: COMMIT, ROLLBACK
o BEGIN TRANSACTION; INSERT INTO employees (id, name)
VALUES (2, 'Jane'); COMMIT;
5. DQL (Data Query Language): Retrieves data from the database.
o Example: SELECT
o SELECT * FROM employees;
2. What is the difference between SQL and MySQL?
Answer:
Feature SQL MySQL
Definition A language for A relational database management
managing data. system (RDBMS) that uses SQL.
Purpose Used to write and A software tool that stores and
execute queries. manages databases.
Execution Cannot store data by Stores data and processes SQL
itself. commands.
Developer Standardized by Developed by Oracle Corporation.
ANSI.
Example:
• SQL command: SELECT * FROM employees;
• MySQL processes this command and retrieves the data.
-- Child table
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);
In this example:
• dept_id is the primary key in the departments table.
• dept_id in the employees table is a foreign key that references
departments.
6. What is a join in SQL? Explain different types of joins.
Answer:
A join in SQL is used to combine rows from two or more tables based on
a related column between them. It allows us to retrieve data from
multiple tables in a relational database.
Types of Joins:
1. INNER JOIN: Returns records that have matching values in both
tables.
2. LEFT JOIN (LEFT OUTER JOIN): Returns all records from the left
table and matched records from the right table. Unmatched rows
will contain NULL.
3. RIGHT JOIN (RIGHT OUTER JOIN): Returns all records from the
right table and matched records from the left table. Unmatched
rows will contain NULL.
4. FULL OUTER JOIN: Returns all records when there is a match in
either table. Unmatched rows from both tables are filled with NULL.
Example Dataset:
-- Table: employees
+----+----------+--------+
| id | name | deptId |
+----+----------+--------+
| 1 | Alice | 101 |
| 2 | Bob | 102 |
| 3 | Charlie | NULL |
+----+----------+--------+
-- Table: departments
+--------+---------------+
| deptId | deptName |
+--------+---------------+
| 101 | HR |
| 102 | IT |
| 103 | Finance |
+--------+---------------+
7. What is the difference between INNER JOIN and LEFT JOIN?
Answer:
Feature INNER JOIN LEFT JOIN
Definition Returns only Returns all rows from the left
matching rows from table and matching rows from
both tables. the right table.
Unmatched Not included in the Filled with NULL values in
Rows result set. columns of the right table.
INNER JOIN Example:
SELECT employees.name, departments.deptName
FROM employees
INNER JOIN departments
ON employees.deptId = departments.deptId;
Result:
+--------+---------+
| name | deptName|
+--------+---------+
| Alice | HR |
| Bob | IT |
+--------+---------+
LEFT JOIN Example:
SELECT employees.name, departments.deptName
FROM employees
LEFT JOIN departments
ON employees.deptId = departments.deptId;
Result:
+----------+---------+
| name | deptName|
+----------+---------+
| Alice | HR |
| Bob | IT |
| Charlie | NULL |
8. How does the RIGHT JOIN work in SQL?
Answer:
The RIGHT JOIN (or RIGHT OUTER JOIN) returns all rows from the
right table and matching rows from the left table. If there is no match,
NULL values are filled in columns of the left table.
Example:
SELECT employees.name, departments.deptName
FROM employees
RIGHT JOIN departments
ON employees.deptId = departments.deptId;
Result:
+----------+---------+
| name | deptName|
+----------+---------+
| Alice | HR |
| Bob | IT |
| NULL | Finance |
9. What is a full outer join? How is it different from other joins?
Answer:
A FULL OUTER JOIN combines the results of both LEFT and RIGHT
joins. It returns all rows when there is a match in either table and fills
unmatched rows with NULL in respective columns.
Differences from Other Joins:
Join Type Rows Returned
INNER Only matching rows from both tables.
LEFT All rows from the left table + matched rows.
RIGHT All rows from the right table + matched rows.
FULL All rows from both tables.
Example:
SELECT employees.name, departments.deptName
FROM employees
FULL OUTER JOIN departments
ON employees.deptId = departments.deptId;
Result:
+----------+---------+
| name | deptName|
+----------+---------+
| Alice | HR |
| Bob | IT |
| Charlie | NULL |
| NULL | Finance |
+----------+---------+
10. What is the UNION operator in SQL, and how is it different from
UNION ALL?
Answer:
The UNION operator combines the result sets of two or more SELECT
statements and removes duplicate rows. UNION ALL also combines
result sets but includes duplicates.
Key Differences:
Feature UNION UNION ALL
Duplicates Removes duplicate rows. Includes duplicate rows.
Performance Slower due to duplicate Faster as no duplicate
removal. check.
Example Tables:
-- Table: table1
+-----+
| col |
+-----+
|A |
|B |
|C |
+-----+
-- Table: table2
+-----+
| col |
+-----+
|B |
|C |
|D |
+-----+
UNION Example:
SELECT col FROM table1
UNION
SELECT col FROM table2;
Result:
+-----+
| col |
+-----+
|A |
|B |
|C |
|D |
+-----+
UNION ALL Example:
SELECT col FROM table1
UNION ALL
SELECT col FROM table2;
Result:
+-----+
| col |
+-----+
|A |
|B |
|C |
|B |
|C |
|D |
+-----+
WhatsApp: 91-9143407019
11. What is the GROUP BY clause used for?
Answer:
The GROUP BY clause is used to group rows that have the same values
in specified columns into summary rows, like calculating aggregate
functions such as SUM(), COUNT(), AVG(), etc.
Example:
We have a table sales:
-- Table: sales
+----------+---------+-------+
| category | product | sales |
+----------+---------+-------+
| Electronics | TV | 1000 |
| Electronics | Laptop | 1500 |
| Furniture | Chair | 300 |
| Furniture | Table | 700 |
| Electronics | Phone | 1200 |
+----------+---------+-------+
Query:
SELECT category, SUM(sales) AS total_sales
FROM sales
GROUP BY category;
Result:
+-------------+-------------+
| category | total_sales |
+-------------+-------------+
| Electronics | 3700 |
| Furniture | 1000 |
+-------------+-------------+
12. How is the COUNT() function used in SQL?
Answer:
The COUNT() function is used to return the number of rows that match a
specific condition or total rows in a table.
Example:
We have a table employees:
-- Table: employees
+----+----------+--------+
| id | name | deptId |
+----+----------+--------+
| 1 | Alice | 101 |
| 2 | Bob | 102 |
| 3 | Charlie | NULL |
| 4 | David | 101 |
| 5 | Eve | 102 |
+----+----------+--------+
Query 1: Count all employees:
SELECT COUNT(*) AS total_employees FROM employees;
Result:
+----------------+
| total_employees|
+----------------+
|5 |
+----------------+
Query 2: Count employees in department 101:
SELECT COUNT(*) AS employees_in_dept_101
FROM employees
WHERE deptId = 101;
Result:
+-----------------------+
| employees_in_dept_101 |
+-----------------------+
|2 |
+-----------------------+
13. What is the difference between WHERE and HAVING clauses?
Answer:
Feature WHERE HAVING
Purpose Filters rows before Filters groups after GROUP BY.
grouping.
Usage Can’t use aggregate Can use aggregate functions.
functions.
Query Works on raw data Works on aggregated data after
Level rows. grouping.
Example:
We have the same sales table.
-- Table: sales
+----------+---------+-------+
| category | product | sales |
+----------+---------+-------+
| Electronics | TV | 1000 |
| Electronics | Laptop | 1500 |
| Furniture | Chair | 300 |
| Furniture | Table | 700 |
| Electronics | Phone | 1200 |
+----------+---------+-------+
Query 1: Using WHERE:
SELECT product, sales
FROM sales
WHERE sales > 1000;
Result:
+---------+-------+
| product | sales |
+---------+-------+
| Laptop | 1500 |
| Phone | 1200 |
+---------+-------+
Query 2: Using HAVING:
SELECT category, SUM(sales) AS total_sales
FROM sales
GROUP BY category
HAVING total_sales > 1500;
Result:
+-------------+-------------+
| category | total_sales |
+-------------+-------------+
| Electronics | 3700 |
+-------------+-------------+
Khurshid MD Anwar
WhatsApp: 91-9143407019
14. What is the purpose of the DISTINCT keyword in SQL?
Answer:
The DISTINCT keyword is used to remove duplicate values from the
result set, ensuring each value is unique.
Example:
We have a table orders:
-- Table: orders
+----+----------+--------+
| id | customer | status |
+----+----------+--------+
| 1 | Alice | Shipped|
| 2 | Bob | Pending|
| 3 | Charlie | Shipped|
| 4 | Alice | Pending|
| 5 | Eve | Shipped|
+----+----------+--------+
Query: Get distinct statuses:
SELECT DISTINCT status
FROM orders;
Result:
+---------+
| status |
+---------+
| Shipped |
| Pending |
+---------+
15. How can you use the LIKE operator in SQL?
Answer:
The LIKE operator is used to search for a specified pattern in a column.
It often uses two wildcards:
• % to represent zero, one, or multiple characters.
• _ to represent a single character.
Example:
We have a table employees:
-- Table: employees
+----+----------+--------+
| id | name | deptId |
+----+----------+--------+
| 1 | Alice | 101 |
| 2 | Bob | 102 |
| 3 | Charlie | NULL |
| 4 | David | 101 |
| 5 | Eve | 102 |
+----+----------+--------+
Query 1: Names starting with "A":
SELECT name
FROM employees
WHERE name LIKE 'A%';
Result:
+-------+
| name |
+-------+
| Alice |
+-------+
Query 2: Names ending with "e":
SELECT name
FROM employees
WHERE name LIKE '%e';
Result:
+-------+
| name |
+-------+
| Alice |
| Eve |
+-------+
Query 3: Names with second letter "o":
SELECT name
FROM employees
WHERE name LIKE '_o%';
Result:
+------+
| name |
+------+
| Bob |
+------+
Khurshid MD Anwar
WhatsApp: 91-9143407019
16. Explain the difference between the AND and OR operators in
SQL.
Answer:
The AND and OR operators are used in SQL to combine multiple
conditions in a query.
Feature AND OR
Functionality All conditions must be At least one condition must
true for the row to be be true for the row to be
included. included.
Use Case Used for narrowing Used for broadening results
results (more restrictive). (less restrictive).
Effect Results are fewer due to Results are more due to
stricter criteria. relaxed criteria.
Example:
We have a table employees:
-- Table: employees
+----+----------+--------+------+
| id | name | deptId | age |
+----+----------+--------+------+
| 1 | Alice | 101 | 30 |
| 2 | Bob | 102 | 35 |
| 3 | Charlie | 103 | 40 |
| 4 | David | 101 | 45 |
| 5 | Eve | 102 | 50 |
+----+----------+--------+------+
Query using AND: Find employees in department 101 and older than
40.
SELECT name, deptId, age FROM employees WHERE deptId = 101
AND age > 40;
Result:
+-------+--------+-----+
| name | deptId | age |
+-------+--------+-----+
| David | 101 | 45 |
+-------+--------+-----+
Query using OR: Find employees in department 101 or older than 40.
SELECT name, deptId, age
FROM employees
WHERE deptId = 101 OR age > 40;
Result:
+-------+--------+-----+
| name | deptId | age |
+-------+--------+-----+
| Alice | 101 | 30 |
| Charlie | 103 | 40 |
| David | 101 | 45 |
| Eve | 102 | 50 |
+-------+--------+-----+
Khurshid MD Anwar
WhatsApp: 91-9143407019
17. What is a subquery in SQL? How is it used?
Answer:
A subquery is a query nested inside another query. It can be used to
perform intermediate calculations or fetch data to be used in the outer
query.
Features:
• A subquery is enclosed in parentheses.
• It can return a single value, multiple values, or a table.
• Commonly used with SELECT, INSERT, UPDATE, or DELETE.
Example:
We have tables employees and departments:
-- Table: employees
+----+----------+--------+
| id | name | deptId |
+----+----------+--------+
| 1 | Alice | 101 |
| 2 | Bob | 102 |
| 3 | Charlie | 103 |
+----+----------+--------+
-- Table: departments
+--------+-------------+
| deptId | deptName |
+--------+-------------+
| 101 | HR |
| 102 | Sales |
+--------+-------------+
Query: Find names of employees who work in the "Sales" department.
SELECT name
FROM employees
WHERE deptId = (
SELECT deptId
FROM departments
WHERE deptName = 'Sales'
);
Result:
+------+
| name |
+------+
| Bob |
+------+
Khurshid MD Anwar
WhatsApp: 91-9143407019
18. What is the difference between a correlated subquery and a
non-correlated subquery?
Feature Correlated Subquery Non-Correlated Subquery
Dependency Depends on the outer Independent of the outer
query for its values. query.
Execution Executed repeatedly for Executed once and the
each row of the outer result is used in the outer
query. query.
Performance Slower due to repeated Faster as it is executed only
execution. once.
Example:
Correlated Subquery:
Find employees whose salary is greater than the average salary in their
department:
SELECT e1.name, e1.salary
FROM employees e1
WHERE e1.salary > ( SELECT AVG(e2.salary) FROM employees e2
WHERE e1.deptId = e2.deptId);
Non-Correlated Subquery:
Find employees who belong to department 101:
SELECT name
FROM employees
WHERE deptId IN (SELECT deptId FROM departments WHERE
deptName = 'HR');
Khurshid MD Anwar
WhatsApp: 91-9143407019
19. How does the ORDER BY clause work in SQL?
Answer:
The ORDER BY clause is used to sort the result set in ascending (ASC)
or descending (DESC) order based on one or more columns.
Features:
• Defaults to ascending order if not specified.
• Multiple columns can be used for sorting.
Example:
We have a table students:
-- Table: students
+----+--------+-----+
| id | name | age |
+----+--------+-----+
| 1 | Alice | 20 |
| 2 | Bob | 22 |
| 3 | Charlie| 19 |
+----+--------+-----+
Query 1: Sort students by age in ascending order:
SELECT name, age
FROM students
ORDER BY age ASC;
Result:
+---------+-----+
| name | age |
+---------+-----+
| Charlie | 19 |
| Alice | 20 |
| Bob | 22 |
+---------+-----+
Query 2: Sort students by age in descending order:
SELECT name, age
FROM students
ORDER BY age DESC;
Result:
+---------+-----+
| name | age |
+---------+-----+
| Bob | 22 |
| Alice | 20 |
| Charlie | 19 |
+---------+-----+
20. What are aggregate functions in SQL? List a few common ones.
Answer:
Aggregate functions perform calculations on multiple rows of data and
return a single value.
Aggregate Description Example Query
Function
COUNT() Counts the number of SELECT COUNT(*)
rows. FROM employees;
SUM() Calculates the total sum SELECT SUM(salary)
of a column. FROM employees;
AVG() Calculates the average SELECT AVG(salary)
value of a column. FROM employees;
MAX() Finds the maximum value SELECT MAX(salary)
in a column. FROM employees;
MIN() Finds the minimum value SELECT MIN(salary)
in a column. FROM employees;
Example:
We have a table employees:
-- Table: employees
+----+----------+--------+
| id | name | salary |
+----+----------+--------+
| 1 | Alice | 5000 |
| 2 | Bob | 7000 |
| 3 | Charlie | 6000 |
+----+----------+--------+
Query: Calculate aggregate values for salaries:
SELECT
COUNT(*) AS total_employees,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary,
MAX(salary) AS max_salary,
MIN(salary) AS min_salary
FROM employees;
Result:
+----------------+-------------+---------------+------------+------------+
| total_employees| total_salary| average_salary| max_salary | min_salary
|
+----------------+-------------+---------------+------------+------------+
|3 | 18000 | 6000 | 7000 | 5000 |
+----------------+-------------+---------------+------------+------------+
21. Explain the use of the LIMIT clause in SQL.
Answer:
The LIMIT clause in SQL is used to restrict the number of rows returned
by a query.
• Purpose:
o Fetches a subset of rows from a result set.
o Useful for pagination or testing queries.
• Syntax:
SELECT columns
FROM table
LIMIT number_of_rows;
• Optional OFFSET:
o Used with LIMIT to skip a specified number of rows before
starting to return results.
o Syntax:
SELECT columns
FROM table
LIMIT number_of_rows OFFSET offset_value;
Example:
We have a table students:
-- Table: students
+----+----------+-----+
| id | name | age |
+----+----------+-----+
| 1 | Alice | 20 |
| 2 | Bob | 22 |
| 3 | Charlie | 21 |
| 4 | David | 23 |
| 5 | Eve | 19 |
+----+----------+-----+
Query: Fetch the first 3 rows:
SELECT name, age
FROM students
LIMIT 3;
Result:
+----------+-----+
| name | age |
+----------+-----+
| Alice | 20 |
| Bob | 22 |
| Charlie | 21 |
+----------+-----+
Query with OFFSET: Skip the first 2 rows and fetch the next 2 rows:
SELECT name, age
FROM students
LIMIT 2 OFFSET 2;
Result:
+----------+-----+
| name | age |
+----------+-----+
| Charlie | 21 |
| David | 23 |
+----------+-----+
22. What is a view in SQL? How is it different from a table?
Answer:
A view in SQL is a virtual table based on the result set of a query. It does
not store data physically but fetches it dynamically from the underlying
tables.
Feature View Table
Definition A saved SQL query treated as A database object that
a table. stores data physically.
Storage No physical storage for data. Physically stores data in
rows and columns.
Modifiability Limited (depends on the SQL Fully modifiable
implementation). (INSERT, UPDATE,
DELETE).
Use Case Simplifies complex queries Stores actual data.
and enhances security.
Syntax:
CREATE VIEW view_name AS
SELECT columns
FROM table
WHERE condition;
Example:
We have a table employees:
-- Table: employees
+----+----------+--------+
| id | name | deptId |
+----+----------+--------+
| 1 | Alice | 101 |
| 2 | Bob | 102 |
| 3 | Charlie | 101 |
+----+----------+--------+
Create a View: View to fetch employees from department 101:
CREATE VIEW dept101_employees AS
SELECT name
FROM employees
WHERE deptId = 101;
Query the View:
SELECT * FROM dept101_employees;
Result:
+----------+
| name |
+----------+
| Alice |
| Charlie |
+----------+
Disclaimer:
The information shared in this EBook is based on my knowledge and
experience. While I strive for accuracy, errors or mistakes may occur.
Some details may vary depending on individual use cases or evolving
practices. Please verify independently before making decisions based on
this content. Thank you for your understanding!