Here are one-liner example queries for each point:
1. **`SELECT`**:
```sql
SELECT name FROM employee;
```
2. **`SELECT ALL`**:
```sql
SELECT * FROM employee;
```
3. **`WHERE`**:
```sql
SELECT name FROM employee WHERE salary > 50000;
```
4. **`DISTINCT`**:
```sql
SELECT DISTINCT department FROM employee;
```
5. **`ORDER BY`**:
```sql
SELECT name, salary FROM employee ORDER BY salary DESC;
```
6. **`AND`**:
```sql
SELECT name FROM employee WHERE department = 'HR' AND salary > 40000;
```
7. **`OR`**:
```sql
SELECT name FROM employee WHERE department = 'HR' OR salary > 40000;
```
8. **`NOT`**:
```sql
SELECT name FROM employee WHERE NOT department = 'HR';
```
9. **`INSERT INTO` multiple values**:
```sql
INSERT INTO employee (name, department, salary) VALUES ('John', 'IT',
50000), ('Jane', 'HR', 60000);
```
10. **`IS NULL`**:
```sql
SELECT name FROM employee WHERE manager_id IS NULL;
```
11. **`MIN`**:
```sql
SELECT MIN(salary) AS MinSalary FROM employee;
```
12. **`IN`**:
```sql
SELECT name FROM employee WHERE department IN ('HR', 'IT', 'Finance');
```
13. **`BETWEEN`**:
```sql
SELECT name FROM employee WHERE salary BETWEEN 30000 AND 60000;
```
14. **`GROUP BY`**:
```sql
SELECT department, COUNT(*) AS TotalEmployees FROM employee GROUP BY
department;
```
15. **`HAVING`**:
```sql
SELECT department, AVG(salary) AS AvgSalary FROM employee GROUP BY
department HAVING AVG(salary) > 50000;
```
16. **`CREATE TABLE`**:
```sql
CREATE TABLE employee (id INT PRIMARY KEY, name VARCHAR(50), salary
INT);
```
17. **`ALTER TABLE ADD COLUMN`**:
```sql
ALTER TABLE employee ADD COLUMN age INT;
```
18. **`DELETE COLUMN`** (not directly supported in all databases; use drop
column):
```sql
ALTER TABLE employee DROP COLUMN age;
```
19. **`UPDATE SET`**:
```sql
UPDATE employee SET salary = salary + 5000 WHERE department = 'HR';
```
20. **`LIKE` (start, end, contain)**:
- **Starts with**:
```sql
SELECT name FROM employee WHERE name LIKE 'J%';
```
- **Ends with**:
```sql
SELECT name FROM employee WHERE name LIKE '%n';
```
- **Contains**:
```sql
SELECT name FROM employee WHERE name LIKE '%an%';
```
#1. Write an SQL query to retrieve the second highest salary from the employee
table.
SELECT MAX(salary) AS SecondHighestSalary
FROM employee
WHERE salary < (SELECT MAX(salary) FROM employee);
- Explanation:
- The subquery finds the highest salary.
- The outer query finds the maximum salary below the highest salary.
SELECT DISTINCT salary AS SecondHighestSalary
FROM employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
#### **2. Explain the difference between INNER JOIN and LEFT JOIN.**
- **INNER JOIN**:
- Returns only rows where there is a match in both tables.
- Example:
SELECT *
FROM table1
INNER JOIN table2
ON table1.id = table2.id;
```
- **LEFT JOIN**:
- Returns all rows from the left table and the matched rows from the right
table. If no match exists, NULL values are returned for the right table's columns.
- Example:
```sql
SELECT *
FROM table1
LEFT JOIN table2
ON table1.id = table2.id;
```
#### **3. How do you optimize a SQL query?**
- Use indexing for frequently queried columns.
- Minimize the use of `SELECT *` by specifying required columns.
- Avoid using subqueries if a JOIN can be used.
- Optimize `WHERE` clauses by filtering rows efficiently.
- Use proper database normalization.
- Analyze query execution plans to identify bottlenecks.
- Avoid unnecessary joins and DISTINCT if not required.
---
#### **4. What is the difference between the DROP and TRUNCATE
commands?**
- **DROP**:
- Deletes the entire table and its structure from the database.
- Cannot be rolled back.
- Example:
```sql
DROP TABLE table_name;
```
- **TRUNCATE**:
- Deletes all rows from the table but keeps its structure intact.
- Cannot be rolled back in most systems.
- Example:
```sql
TRUNCATE TABLE table_name;
#### **5. How would you add a new column to an existing table? What if you
want to set a default value?**
- Add a new column:
```sql
ALTER TABLE table_name
ADD column_name datatype;
```
- Add a new column with a default value:
```sql
ALTER TABLE table_name
ADD column_name datatype DEFAULT default_value;
#### **6. How do you insert multiple rows into a table in a single query?**
```sql
INSERT INTO table_name (column1, column2)
VALUES (value1a, value2a), (value1b, value2b), (value1c, value2c);
#### **7. What is the importance of ACID properties in transactions?**
- **Atomicity**: Ensures all operations in a transaction are completed;
otherwise, none are applied.
- **Consistency**: Ensures the database remains in a consistent state before
and after a transaction.
- **Isolation**: Ensures transactions are processed independently without
interference.
- **Durability**: Guarantees that committed transactions are saved
permanently.
#### **8. What is the difference between the IN and EXISTS operators?**
- **IN**:
- Checks if a value exists in a specified set of values or subquery result.
- Example:
```sql
SELECT *
FROM employee
WHERE department_id IN (1, 2, 3);
```
- **EXISTS**:
- Checks if a subquery returns any rows.
- Example:
```sql
SELECT *
FROM employee e
WHERE EXISTS (
SELECT 1
FROM department d
WHERE d.id = e.department_id
);
#### **9. What is the difference between scalar and aggregate functions in
SQL?**
- **Scalar Functions**:
- Operate on a single value and return a single value.
- Example: `UPPER(column_name)`, `ROUND(value)`.
- Usage:
```sql
SELECT UPPER(name) AS UpperCaseName FROM employee;
```
- **Aggregate Functions**:
- Operate on multiple values and return a single aggregated value.
- Example: `SUM(column_name)`, `AVG(column_name)`.
- Usage:
```sql
SELECT AVG(salary) AS AverageSalary FROM employee;
```
#### **10. How do you perform string concatenation in MySQL?**
- Use the `CONCAT` function:
```sql
SELECT CONCAT(first_name, ' ', last_name) AS FullName FROM employee;
#### **11. What is the LIMIT clause used for in SQL queries? Provide an
example.**
- **LIMIT**: Restricts the number of rows returned by a query.
- Example:
```sql
SELECT *
FROM employee
ORDER BY salary DESC
LIMIT 5;
```
- Retrieves the top 5 highest-paid employees.
#### **12. What is a SELF JOIN and when would you use it?**
- A **SELF JOIN** is a join where a table is joined with itself.
- Use it to compare rows within the same table.
- Example:
```sql
SELECT e1.name AS Employee1, e2.name AS Employee2
FROM employee e1, employee e2
WHERE e1.manager_id = e2.id;
```
- Retrieves employees and their managers from the same table.
#### **13. What is the difference between JOIN and UNION?**
- **JOIN**:
- Combines rows from two or more tables based on related columns.
- Example:
```sql
SELECT e.name, d.department_name
FROM employee e
JOIN department d
ON e.department_id = d.id;
```
- **UNION**:
- Combines results of two or more `SELECT` queries into a single result set and
removes duplicates by default.
- Example:
SELECT name FROM employee
UNION
SELECT name FROM manager;
### **14. What is the use of indexes in SQL, and how do they improve query
performance?**
Indexes are used to speed up the retrieval of data from a database. They allow
the database to quickly locate the rows that satisfy a query condition without
scanning the entire table. Indexes improve performance in queries with
`WHERE`, `JOIN`, and `ORDER BY` clauses by reducing the number of rows the
database engine needs to process.
---
### **15. How would you retrieve the top N rows in SQL?**
To retrieve the top N rows, you can use the `LIMIT` clause (in MySQL or
PostgreSQL) or the `TOP` keyword (in SQL Server). These limit the number of
rows returned by a query. In Oracle, you can use `ROWNUM` or `FETCH FIRST N
ROWS ONLY`.
---
### **16. Explain the concept of normalization and its advantages.**
Normalization is the process of organizing database tables to reduce redundancy
and improve data integrity. It involves dividing data into smaller, related tables
and applying rules like 1NF, 2NF, and 3NF.
Advantages include reduced data duplication, improved consistency, better
query performance, and easier database maintenance.
---
### **17. What is a primary key, and why is it important?**
A primary key is a column (or combination of columns) that uniquely identifies
each row in a table. It ensures there are no duplicate or null values. Primary keys
are essential for maintaining data integrity and creating relationships between
tables.
---
### **18. What is a foreign key, and how does it maintain referential
integrity?**
A foreign key is a column in one table that refers to the primary key in another
table. It maintains referential integrity by ensuring that a value in the foreign
key column matches an existing value in the referenced primary key, thereby
maintaining valid relationships between tables.
---
### **19. What is the difference between GROUP BY and ORDER BY?**
`GROUP BY` is used to group rows with the same values into summary rows,
often with aggregate functions like `SUM` or `COUNT`.
`ORDER BY` is used to sort the rows of a query result in ascending or descending
order.
---
### **20. What is the difference between HAVING and WHERE clauses in
SQL?**
The `WHERE` clause filters rows before any grouping is applied. It is used for
individual rows.
The `HAVING` clause filters groups after they have been created by the `GROUP
BY` clause. It is often used with aggregate functions.
### **1. What is a View?**
A **view** is a virtual table in SQL that is based on a SELECT query. It doesn’t
store data itself but provides a way to simplify complex queries and reuse them.
- **Example**:
```sql
CREATE VIEW EmployeeSalary AS
SELECT name, salary FROM employee WHERE salary > 50000;
```
---
### **2. What is a Stored Procedure?**
A **stored procedure** is a precompiled set of SQL statements that can be
executed as a single unit. It allows reusable and modular SQL logic.
- **Example**:
```sql
CREATE PROCEDURE IncreaseSalary(IN percentage INT)
BEGIN
UPDATE employee SET salary = salary + (salary * percentage / 100);
END;
```
---
### **3. What is a Trigger?**
A **trigger** is a special type of stored procedure that automatically executes
in response to certain events (INSERT, UPDATE, DELETE) on a table.
- **Example**:
```sql
CREATE TRIGGER BeforeInsertTrigger
BEFORE INSERT ON employee
FOR EACH ROW
SET NEW.salary = IF(NEW.salary < 30000, 30000, NEW.salary);
```
---
### **4. What is Normalization and its Types?**
**Normalization** is the process of structuring a database to reduce
redundancy and dependency by dividing data into smaller related tables.
- **Types of Normalization**:
1. **First Normal Form (1NF)**: Ensures that all columns have atomic values
(no repeating groups or arrays).
2. **Second Normal Form (2NF)**: Ensures all non-primary key attributes are
fully functionally dependent on the primary key.
3. **Third Normal Form (3NF)**: Ensures no transitive dependencies (non-
primary attributes depend only on the primary key).
4. **Boyce-Codd Normal Form (BCNF)**: Ensures stricter conditions than 3NF
for functional dependency.
---
### **5. What is a Database?**
A **database** is an organized collection of data that can be easily accessed,
managed, and updated. It is stored and managed by a database management
system (DBMS).
- Examples: MySQL, PostgreSQL, Oracle.
---
### **6. What is a Schema?**
A **schema** is the structure of a database that defines how data is organized,
including tables, views, indexes, procedures, and relationships. It serves as a
blueprint for the database.
- Example: A database can have a schema defining tables like `employee` and
`department`.
---
### **7. What are Constraints in SQL?**
**Constraints** are rules enforced on columns in a table to ensure the integrity
and accuracy of the data.
- **Types of Constraints**:
1. **PRIMARY KEY**: Ensures unique and non-null values for the column.
2. **FOREIGN KEY**: Ensures referential integrity between two tables.
3. **UNIQUE**: Ensures all values in a column are unique.
4. **NOT NULL**: Ensures the column cannot contain null values.
5. **CHECK**: Ensures values satisfy a specified condition.
6. **DEFAULT**: Assigns a default value to the column if no value is provided.
- **Example**:
```sql
CREATE TABLE employee (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
salary INT CHECK (salary > 0),
department_id INT,
FOREIGN KEY (department_id) REFERENCES department(id)
);
```