MySQL: Downloading, Configuring, and
Understanding Databases
1. Introduction to Databases
What is a Database?
Many people overcomplicate the definition of a database, leaving us confused. Simply put, a database is a
software that stores data permanently in a structured way.
● If we store data in variables, it is temporary because variables are created in RAM (Random Access
Memory).
● However, if we want data to be saved permanently, we need a database.
Example:
Suppose we want to store usernames and passwords. If we store them in variables, they will be lost when the
program stops running. Instead, we should store them in a database so they remain available even after the system
is restarted.
Types of Databases
There are several types of databases available:
● Relational Databases (SQL-based): MySQL, Oracle, PostgreSQL, DB2
● NoSQL Databases: MongoDB, HSQL
Each has its own use case, but we will focus on MySQL.
2. Why Do We Need SQL?
In any application, when we enter data into a form (e.g., a registration form), that data needs to be stored in a
database.
● For example, when a user enters First Name, Last Name, Mobile Number, Email ID and clicks Save, that
data must be stored in the database.
● If the data is not stored correctly, it leads to bad data, making it useless.
● Example: If a platform like Shadi.com is storing user data but fails to save the phone number, the platform
cannot contact users, making all the marketing efforts wasted.
Thus, SQL (Structured Query Language) is required to interact with the database and ensure that data is stored
and retrieved correctly.
3. Installing and Configuring MySQL
To use MySQL, we need to install it on our system.
Installation Methods:
1. Direct MySQL Download (Manual Installation)
○ Download MySQL from the official website and install it manually.
2. Using XAMPP (Recommended for Practice)
○ XAMPP is a software package that includes MySQL, Apache Server, and PHPMyAdmin.
○ It provides an easy way to install and manage MySQL using a graphical interface.
Steps to Install XAMPP
1. Download XAMPP
○ Open Google and search for “Download XAMPP”
○ Click the official download link and install XAMPP on your system.
2. Installation Process
○ Run the installer
○ Click Next → Next → Finish
○ XAMPP is now installed.
3. Starting MySQL
○ Open the XAMPP Control Panel.
○ Start Apache and MySQL.
○ Verify that MySQL is running.
Understanding Ports:
● MySQL runs on port 3306 (by default).
● Apache runs on port 8443 (for web servers).
4. Accessing MySQL via PHPMyAdmin
Once MySQL is installed via XAMPP, we can access it using PHPMyAdmin:
Open a browser and type:
http://localhost
1.
2. Click on “PHPMyAdmin”
3. You can now create and manage databases through the graphical interface.
5. Creating a Database and Table
To store data, we need to create:
1. A Database
2. A Table inside the database
Steps to Create a Database:
1. Open PHPMyAdmin
2. Click “New” → Enter Database Name → Click Create
○ Example: Create a database named "TestingCampus"
Creating a Table in the Database
● Inside the "TestingCampus" database, create a table called "Employee" with 4 columns:
Column Name Data Type Description
Employee ID INT Unique identifier for employees
Name VARCHAR(20) Employee name (text)
City VARCHAR(20) City name (text)
Salary INT Employee salary (integer)
1. Click on "New Table"
2. Enter Table Name: Employee
3. Define columns as follows:
○ EID (INT)
○ EName (VARCHAR(20))
○ City (VARCHAR(20))
○ Salary (INT)
4. Click Save.
○ The Employee table is now created.
6. Inserting Data into the Table
Once the table is created, we can insert data manually through PHPMyAdmin.
Steps to Insert Data:
1. Open the Employee Table
2. Click "Insert"
Enter data:
EID: 100
EName: Smith
City: Bangalore
Salary: 10,000
3.
4. Click Go → Data is inserted.
Repeat for multiple entries:
EID: 101 | EName: Karl | City: Bangalore | Salary: 12,000
EID: 102 | EName: Ravi | City: Chennai | Salary: 12,000
EID: 103 | EName: Ajay | City: Delhi | Salary: 5,000
EID: 104 | EName: Vikram | City: Pune | Salary: 2,000
5.
6. Click Search to view inserted data.
7. Writing SQL Queries via Command Prompt
Instead of using PHPMyAdmin, we should practice using the Command Prompt (CMD).
Connecting MySQL to Command Prompt
1. Open XAMPP Control Panel
2. Ensure MySQL is started
3. Open Command Prompt (CMD)
Navigate to MySQL bin folder:
cd C:\xampp\mysql\bin
4.
Login to MySQL:
mysql -u root -p
5. (Press Enter, no password is required by default in XAMPP.)
Executing Queries in CMD
Creating a Database
CREATE DATABASE TestingCampus;
Using the Database
USE TestingCampus;
Creating the Employee Table
CREATE TABLE Employee (
EID INT PRIMARY KEY,
EName VARCHAR(20),
City VARCHAR(20),
Salary INT
);
Inserting Data
INSERT INTO Employee VALUES (100, 'Smith', 'Bangalore', 10000);
INSERT INTO Employee VALUES (101, 'Karl', 'Bangalore', 12000);
INSERT INTO Employee VALUES (102, 'Ravi', 'Chennai', 12000);
INSERT INTO Employee VALUES (103, 'Ajay', 'Delhi', 5000);
INSERT INTO Employee VALUES (104, 'Vikram', 'Pune', 2000);
Retrieving Data
SELECT * FROM Employee;
This will display all employees stored in the table.
8. Summary
✅ Database stores data permanently
✅ MySQL is a relational database for structured storage
✅ XAMPP is an easy way to install and manage MySQL
✅ PHPMyAdmin provides a GUI for managing databases
✅ Command Prompt helps practice writing SQL queries
Here’s your cleaned-up and structured version of the transcript:
Connecting to MySQL Database Using Command
Prompt
Step 1: Open Command Prompt and Navigate to MySQL Bin Folder
1. Open the Command Prompt (CMD).
Navigate to the bin folder of MySQL by running:
cd <path-to-mysql-bin-folder>
Example:
cd C:\Program Files\MySQL\MySQL Server 8.0\bin
2.
Step 2: Connect to MySQL
Enter the following command to log in to MySQL:
mysql -u root
1.
○ -u root specifies the username (root by default).
○ By default, there is no password for practice purposes.
2. Press Enter to establish a connection with MySQL.
Step 3: Show Available Databases
To list all available databases, run:
SHOW DATABASES;
Step 4: Select a Database
To connect to a specific database, use:
USE testing_campus;
● This command switches the current database to testing_campus.
● You will see the message "Database changed" upon successful selection.
Step 5: Show Available Tables
To see the tables inside the database, run:
SHOW TABLES;
Example output:
+-----------------+
| Tables_in_testing_campus |
+-----------------+
| employee |
+-----------------+
● The table employee is available in the selected database.
Basic SQL Queries for Retrieving Data
1. Read All Data from a Table
SELECT * FROM employee;
● * means selecting all columns from the employee table.
2. Read Specific Columns from a Table
Example: Retrieve only Employee ID and Name:
SELECT eid, ename FROM employee;
● This fetches only the eid and ename columns.
3. Filter Data with WHERE Clause
Example: Retrieve employees with a salary of 10,000:
SELECT ename FROM employee WHERE salary = 10000;
● This fetches only the ename where salary is 10,000.
4. Filter Data Using Greater Than or Equal To
Example: Retrieve employees with a salary of 10,000 or more:
SELECT ename FROM employee WHERE salary >= 10000;
5. Use the IN Operator to Match Multiple Values
Example: Retrieve employees with salaries 5,000 or 2,000:
SELECT ename FROM employee WHERE salary IN (5000, 2000);
● This selects employees where salary is either 5,000 or 2,000.
6. Retrieve Employee ID for Specific Names
Example: Retrieve eid where ename is "Smith" or "Carl":
SELECT eid FROM employee WHERE ename IN ('Smith', 'Carl');
● The IN operator helps in filtering multiple names.
7. Sort Data in Descending Order
Example: Retrieve eid in descending order:
SELECT eid FROM employee ORDER BY eid DESC;
● ORDER BY sorts the results; DESC sorts in descending order.
Golden Rule of SQL - Structured Query Order
Whenever you write SQL queries, maintain this order:
1. SELECT - Choose the columns.
2. FROM - Specify the table.
3. WHERE - Apply filters.
4. GROUP BY - Group results.
5. HAVING - Apply conditions after grouping.
6. ORDER BY - Sort the results.
Example of correct syntax:
SELECT ename FROM employee WHERE salary >= 10000 ORDER BY ename;
● Correct Order: SELECT → FROM → WHERE → ORDER BY.
Example of incorrect syntax:
SELECT ename FROM employee ORDER BY ename WHERE salary >= 10000;
● Incorrect Order: ORDER BY should come after WHERE.
Practice Exercise
Try writing queries for the following:
1. Retrieve employee IDs in ascending order.
2. Retrieve employees whose salary is NOT 5,000 or 2,000.
3. Retrieve employee names that start with 'S'.
Corrected and Structured Notes from the SQL Lecture
Filtering Records in SQL
1. Two ways to filter records in SQL:
○ WHERE (Used for filtering individual records before grouping)
○ HAVING (Used for filtering grouped records)
2. Syntax Rules:
○ WHERE is used before GROUP BY
○ HAVING is used after GROUP BY
○ If using both WHERE and HAVING, WHERE comes first.
Examples:
-- Using WHERE
SELECT * FROM employee WHERE salary = 10000;
-- Using HAVING (incorrect syntax)
SELECT * FROM employee HAVING salary = 10000; -- ❌ Incorrect
-- Correct usage of HAVING
SELECT employee_id FROM employee GROUP BY employee_id HAVING salary = 10000;
3.
Example Query (Using HAVING instead of WHERE)
SELECT employee_id FROM employee HAVING ename = 'Vikram';
4.
○ This works syntactically but is incorrect logically because HAVING should be used with GROUP BY.
Sorting Data in SQL
1. Sorting Syntax:
○ ORDER BY is used to sort records.
○ ORDER BY must always be the last clause in the query.
Sorting Examples:
-- Sorting Employee IDs in Descending Order
SELECT employee_id FROM employee ORDER BY employee_id DESC;
-- Sorting Employee Names in Descending Order
SELECT ename FROM employee ORDER BY ename DESC;
-- Sorting Employee IDs in Ascending Order
SELECT employee_id FROM employee ORDER BY employee_id ASC;
2.
3. SQL Query Order:
○ SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY
○ If you remember this order, writing queries becomes easier.
Built-in Functions in SQL
Finding Maximum Salary
SELECT MAX(salary) FROM employee;
1.
Finding Minimum Salary
SELECT MIN(salary) FROM employee;
2.
Finding Average Salary
SELECT AVG(salary) FROM employee;
3.
Finding Sum of Salaries
SELECT SUM(salary) FROM employee;
4.
Counting Employees
SELECT COUNT(employee_id) FROM employee;
5.
Grouping Data Using GROUP BY
Counting Employees City-wise
SELECT city, COUNT(employee_id) FROM employee GROUP BY city;
1.
○ This groups employees based on their city and counts them.
2. Grouping Explanation:
○ GROUP BY groups rows that have the same values in specified columns.
Example:
+---------+-----------+
| City | Employee Count |
+---------+-----------+
| Mumbai | 5 |
| Delhi | 3 |
| Bangalore | 7 |
+---------+-----------+
○
○ It creates logical groups before applying aggregate functions.
Key Takeaways
● Filtering: Use WHERE for individual records, HAVING for grouped records.
● Sorting: ORDER BY should be the last clause.
● Built-in Functions: MAX(), MIN(), AVG(), SUM(), and COUNT().
● Grouping: GROUP BY is used to organize data into groups before applying aggregate functions.
Here are the key SQL concepts covered in your lecture:
1. GROUP BY and COUNT
Basic GROUP BY Query:
SELECT city, COUNT(emp_id)
FROM employee
GROUP BY city;
●
○ Groups employees based on city and counts the number of employees per city.
GROUP BY with ORDER BY (Ascending Count Order):
SELECT city, COUNT(emp_id)
FROM employee
GROUP BY city
ORDER BY COUNT(emp_id);
●
○ Groups employees by city and orders the result based on the count (default is ascending).
GROUP BY with ORDER BY (Descending Count Order):
SELECT city, COUNT(emp_id)
FROM employee
GROUP BY city
ORDER BY COUNT(emp_id) DESC;
●
○ Groups employees by city and orders the result based on count in descending order.
2. HAVING Clause
Filtering after GROUP BY using HAVING:
SELECT city, COUNT(emp_id)
FROM employee
GROUP BY city
HAVING city = 'Bangalore';
●
○ Filters records after grouping, showing only employees from Bangalore.
3. GROUP BY with Different Columns
Grouping by Age:
SELECT age, COUNT(emp_id)
FROM employee
GROUP BY age;
●
○ Counts how many employees belong to each age group.
Grouping by Salary:
SELECT salary, COUNT(emp_id)
FROM employee
GROUP BY salary;
●
○ Counts the number of employees per salary.
4. UPPERCASE & LOWERCASE Conversion
Convert Employee Names to Uppercase:
SELECT UCASE(ename) FROM employee;
●
Convert Employee Names to Lowercase:
SELECT LCASE(ename) FROM employee;
●
5. Additional Aggregate Functions
Find Maximum Salary:
SELECT MAX(salary) FROM employee;
●
Find Minimum Salary:
SELECT MIN(salary) FROM employee;
●
Find Average Salary:
SELECT AVG(salary) FROM employee;
●
Find Total Salary Paid:
SELECT SUM(salary) FROM employee;
●
Here are the notes from the lecture, maintaining the detailed explanation style:
SQL Queries - Sorting, Limiting, Substring, Wildcards, and Deletion
Retrieving Top Records using LIMIT
1. Retrieving Top Two Records:
○ First, sort the table in ascending order based on employee_id.
○ Use the LIMIT clause to restrict the number of records displayed.
Query:
SELECT * FROM Employee ORDER BY employee_id ASC LIMIT 2;
○
○ This ensures that the first two records (smallest employee_id values) are displayed.
2. Retrieving the First Record Only:
○ Modify the above query to limit output to one record.
Query:
SELECT * FROM Employee ORDER BY employee_id ASC LIMIT 1;
○
3. Retrieving the Last Two Records:
○ Sort the table in descending order so the most recently added records appear first.
Query:
SELECT * FROM Employee ORDER BY employee_id DESC LIMIT 2;
○
○ This fetches the last two records from the table.
Retrieving Substrings from a Column
● Extract only the first three letters from the city column.
● Use the MID() function, which extracts a substring from a given column.
Query:
SELECT MID(city, 1, 3) FROM Employee;
●
Example Output:
+------+
| MID |
+------+
| BAN |
| CHE |
| HYD |
| PUN |
+------+
●
Fetching Current System Time
1. Retrieve the Current System Time using NOW():
Query:
SELECT NOW();
○
○ This returns the current timestamp.
2. Changing the Column Name (Alias) to "Timestamp":
○ Use the AS keyword to rename the output column.
Query:
SELECT NOW() AS Timestamp;
○
Output:
+---------------------+
| Timestamp |
+---------------------+
| 2025-03-21 14:30:00 |
+---------------------+
○
Using Aliases to Rename Columns
● Change the column name ename to name in the output.
Query:
SELECT ename AS name FROM Employee;
●
● This does not change the column name in the database, only in the output.
Using Wildcards in SQL (LIKE, %, _)
Wildcards allow searching for patterns within text data.
1. Fetch Employee Names Ending with "M"
● Use LIKE with %m to match names where the last letter is m.
Query:
SELECT ename FROM Employee WHERE ename LIKE '%m';
●
Example Output:
+--------+
| ename |
+--------+
| Vikram |
| Ram |
+--------+
●
2. Fetch Employee Names Containing the Letter "M" Anywhere
● Use %m% so m can appear anywhere in the name.
Query:
SELECT ename FROM Employee WHERE ename LIKE '%m%';
●
3. Fetch Employee Names Starting with "S"
● Use LIKE 'S%' to match names starting with S.
Query:
SELECT ename FROM Employee WHERE ename LIKE 'S%';
●
4. Fetch Employee Names with Exactly Three Letters
● Use _ (underscore) as a wildcard for single characters.
Query:
SELECT ename FROM Employee WHERE ename LIKE '___';
●
● This fetches names that only have three characters (e.g., Ram, Sim).
5. Fetch Employee Names Ending with "M" and Containing Exactly Three Letters
● Use _ _ m (underscore for any letter before m).
Query:
SELECT ename FROM Employee WHERE ename LIKE '__m';
●
Deleting Records from a Table
1. Delete a Specific Record by Employee ID
Query:
DELETE FROM Employee WHERE employee_id = 101;
●
● This removes the record where employee_id = 101.
2. Delete Multiple Records
● Use IN() to delete multiple records at once.
Query:
DELETE FROM Employee WHERE employee_id IN (101, 102);
●
● This deletes records where employee_id = 101 or employee_id = 102.
Here are the structured notes based on your transcript:
SQL Queries - String Manipulation and Data Modification
1. Concatenation in SQL
Concatenating Employee Name and Salary
SELECT CONCAT(ename, salary) AS salary_info FROM employee;
●
Concatenating with an Underscore Separator
SELECT CONCAT(ename, '_', salary) AS salary_info FROM employee;
●
Concatenating Multiple Columns (e.g., Name, Salary, and Age)
SELECT CONCAT(ename, '_', salary, '_', age) AS full_info FROM employee;
●
2. Trimming White Spaces
Trim Left Side (Leading spaces)
SELECT LTRIM(ename) AS trimmed_name FROM employee;
●
Trim Right Side (Trailing spaces)
SELECT RTRIM(ename) AS trimmed_name FROM employee;
●
Trim Both Sides
SELECT TRIM(ename) AS trimmed_name FROM employee;
●
Trimming and Concatenating with an Underscore
SELECT CONCAT(TRIM(ename), '_', TRIM(salary)) AS cleaned_info FROM employee;
●
3. Sorting Data
Sorting Concatenated Data in Descending Order
SELECT CONCAT(ename, salary) AS salary_info FROM employee
ORDER BY CONCAT(ename, salary) DESC;
●
Sorting Employee Name in Ascending Order
SELECT ename FROM employee ORDER BY ename ASC;
●
4. Updating Data
Updating a Specific Employee Name
UPDATE employee SET ename = 'ABC' WHERE ename = 'Smith';
●
Updating Employee Name When ID is Specified
UPDATE employee SET ename = 'ABC' WHERE eid = 101;
●
Updating Employee ID
UPDATE employee SET eid = 10 WHERE eid = 101;
●
Updating City Name
UPDATE employee SET city = 'Bengaluru' WHERE city = 'Bangalore';
●
5. Deleting Data
Deleting Employee Record Based on Name
DELETE FROM employee WHERE ename = 'Smith';
●
Deleting Employees Based on Salary
DELETE FROM employee WHERE salary = 12000;
●
6. Updating Salary for All Employees
Increasing Salary by 200
UPDATE employee SET salary = salary + 200;
●
Decreasing Salary by 5000
UPDATE employee SET salary = salary - 5000;
●
7. Modifying Table Structure
Adding a Column to an Existing Table
ALTER TABLE employee ADD email VARCHAR(20);
●
Adding a Column at the Beginning of the Table
ALTER TABLE employee ADD email VARCHAR(20) FIRST;
●
SQL Subqueries and Finding Second & Third Maximum Salary
Recap of Previous Topics
Before jumping into subqueries, let's quickly recall the SQL concepts we have covered:
● UNIQUE, ALTER, DROP
● How to update, add, and remove a column in a table
Now, let’s move on to subqueries, which are commonly asked in interviews.
What is a Subquery?
A subquery is a query within another query.
● The inner query runs first and provides results to the outer query.
● The outer query then processes these results further.
Example: Finding Second Maximum Salary
We will demonstrate subqueries by solving a common SQL problem:
"Find the second maximum salary from the Employee table."
Connecting to MySQL Database
1. Open XAMPP Control Panel
○ Start MySQL service.
2. Open MySQL Command Line Interface
Navigate to the MySQL bin directory:
cd C:\xampp\mysql\bin
○
Login to MySQL:
mysql -u root
○
Show all databases:
SHOW DATABASES;
○
Use the required database:
USE testing_campus;
○
Show all tables:
SHOW TABLES;
○
Print the content of the Employee table:
SELECT * FROM Employee;
○
Approach 1: Finding Second Maximum Salary (Without Subquery)
To find the second highest salary manually, we can use:
SELECT MAX(salary) FROM Employee WHERE salary < (SELECT MAX(salary) FROM Employee);
Breakdown:
First, find the maximum salary:
SELECT MAX(salary) FROM Employee;
1. Assume the result is 12,000.
Now, get the second highest salary:
SELECT MAX(salary) FROM Employee WHERE salary < 12000;
2. This gives 10,000.
Problem with This Approach
● If a new employee is added with a higher salary (e.g., 30,000), we have to manually update the query.
● This approach is static and does not work dynamically when data changes.
Approach 2: Finding Second Maximum Salary (With Subquery)
To avoid manual updates, we use a subquery:
SELECT MAX(salary)
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee);
Explanation
Inner Query:
SELECT MAX(salary) FROM Employee;
1. This fetches the highest salary (e.g., 12,000).
Outer Query:
SELECT MAX(salary) FROM Employee WHERE salary < 12000;
2. This dynamically finds the second highest salary.
Advantage: ✅ Works dynamically even if salary data changes.
Finding Third Maximum Salary
To get the third highest salary, we extend the subquery logic:
SELECT MAX(salary)
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee WHERE salary < (SELECT MAX(salary) FROM
Employee));
Explanation
Innermost Query:
SELECT MAX(salary) FROM Employee;
1. Finds the highest salary (e.g., 12,000).
Middle Query:
SELECT MAX(salary) FROM Employee WHERE salary < 12000;
2. Finds the second highest salary (e.g., 10,000).
Outer Query:
SELECT MAX(salary) FROM Employee WHERE salary < 10000;
3. Finds the third highest salary (e.g., 5,000).
✅ Dynamic Approach—works regardless of data changes.
Using the LIMIT Clause (Alternative Approach)
Another efficient way to find the Nth highest salary:
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
Explanation:
● ORDER BY salary DESC → Sorts salaries in descending order.
● LIMIT 1 OFFSET 1 → Skips the highest salary and fetches the second highest.
For the third highest salary, change OFFSET 1 to OFFSET 2:
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
✅ Better performance than using multiple MAX() subqueries.
Building Subqueries with Multiple Tables
Problem Statement
"Find employee names who have received incentives."
We have two tables:
Employee Table (Employee)
+------------+--------+------------+--------+
| EmpID | Name | City | Salary |
+------------+--------+------------+--------+
| 100 | Smith | Bangalore | 12000 |
| 101 | Cal | Bangalore | 10000 |
| 102 | Ram | Chennai | 5000 |
| 103 | Siri | Pune | 2000 |
+------------+--------+------------+--------+
1.
Incentives Table (Incentives)
+------------+----------------+------------+
| EmpID | IncentiveAmt | Date |
+------------+----------------+------------+
| 100 | 5000 | 02-02-14 |
| 100 | 3000 | 03-06-14 |
| 101 | 6000 | 03-09-14 |
| 102 | 2000 | 02-09-14 |
+------------+----------------+------------+
2.
Solution Using Subquery
SELECT Name
FROM Employee
WHERE EmpID IN (SELECT DISTINCT EmpID FROM Incentives);
Explanation:
Inner Query:
SELECT DISTINCT EmpID FROM Incentives;
1. Retrieves EmpID of employees who received incentives.
Outer Query:
SELECT Name FROM Employee WHERE EmpID IN (...);
2. Fetches names of those employees.
✅ Efficient and dynamic.
Key Takeaways
1. Subquery = A query inside another query.
2. Use subqueries to get dynamic results instead of hardcoding values.
3. Second & Third Maximum Salary:
○ Use MAX() with a subquery.
○ Or use ORDER BY salary DESC LIMIT 1 OFFSET N.
4. Joining Multiple Tables:
○ Use IN (SELECT DISTINCT column FROM table).
Next Steps
● Try different SQL interview problems using subqueries.
● Practice on real databases to improve understanding.
Here’s a structured summary of the lecture on SQL Subqueries:
SQL Subqueries - Understanding Inner and Outer Queries
A subquery (or nested query) is a query within another query, where:
● The inner query retrieves data first.
● The outer query uses this data to filter results.
Rule #1:
A subquery is only possible when there is a common column between the two tables.
Example 1: Get Employee Names Who Got Incentives
Tables Used:
1. incentive_list (eid, incentive_amount)
2. employee (eid, ename, salary)
Steps:
First, get employee IDs (eid) who received incentives.
SELECT eid FROM incentive_list;
1. Output: 100, 100, 101, 102
Use these IDs in the outer query to get their names.
SELECT DISTINCT ename FROM employee WHERE eid IN (
SELECT eid FROM incentive_list
);
2. Output: Smith, Carl, Ram
Example 2: Get Employee Names Who Are Not Married
Tables Used:
1. status (eid, marital_status, gender)
2. employee (eid, ename)
Steps:
Find employee IDs (eid) where marital_status = 'No'.
SELECT eid FROM status WHERE marital_status = 'No';
1. Output: 101, 102
Use this result in the outer query to get names.
SELECT ename FROM employee WHERE eid IN (
SELECT eid FROM status WHERE marital_status = 'No'
);
2. Output: Carl, Ram
Example 3: Get Female Employees and Their Salary
Tables Used:
1. status (eid, gender)
2. employee (eid, ename, salary)
Steps:
Find IDs of female employees.
SELECT eid FROM status WHERE gender = 'F';
1. Output: 103, 104
Use these IDs to get their names and salaries.
SELECT ename, salary FROM employee WHERE eid IN (
SELECT eid FROM status WHERE gender = 'F'
);
2. Output: Sheila, Ankita
Example 4: Get Employee Names Who Got Incentives ≥ 5000
Tables Used:
1. incentive_list (eid, incentive_amount)
2. employee (eid, ename)
Steps:
Find IDs of employees with incentive ≥ 5000.
SELECT eid FROM incentive_list WHERE incentive_amount >= 5000;
1. Output: 100, 102
Use these IDs to get names.
SELECT ename FROM employee WHERE eid IN (
SELECT eid FROM incentive_list WHERE incentive_amount >= 5000
);
2. Output: Smith, Ram
Example 5: Get Married Employees Who Got Incentives
Tables Used:
1. status (eid, marital_status)
2. incentive_list (eid, incentive_amount)
3. employee (eid, ename)
Steps:
Find IDs of married employees.
SELECT eid FROM status WHERE marital_status = 'Yes';
1. Output: 100, 103, 104
Find IDs from this list who also got incentives.
SELECT eid FROM incentive_list WHERE eid IN (
SELECT eid FROM status WHERE marital_status = 'Yes'
);
2. Output: 100
Use this result in the outer query to get the name.
SELECT ename FROM employee WHERE eid IN (
SELECT eid FROM incentive_list WHERE eid IN (
SELECT eid FROM status WHERE marital_status = 'Yes'
);
3. Output: Smith
Example 6: Get Marital Status of Employees with Salary > 10,000
Tables Used:
1. employee (eid, salary)
2. status (eid, marital_status)
Steps:
Find IDs of employees with salary > 10,000.
SELECT eid FROM employee WHERE salary > 10000;
1. Output: 101, 103
Use these IDs to get marital status.
SELECT marital_status FROM status WHERE eid IN (
SELECT eid FROM employee WHERE salary > 10000
);
2. Output: No, Yes
Key Takeaways
1. Always execute the inner query first.
2. The outer query depends on the result of the inner query.
3. Use IN when comparing multiple values in a subquery.
4. Use DISTINCT if duplicate records exist.
5. Ensure that a common column exists between tables.
This covers subqueries using two and three tables effectively! 🚀
Here are the cleaned-up and structured notes based on the lecture:
SQL Data Types in MySQL
1. Introduction
● In previous sessions, we learned how to create, update, and delete tables using PHPMyAdmin, which is a
GUI (Graphical User Interface) for managing MySQL databases.
● However, we did not discuss data types, which are crucial when defining table columns.
● Similar to Java (which has int, float, double, etc.), databases also have predefined data types to control
what kind of data can be stored in a column.
2. Why Are Data Types Important?
● When creating a table, each column should have a defined data type to ensure data consistency and
storage efficiency.
● Example: Creating a Pets table with columns:
○ pet_id (stores a number → Integer)
○ pet_name (stores text → String)
○ owner_name (stores text → String)
○ birth_date (stores date → Date)
○ gender (stores male/female → Fixed value)
○ height (stores decimal values → Float/Double)
3. Numeric Data Types
Numeric types store numbers and are categorized based on storage size and range.
Data Type Storage Value Range
Size
TINYINT 1 byte -128 to 127 (signed) or 0 to 255 (unsigned)
SMALLINT 2 bytes -32,768 to 32,767
MEDIUMINT 3 bytes -8,388,608 to 8,388,607
INT (INTEGER) 4 bytes -2,147,483,648 to 2,147,483,647
BIGINT 8 bytes Large numbers (2^63 -1)
FLOAT 4 bytes Stores decimal values (approximate
precision)
DOUBLE 8 bytes Higher precision for decimal values
● Choosing the Right Numeric Type:
○ If pet_id values will never exceed 10,000, we can use SMALLINT instead of INT to save memory.
4. String Data Types
String types store text data.
Data Type Description
CHAR(n) Fixed-length string (e.g., CHAR(4) always uses 4 bytes)
VARCHAR(n) Variable-length string (uses only as much space as
needed)
TEXT Used for large text storage (e.g., descriptions)
BLOB (Binary Large Stores large binary data (e.g., images, files)
Object)
● Difference between CHAR and VARCHAR:
○ CHAR(10): Always stores 10 bytes, even if the string is "dog" (wasting memory).
○ VARCHAR(10): Stores only the exact length of the string, saving space.
5. Boolean and Enum Data Types
● ENUM: Stores fixed values (e.g., Male/Female, Order Status: Pending, Shipped, Delivered)
● BOOLEAN: Typically stored as TINYINT(1) where:
○ 0 = False
○ 1 = True
Example: Storing Gender as ENUM
CREATE TABLE Pets (
pet_id INT PRIMARY KEY,
pet_name VARCHAR(50),
gender ENUM('Male', 'Female')
);
● This prevents users from entering incorrect values like "M" instead of "Male".
6. Date and Time Data Types
Data Type Description
DATE Stores only date (YYYY-MM-DD)
TIME Stores only time (HH:MM:SS)
DATETIME Stores date & time (YYYY-MM-DD HH:MM:SS)
TIMESTAM Stores UNIX timestamp (auto-updated for logging)
P
YEAR Stores only year (YYYY)
● Example: Storing Birth Date
CREATE TABLE Pets (
pet_id INT PRIMARY KEY,
birth_date DATE
);
● Default Format for MySQL Date: YYYY-MM-DD
7. Choosing the Best Data Types for Our Table
Column Best Data Type Reason
pet_id SMALLINT Pet IDs are within 10,000
pet_name VARCHAR(50) Names vary in length
owner_na VARCHAR(50) Owner names vary in length
me
birth_da DATE Stores only date
te
gender ENUM('Male', Restricts values to Male/Female
'Female')
height FLOAT Stores decimal values (e.g., height in
cm)
8. Summary
1. Numeric Types: Use INT, SMALLINT, etc., based on the range of values.
2. String Types: Use CHAR for fixed-size, VARCHAR for dynamic-size, and TEXT for long content.
3. Boolean & ENUM: Use ENUM for predefined choices.
4. Date & Time Types: Use DATE, TIME, DATETIME, or TIMESTAMP as needed.
5. Always choose the most efficient type to save memory and improve performance.
This knowledge helps in designing efficient and optimized database tables. 🚀
This lecture covers SQL constraints in detail, including NOT NULL, UNIQUE, PRIMARY KEY, and ENUM. Below is
a structured note based on the lecture flow:
SQL Constraints & Data Types
When creating a table, we define data types for each column. Constraints are used to restrict certain types of data
from being entered.
What are Constraints?
Constraints are rules applied to table columns to restrict invalid data. They ensure data integrity and validity.
Example Table: students
To understand constraints, we design a students table with columns:
● student_id (SID) – A unique identifier (Integer)
● name – Student's name (VARCHAR)
● gender – Male/Female (ENUM)
● dob – Date of Birth (DATE)
● phone_number – Contact number (VARCHAR)
● location – Address (VARCHAR)
Defining Data Types
Column Name Data Type Notes
student_id INT(10) Large enough for many students
name VARCHAR(25) Assumed max 25 characters
gender ENUM('M', 'F') Restricts values to M or F
dob DATE Stores date format YYYY-MM-DD
phone_numbe VARCHAR(10) Allows flexibility for different regions
r
location VARCHAR(50) Address of the student
Types of Constraints
1️⃣ NOT NULL
● Ensures that a column cannot have NULL values.
Example:
CREATE TABLE students (
student_id INT(10) NOT NULL,
name VARCHAR(25) NOT NULL,
gender ENUM('M', 'F') NOT NULL,
dob DATE NOT NULL,
phone_number VARCHAR(10),
location VARCHAR(50)
);
●
● Explanation:
○ name, gender, and dob must have values.
○ phone_number and location can be NULL.
2️⃣ UNIQUE
● Ensures that all values in a column are distinct.
Example:
CREATE TABLE students (
student_id INT(10) NOT NULL UNIQUE,
phone_number VARCHAR(10) UNIQUE
);
●
● Explanation:
○ student_id must be unique and cannot be NULL.
○ phone_number must be unique but can be NULL.
3️⃣ PRIMARY KEY
● Combination of UNIQUE + NOT NULL.
● Used to uniquely identify each record.
Example:
CREATE TABLE students (
student_id INT(10) PRIMARY KEY,
name VARCHAR(25) NOT NULL
);
●
● Explanation:
○ student_id cannot be NULL and must be unique.
4️⃣ ENUM
● Restricts a column to predefined values.
Example:
CREATE TABLE students (
gender ENUM('M', 'F') NOT NULL
);
●
● Explanation:
○ gender can only have values 'M' or 'F'.
Key Takeaways
1. NOT NULL → Prevents NULL values but allows duplicates.
2. UNIQUE → Ensures unique values but allows NULL.
3. PRIMARY KEY → Ensures unique + non-null values.
4. ENUM → Restricts values to predefined options.
Lecture Notes: MySQL SET Data Type & Constraints
Creating a Table with SET Data Type
● In the previous part, we created a table with constraints.
● Now, we explore the SET data type and its syntax.
● SET allows us to store multiple predefined values in a column.
● Unlike VARCHAR, we don’t need to explicitly declare it as such because SET inherently stores values as
VARCHAR.
Example: Defining a SET Column
● Suppose we are offering three certifications: QTP, Selenium, J2W.
● We define a column certificate that can store these values.
CREATE TABLE student (
sid INT,
name VARCHAR(50),
gender CHAR(1),
dob DATE,
phone VARCHAR(15),
certificate SET('QTP', 'Selenium', 'J2W')
);
● The certificate column is defined as a SET containing QTP, Selenium, and J2W.
Inserting Values into a SET Column
● When inserting values, we specify them using single quotes and separate them with a comma.
INSERT INTO student (sid, name, gender, dob, phone, certificate)
VALUES (100, 'XYZ', 'M', '1999-02-23', '988626205336', 'QTP,Selenium');
● The column certificate accepts multiple values (QTP and Selenium).
● Values must be enclosed in single quotes and separated by a comma.
Behavior of SET in MySQL
● The SET column allows:
○ Selecting one value (QTP).
○ Selecting multiple values (QTP, Selenium).
○ Selecting all available values.
● This makes SET different from ENUM, which allows only a single value.
Next Concept: Foreign Key Constraint
● Why do we need a foreign key?
● A foreign key links one table to another, ensuring referential integrity.
● We will discuss how to define and use a foreign key in the next section.
✅ Please write down the notes and confirm if done.
SQL Constraints: Set, Foreign Key, and Auto
Increment
Set Constraint in SQL
● A SET is a collection of predefined values from which a column can store one or more values.
● It is similar to an ENUM, but unlike ENUM, a SET column can hold multiple values.
● Values in a SET are treated as varchar types, so they must be enclosed in single quotes.
Creating a Table with a SET Column
CREATE TABLE student (
s_id INT PRIMARY KEY,
name VARCHAR(50),
gender CHAR(1),
dob DATE,
phone VARCHAR(15),
certificate SET('QTP', 'Selenium', 'J2W')
);
Inserting Values into a SET Column
INSERT INTO student (s_id, name, gender, dob, phone, certificate)
VALUES (100, 'XYZ', 'M', '1999-02-23', '988626205336', 'QTP,Selenium');
● The values for the SET column are separated by commas within single quotes.
● The column can store one or multiple values from the defined set.
DBMS vs RDBMS
Feature DBMS RDBMS
Data Storage Single large table Multiple related tables
Performance Slower for large data Faster due to relationships
Data High Low
Redundancy
Keys Used No primary or foreign key Uses primary and foreign
keys
Example File System, MS Access MySQL, PostgreSQL, Oracle
Foreign Key Constraint
● A foreign key is used to establish a relationship between two tables.
● It links a column in the child table to the primary key of the parent table.
● Primary key: Always unique.
● Foreign key: Can contain duplicate values.
Why Use Foreign Keys?
1. Avoids data duplication.
2. Improves database efficiency.
3. Allows linking between related tables.
Creating Parent and Child Tables with a Foreign Key
Parent Table (Students)
CREATE TABLE students (
s_id INT PRIMARY KEY,
name VARCHAR(50)
);
Child Table (Attendance)
CREATE TABLE attendance (
attendance_id INT PRIMARY KEY AUTO_INCREMENT,
s_id INT,
subject VARCHAR(50),
attendance_date DATE,
FOREIGN KEY (s_id) REFERENCES students(s_id)
);
● s_id in attendance is a foreign key referencing s_id in students.
● The foreign key allows repeated values, meaning a student can have multiple attendance records.
Example Data in Attendance Table
s_i Subject Attendance
d Date
100 P1 2025-03-21
100 P2 NULL
100 P3 2025-03-20
● If attendance_date is NULL, the student was absent for that subject.
Querying Using Foreign Keys
Get Attendance of a Specific Student
SELECT subject, attendance_date
FROM attendance
WHERE s_id = (SELECT s_id FROM students WHERE name = 'XYZ');
● The inner query fetches the s_id of student XYZ.
● The outer query retrieves their subject-wise attendance.
Auto Increment in SQL
● Auto Increment allows automatic numbering of records.
● The ID column automatically increments with each new row.
● Syntax for Auto Increment:
CREATE TABLE employee (
emp_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
department VARCHAR(50)
);
● You do not need to manually insert the emp_id; it will be auto-generated.
Inserting Values with Auto Increment
INSERT INTO employee (name, department) VALUES ('John Doe', 'IT');
● The emp_id will automatically be 1, 2, 3... as new rows are added.
Creating a Child Table with Auto Increment and Foreign Key
CREATE TABLE attendance (
attendance_id INT PRIMARY KEY AUTO_INCREMENT,
emp_id INT,
FOREIGN KEY (emp_id) REFERENCES employee(emp_id)
);
● The child table (attendance) references the parent table (employee) using a foreign key.
Key Takeaways
1. SET Constraint: Stores multiple predefined values, separated by commas.
2. Foreign Key: Establishes a relationship between two tables.
3. DBMS vs RDBMS: RDBMS provides better performance with multiple linked tables.
4. Auto Increment: Automatically generates unique ID values for new records.
SQL Notes: Subtracting Two Tables & Joins
Subtracting Two Tables in MySQL
Scenario:
If an interviewer asks you to subtract two tables and return the non-matching records, you should use subqueries
with NOT IN because MySQL does not support MINUS or INTERSECT commands (which are available in Oracle).
Example Tables
Students Table
SID Name Gender DOB Phone Locatio
n
100 XYZ Male 02/2002 123456789 Delhi
0
101 ABC Male 03/2001 123456789 Mumbai
1
102 PQR Female 04/2003 123456789 Kolkata
2
103 LMN Male 05/2004 123456789 Chennai
3
Attendance Table
SID Attendance_Dat
e
100 2024-03-20
101 2024-03-21
Subtracting Attendance Table from Students Table
We want to return students who do not have an attendance record (i.e., SID not present in the Attendance
table).
SQL Query
SELECT * FROM Students
WHERE SID NOT IN (SELECT SID FROM Attendance);
Output
SID Name Gender DOB Phone Locatio
n
102 PQR Female 04/2003 123456789 Kolkata
2
103 LMN Male 05/2004 123456789 Chennai
3
Joins in SQL
Joins are used to combine rows from two or more tables based on a common column.
Types of Joins
1. Inner Join - Returns only the matching records between two tables.
2. Left Join (Left Outer Join) - Returns all records from the left table, and matching records from the right
table.
3. Right Join (Right Outer Join) - Returns all records from the right table, and matching records from the
left table.
4. Full Join (Full Outer Join) - Returns all records from both tables, with NULL where there is no match.
5. Cross Join - Returns the Cartesian product of two tables (each row from table 1 combines with every row
from table 2).
Inner Join
Scenario:
You want to retrieve only employees who have attendance records.
Employee Table
EMP_ID Name Department Location
100 Smith Science Bangalore
101 Carl Social Chennai
102 Jimmy Math Bangalore
103 Don English Delhi
104 John Hindi Mumbai
105 Kim Kannada Chennai
Attendance Table
EMP_ID Attendance_Dat
e
100 2025-03-15
101 2025-03-15
102 2025-03-15
104 2025-03-15
SQL Query for Inner Join
SELECT Employee.EMP_ID, Employee.Name, Employee.Department, Attendance.Attendance_Date
FROM Employee
INNER JOIN Attendance ON Employee.EMP_ID = Attendance.EMP_ID;
Output (Only Matching Records)
EMP_ID Name Department Attendance_Dat
e
100 Smith Science 2025-03-15
101 Carl Social 2025-03-15
102 Jimmy Math 2025-03-15
104 John Hindi 2025-03-15
Left Join (Left Outer Join)
Scenario:
Retrieve all employees, even if they don't have an attendance record.
SQL Query
SELECT Employee.EMP_ID, Employee.Name, Employee.Department, Attendance.Attendance_Date
FROM Employee
LEFT JOIN Attendance ON Employee.EMP_ID = Attendance.EMP_ID;
Output
EMP_ID Name Department Attendance_Dat
e
100 Smith Science 2025-03-15
101 Carl Social 2025-03-15
102 Jimmy Math 2025-03-15
103 Don English NULL
104 John Hindi 2025-03-15
105 Kim Kannada NULL
Explanation:
● 103 (Don) and 105 (Kim) are included even though they have no attendance record.
Right Join (Right Outer Join)
Scenario:
Retrieve all attendance records, even if they don't match an employee.
SQL Query
SELECT Employee.EMP_ID, Employee.Name, Employee.Department, Attendance.Attendance_Date
FROM Employee
RIGHT JOIN Attendance ON Employee.EMP_ID = Attendance.EMP_ID;
Output
EMP_ID Name Department Attendance_Dat
e
100 Smith Science 2025-03-15
101 Carl Social 2025-03-15
102 Jimmy Math 2025-03-15
104 John Hindi 2025-03-15
Explanation:
● If an Attendance record exists without a matching Employee, it would still be included.
Full Join (Full Outer Join)
Scenario:
Retrieve all employees and all attendance records, even if there's no match.
SQL Query
SELECT Employee.EMP_ID, Employee.Name, Employee.Department, Attendance.Attendance_Date
FROM Employee
LEFT JOIN Attendance ON Employee.EMP_ID = Attendance.EMP_ID
UNION
SELECT Employee.EMP_ID, Employee.Name, Employee.Department, Attendance.Attendance_Date
FROM Employee
RIGHT JOIN Attendance ON Employee.EMP_ID = Attendance.EMP_ID;
Output
EMP_ID Name Department Attendance_Dat
e
100 Smith Science 2025-03-15
101 Carl Social 2025-03-15
102 Jimmy Math 2025-03-15
103 Don English NULL
104 John Hindi 2025-03-15
105 Kim Kannada NULL
Key Takeaways
1. Subtracting Tables:
○ Use NOT IN to get non-matching records.
○ MySQL does not support MINUS or INTERSECT.
2. Joins:
○ INNER JOIN → Matching records from both tables.
○ LEFT JOIN → All left table records + matching right table records.
○ RIGHT JOIN → All right table records + matching left table records.
○ FULL JOIN → All records from both tables (MySQL uses UNION).
Here’s a cleaned-up version of your transcript while keeping the lecture’s original flow:
LEFT JOIN
A LEFT JOIN returns all records from the left table and only matching records from the right table. When
using an INNER JOIN, we only get common records. But now, we want all the records from the left table, even if
there’s no match in the right table. The unmatched records from the right table will have NULL values.
Let’s analyze an example:
Left Table (Employee)
EMPID Employee Department
Name
100 Smith Science
101 Karl Social
102 Jimmy Maths
103 Dummy English
104 Don John Hindi
105 Kim Alex Kannada
Right Table (Attendance)
EMPID Attendance
Date
100 18-Feb-2016
102 16-Feb-2016
102 16-Feb-2016
104 16-Feb-2016
106 16-Feb-2016
Here, EMPID 101, 103, and 105 are present in the Employee table but do not have matching records in the
Attendance table.
Query for LEFT JOIN:
SELECT employee.ename, employee.department, attendance.attendance_date
FROM employee
LEFT JOIN attendance
ON employee.empid = attendance.empid;
Expected Output:
Employee Department Attendance
Name Date
Smith Science 18-Feb-2016
Karl Social NULL
Jimmy Maths 16-Feb-2016
Jimmy Maths 16-Feb-2016
Dummy English NULL
Don John Hindi 16-Feb-2016
Kim Alex Kannada NULL
● Since Karl (101), Dummy (103), and Kim Alex (105) have no matching records in the right table, their
attendance date is NULL.
● Jimmy (102) appears twice because there are two matching records in the attendance table.
● EMPID 106 is not displayed because it exists only in the right table, and a LEFT JOIN only includes all
records from the left table.
RIGHT JOIN
A RIGHT JOIN returns all records from the right table and only matching records from the left table.
Query for RIGHT JOIN:
SELECT employee.ename, employee.department, attendance.attendance_date
FROM employee
RIGHT JOIN attendance
ON employee.empid = attendance.empid;
Expected Output:
Employee Department Attendance
Name Date
Smith Science 18-Feb-2016
Jimmy Maths 16-Feb-2016
Jimmy Maths 16-Feb-2016
Don John Hindi 16-Feb-2016
NULL NULL 16-Feb-2016
● EMPID 106 appears because it exists in the right table, but there is no matching record in the left table
(Employee), so it appears as NULL for Employee Name and Department.
● EMPID 101, 103, and 105 are missing since they exist in the left table but do not have matching records in
the right table.
Key Takeaways:
1. LEFT JOIN → All records from the left table + matching records from the right table.
2. RIGHT JOIN → All records from the right table + matching records from the left table.
3. Unmatched records get NULL values in the output.
4. Repeated records appear multiple times if there are multiple matches.
This should help in understanding LEFT JOIN vs RIGHT JOIN!
Here’s a structured version of your SQL lecture notes based on the transcription:
SQL Joins and Cartesian Product
1. Understanding Joins in SQL
● Joins are used to combine rows from two or more tables based on a related column.
● Inner Join: Returns only matching records from both tables.
● Left Join: Returns all records from the left table and only matching records from the right table.
● Right Join: Returns all records from the right table and only matching records from the left table.
Example Query (Right Join)
SELECT attendance.attendance_date,
attendance.class,
employee.department
FROM employee
RIGHT JOIN attendance
ON employee.emp_id = attendance.emp_id;
Key points:
● The right table is attendance, the left table is employee.
● If the table order is reversed, the meaning of the right join changes.
● Always specify the common column in ON for join conditions.
2. Cartesian Product (Cross Join)
● Every single record from Table 1 is combined with every single record from Table 2.
● No matching condition (ON clause) is applied.
● Useful for generating large datasets for testing.
Example Query (Cartesian Join)
SELECT employee.emp_id, employee.ename, attendance.class
FROM employee, attendance;
Key points:
● FROM employee, attendance performs a Cartesian join.
● No ON condition means every row in employee multiplies with every row in attendance.
● If there are 5 employees and 4 attendance records, the result set will have 5 × 4 = 20 rows.
● No filtering or matching happens in Cartesian Join.
SQL Interview Questions
1. Common Interview Queries
Requirement Query Type
Find the second maximum salary Subquery
Subtract two tables and get specific columns Subquery with NOT IN
Get common records between two tables Subquery with IN / INNER JOIN
Get all records from left table, only matching from Left Join
right
Get all records from right table, only matching from Right Join
left
Multiply records from both tables Cartesian Join
Retrieve top 2 records LIMIT
Retrieve last 2 records LIMIT with ORDER BY DESC
Sort records in ascending order ORDER BY ASC
Sort records in descending order ORDER BY DESC
Filter records where city starts with 'B' WHERE city LIKE 'B%'
Filter records with exactly 3-letter city names WHERE city LIKE '___' (3
underscores)
Get the current system time SELECT NOW();
Store date of birth in a table DATE datatype
Retrieve year from a date YEAR(date_column)
2. Example: Fetching Employees Born in February 2000
SELECT name
FROM employee
WHERE YEAR(date_of_birth) = 2000
AND MONTH(date_of_birth) = 2;
● YEAR(date_of_birth) = 2000 extracts the year.
● MONTH(date_of_birth) = 2 extracts the month (February).
3. SQL Theoretical Questions
1. What is Rollback and Commit?
○ COMMIT: Saves all changes made in the current transaction permanently.
○ ROLLBACK: Undoes all uncommitted changes in the current transaction.
2. What is Normalization?
○ Process of organizing data to minimize redundancy and improve data integrity.
○ 1NF (First Normal Form): Ensure atomicity (each column has unique values).
○ 2NF (Second Normal Form): Remove partial dependencies.
○ 3NF (Third Normal Form): Remove transitive dependencies.
3. Other Possible SQL Interview Questions
○ Difference between DROP, DELETE, and TRUNCATE.
○ How to add a column to an existing table? (ALTER TABLE ADD COLUMN)
○ How to delete a column from a table? (ALTER TABLE DROP COLUMN)
○ Difference between PRIMARY KEY and FOREIGN KEY.
○ SQL Built-in functions like MAX(), COUNT(), GROUP BY, etc.
Final Summary
● Join types (Inner, Left, Right)
● Cartesian Join (Cross Join) for generating test data
● Important SQL queries for interviews
● Common SQL interview questions
Extracting Date Parts in SQL
● SQL provides functions to extract specific parts of a date.
● YEAR(date_column) → Extracts the year.
● MONTH(date_column) → Extracts the month.
● DAY(date_column) → Extracts the day.
● HOUR(date_column) → Extracts the hour.
● MINUTE(date_column) → Extracts the minute.
● SECOND(date_column) → Extracts the second.
Example Queries:
SELECT YEAR(date_of_birth) FROM employees;
SELECT MONTH(date_of_birth) FROM employees;
SELECT DAY(date_of_birth) FROM employees;
SELECT HOUR(time_column) FROM table_name;
SELECT MINUTE(time_column) FROM table_name;
SELECT SECOND(time_column) FROM table_name;
Use Case: Find all employees born in a specific month:
SELECT name FROM employees WHERE MONTH(date_of_birth) = 7;
●
Find all employees born on the 14th day of any month:
SELECT name FROM employees WHERE DAY(date_of_birth) = 14;
●
SQL Frequently Asked Questions
Removing white spaces from a column:
SELECT TRIM(column_name) FROM table_name;
1.
Concatenating two columns after removing white spaces:
SELECT CONCAT(TRIM(first_name), ' ', TRIM(last_name)) AS full_name FROM employees;
2.
Changing the column name in the output:
SELECT column_name AS new_name FROM table_name;
3.
CRUD Operations in SQL
● CRUD stands for:
1. C - Create (Creating a table)
2. R - Read (Reading data using SELECT)
3. U - Update (Updating records using UPDATE)
4. D - Delete (Deleting records using DELETE or DROP)
Example Queries:
Create a table:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
salary INT
);
●
Read data:
SELECT * FROM employees;
●
Update data:
UPDATE employees SET salary = salary + 500 WHERE department = 'IT';
●
Delete data:
DELETE FROM employees WHERE id = 5;
●
Drop a table:
DROP TABLE employees;
●
SQL Joins & Set Operations
● INTERSECT in MySQL:
○ MySQL does not support INTERSECT but you can achieve the same result using JOIN.
Example using INNER JOIN:
SELECT t1.name FROM table1 t1
INNER JOIN table2 t2 ON t1.id = t2.id;
○
● UNION in SQL:
○ Combines results from two tables and removes duplicates.
Example:
SELECT name FROM table1
UNION
SELECT name FROM table2;
○
UNION ALL (includes duplicates):
SELECT name FROM table1
UNION ALL
SELECT name FROM table2;
●
● MINUS in SQL (EXCEPT in MySQL alternative):
○ Returns rows from the first table that do not exist in the second.
Example using LEFT JOIN and WHERE NULL:
SELECT t1.name FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE t2.id IS NULL;
○
String Functions in SQL
Convert names to uppercase:
SELECT UPPER(name) FROM employees;
1.
Extract the first three letters of a name:
SELECT SUBSTRING(name, 1, 3) FROM employees;
2.
Replace letter ‘a’ with ‘t’ in names:
SELECT REPLACE(name, 'a', 't') FROM employees;
3.
Conclusion
● SQL is essential and frequently used in job interviews.
● Practice CRUD, Joins, and Date Manipulations.
● Future SQL Use Case in Java:
○ JDBC (Java Database Connectivity) will interact with MySQL.
○ Example: Building a form in Java that submits data to a MySQL database.
Final Assignment Topics
1. Find INTERSECT, UNION, and MINUS alternatives in MySQL.
2. Write queries to manipulate date/time values.
3. String manipulation functions (UPPER, REPLACE, SUBSTRING).
4. Normalization concepts.
5. CRUD operations practice.