SELECT: The select statement in MySQL is used to retrieve data from one or more
tables in a database.
FROM: The FROM clause is used in a SELECT statement to specify the tables(s) from
which to retrieve data.
Add a Condition (WHERE): The WHERE clause in MySQL is used to filter records that
meet a specific condition. It works with SELECT, UPDATE, DELETE, and other SQL
statements.
Column Alias (AS): The AS keyword is used to assign an alias to a column or a table.
Aliases are temporary names used to make your queries more readable or to rename
columns/tables in the result set.
Uniqueness (DISTINCT): The DISTINCT keyword is used in SELECT statement to remove
duplicate rows from the result set.
Limit the result (LIMIT): The LIMIT clause is used to restrict the number of rows
returned by SELECT statement. It is especially useful when working with large datasets.
e.g : SELECT column1, column2, ….
FROM table_name
LIMIT number_of_rows;
Sorting the result (ORDER BY): The ORDER BY clause is used to sort the result set of
SELECT query by one or more columns, either in ascending or descending order.
e.g: SELECT column1, column2,…
FROM table_name
ORDER BY column1 (ASC|DESC), column2 (ASC|DESC), …
SQL Aggregate Function
SQL Aggregate functions are essential tools for summarizing and analyzing data within a
database. They allow you to perform calculations on a set of values and return a single
summary value.
Purpose:
• Aggregate functions are used to summarize data, provide insights into trends,
averages, totals, and other statistical measures.
• They are typically used with the GROUP BY clause to perform calculations on
subsets of data.
Common Aggregate Functions:
• COUNT ( ):
o Returns the number of rows in a result set
o COUNT (*): Counts all rows, including those with null values.
o COUNT (column_name): Counts only rows where the specified column is
not NULL.
• SUM( ):
o Returns the sum of all values in a numeric column.
o Ignores NULL values.
• AVG ( ):
o Returns the average (mean) of all values in a numeric column.
o Ignores NULL values.
• MIN ( ):
o Returns the minimum value in a column.
o Can be used with numeric, string, and date/time columns.
o Ignores NULL values.
• MAX ( ):
o Returns the maximum value in a column.
o Can be used with numeric, string, and date/time columns.
o Ignores NULL values.
• COUNT(DISTINCT column_name):
o Returns the number of distinct (unique) values in a column
Categorize (GROUP BY):
The GROUP BY clause is used to group rows that have the same values in specified
columns into summary rows, like ‘total sales per region’ or ‘number of users per
country’. It is commonly used with aggregate functions like COUN(), SUM(), AVG(),
MAX(), and MIN().
e.g: SELECT column1, AGGREGATE_FUNCTION(column2)
FROM table_name
GROUP BY column1;
Non-Aggregated columns in SELECT must be in GROUP BY.
GROUP BY comes after WHERE and before ORDER BY.
e.g: SELECT department, COUNT(*) AS employee_count
FROM employees
WHERE hire_date >= ‘2025-01-01’
GROUP BY department
ORDER BY employee_count DESC;
Some Other function in MySQL:
1. String Functions
These functions are used to manipulate and query string data.
• CONCAT(str1, str2, ...): Joins multiple strings together.
o Example: SELECT CONCAT('First', ' ', 'Last') AS FullName; -> 'First Last'
• LENGTH(str): Returns the length of the string in bytes.
o Example: SELECT LENGTH('MySQL'); -> 5
• TRIM(str): Removes leading and trailing spaces.
o Example: SELECT TRIM(' hello '); -> 'hello'
• LOWER(str): Converts all characters to lowercase.
o Example: SELECT LOWER('HELLO'); -> 'hello'
• UPPER(str): Converts all characters to uppercase.
o Example: SELECT UPPER('hello'); -> 'HELLO'
• SUBSTRING(str, start, length): Extracts a substring.
o Example: SELECT SUBSTRING('database', 5, 4); -> 'base'
• REPLACE(str, from_str, to_str): Replaces all occurrences of a substring.
o Example: SELECT REPLACE('www.mysql.com', 'mysql', 'sql'); ->
'www.sql.com'
• INSTR(str, substr): Returns the position of the first occurrence of a substring.
o Example: SELECT INSTR('hello world', 'world'); -> 7
2. Numeric Functions
These functions perform mathematical operations.
• ABS(X): Returns the absolute value of X.
o Example: SELECT ABS(-15); -> 15
• ROUND(X, D): Rounds a number X to D decimal places.
o Example: SELECT ROUND(123.456, 2); -> 123.46
• CEILING(X): Returns the smallest integer greater than or equal to X.
o Example: SELECT CEILING(12.3); -> 13
• FLOOR(X): Returns the largest integer less than or equal to X.
o Example: SELECT FLOOR(12.7); -> 12
• MOD(N, M): Returns the remainder of N divided by M.
o Example: SELECT MOD(10, 3); -> 1
• POWER(X, Y): Returns X raised to the power of Y.
o Example: SELECT POWER(2, 3); -> 8
3. Date and Time Functions
These functions handle date and time values.
• NOW(): Returns the current date and time.
o Example: SELECT NOW(); -> '2025-09-02 08:00:16'
• CURDATE(): Returns the current date.
o Example: SELECT CURDATE(); -> '2025-09-02'
• DATE_FORMAT(date, format): Formats a date value as a string.
o Example: SELECT DATE_FORMAT('2025-09-02', '%W, %M %d, %Y'); ->
'Tuesday, September 02, 2025'
• DATEDIFF(date1, date2): Returns the number of days between two dates.
o Example: SELECT DATEDIFF('2025-09-10', '2025-09-02'); -> 8
• DATE_ADD(date, INTERVAL value unit): Adds an interval to a date.
o Example: SELECT DATE_ADD('2025-09-02', INTERVAL 10 DAY); -> '2025-
09-12'
• DAYOFWEEK(date): Returns the weekday index (1=Sunday, 2=Monday, ...,
7=Saturday).
o Example: SELECT DAYOFWEEK('2025-09-02'); -> 3
5. Conditional Functions
CASE: A more powerful conditional statement.
• Example:
SELECT
product_name,
CASE
WHEN price > 500 THEN 'High-End'
WHEN price > 100 THEN 'Mid-Range'
ELSE 'Low-End'
END AS price_category
FROM products;
JOIN
1. INNER JOIN
An INNER JOIN returns rows where there's a match in both tables. It's the most
common type of join.
Example 1: Find employees and their department names. This query joins employees
and departments on department_id, showing only employees who are assigned to a
department. David will be excluded because his department_id is NULL.
SQL
SELECT
e.employee_name,
d.department_name
FROM employees AS e
INNER JOIN departments AS d
ON e.department_id = d.department_id;
Result: | employee_name | department_name | | :------------ | :-------------- | | Alice | HR | |
Bob | IT | | Charlie | Finance |
Example 2: Find employees and the projects they are working on. This query joins
employees and employee_projects to find which employees are assigned to a project.
David will be excluded because he has no projects, and Project Beta is not included
with an employee.
SQL
SELECT
e.employee_name,
ep.project_id
FROM employees AS e
INNER JOIN employee_projects AS ep
ON e.employee_id = ep.employee_id;
Result: | employee_name | project_id | | :------------ | :--------- | | Alice | 201 | | Alice | 202 |
| Bob | 201 | | Charlie | 203 |
2. LEFT JOIN
A LEFT JOIN (or LEFT OUTER JOIN) returns all rows from the left table and the matched
rows from the right table. If there's no match, the columns from the right table will be
NULL.
Example 1: List all employees and their department names, even if they aren't in a
department. This query includes all employees from the employees table (the left
table) and their corresponding department. Since David has no matching
department_id, his department_name will be NULL.
SQL
SELECT
e.employee_name,
d.department_name
FROM employees AS e
LEFT JOIN departments AS d
ON e.department_id = d.department_id;
Result: | employee_name | department_name | | :------------ | :-------------- | | Alice | HR | |
Bob | IT | | Charlie | Finance | | David | NULL |
Example 2: List all projects and the employees assigned to them. This query
includes all projects from the projects table (the left table). Project Alpha, Project Beta,
and Project Gamma are included.
SQL
SELECT
p.project_name,
e.employee_name
FROM projects AS p
LEFT JOIN employee_projects AS ep
ON p.project_id = ep.project_id
LEFT JOIN employees AS e
ON ep.employee_id = e.employee_id;
Result: | project_name | employee_name | | :------------- | :------------ | | Project Alpha |
Alice | | Project Alpha | Bob | | Project Beta | Alice | | Project Gamma | Charlie |
3. RIGHT JOIN
A RIGHT JOIN (or RIGHT OUTER JOIN) returns all rows from the right table and the
matched rows from the left table. If there's no match, the columns from the left table
will be NULL.
Example 1: List all departments and their employees, even if a department has no
employees. This query includes all departments from the departments table (the right
table). The Marketing department has no employees, so its employee_name will be
NULL.
SQL
SELECT
e.employee_name,
d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
ON e.department_id = d.department_id;
Result: | employee_name | department_name | | :------------ | :-------------- | | Alice | HR | |
Bob | IT | | Charlie | Finance | | NULL | Marketing |
Example 2: Find all projects, including those with no employees. This query joins
employee_projects to projects (the right table) to see which employees are on which
projects. Project Alpha, Project Beta, and Project Gamma are included with
employee_id.
SQL
SELECT
p.project_name,
ep.employee_id
FROM employee_projects AS ep
RIGHT JOIN projects AS p
ON ep.project_id = p.project_id;
Result: | project_name | employee_id | | :------------ | :------------ | | Project Alpha | 1 | |
Project Alpha | 2 | | Project Beta | 1 | | Project Gamma | 3 |
4. FULL OUTER JOIN
A FULL OUTER JOIN returns all rows when there is a match in either the left or the right
table. Rows without a match are returned with NULL values in the opposite table's
columns. MySQL doesn't have a direct FULL OUTER JOIN syntax, but you can simulate it
using a UNION of a LEFT JOIN and a RIGHT JOIN.
Example 1: List all employees and all departments. This query shows all employees
and all departments. David has no department, so his department_name is NULL.
Marketing has no employees, so its employee_name is NULL.
SQL
SELECT
e.employee_name,
d.department_name
FROM employees AS e
LEFT JOIN departments AS d
ON e.department_id = d.department_id
UNION
SELECT
e.employee_name,
d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
ON e.department_id = d.department_id;
Result: | employee_name | department_name | | :------------ | :-------------- | | Alice | HR | |
Bob | IT | | Charlie | Finance | | David | NULL | | NULL | Marketing |
Example 2: List all employees and all projects. This query includes all employees
from the employees table and all projects from the projects table. David has no projects
and Project Beta has no dedicated employee, so their respective columns will be NULL.
SQL
SELECT
e.employee_name,
p.project_name
FROM employees AS e
LEFT JOIN employee_projects AS ep
ON e.employee_id = ep.employee_id
LEFT JOIN projects AS p
ON ep.project_id = p.project_id
UNION
SELECT
e.employee_name,
p.project_name
FROM employees AS e
RIGHT JOIN employee_projects AS ep
ON e.employee_id = ep.employee_id
RIGHT JOIN projects AS p
ON ep.project_id = p.project_id;
Result: | employee_name | project_name | | :------------ | :----------- | | Alice | Project
Alpha | | Alice | Project Beta | | Bob | Project Alpha | | Charlie | Project Gamma | | David |
NULL |