My SQL Note
My SQL Note
Introduction to MySQL
MySQL is an open-source relational database management system (RDBMS) that uses Structured Query
Language (SQL) to manage data. It's widely used for web applications and is a popular choice for
databases in various environments due to its reliability, performance, and ease of use.
2. MySQL Basics
4. MySQL Functions
Functions in MySQL are predefined operations that perform calculations, manipulate data, or perform
operations on the data stored in tables. Functions are categorized into several types:
Example:
sql
Copy code
Example:
sql
Copy code
Example:
sql
Copy code
CEIL(): Returns the smallest integer value greater than or equal to a number.
FLOOR(): Returns the largest integer value less than or equal to a number.
Example:
sql
Copy code
IF(): Returns a value if a condition is true, and another value if it’s false.
CASE: A more complex conditional statement that returns different values based on multiple
conditions.
Example:
sql
Copy code
FROM employees;
The SELECT statement is used to retrieve data from one or more tables.
sql
Copy code
sql
Copy code
sql
Copy code
5.4. JOINs
JOINs are used to combine rows from two or more tables based on a related column.
INNER JOIN: Returns records that have matching values in both tables.
LEFT JOIN: Returns all records from the left table and matched records from the right table.
RIGHT JOIN: Returns all records from the right table and matched records from the left table.
Example:
sql
Copy code
FROM employees
The GROUP BY clause groups rows that have the same values in specified columns into summary rows.
sql
Copy code
FROM employees
GROUP BY department;
The HAVING clause is used to filter groups based on conditions, often used with GROUP BY.
sql
Copy code
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
The LIMIT clause is used to specify the maximum number of rows to return.
sql
Copy code
6. Indexing in MySQL
Indexes are used to speed up the retrieval of data from a database table by reducing the amount of data
MySQL needs to examine.
Creating an Index:
sql
Copy code
sql
Copy code
sql
Copy code
7. Transactions in MySQL
Transactions allow you to execute a sequence of SQL statements as a single unit of work. MySQL
supports transactions with the InnoDB storage engine.
Example:
sql
Copy code
START TRANSACTION;
COMMIT;
sql
Copy code
BEGIN
-- SQL statements
END;
sql
Copy code
RETURNS datatype
BEGIN
-- SQL statements
RETURN value;
END;
Input Validation: Always validate and sanitize user inputs to prevent SQL injection.
Use Prepared Statements: Avoid dynamic SQL queries; use prepared statements instead.
This guide provides a comprehensive overview of MySQL, including functions, query syntax, and best
practices. Each topic covered here is fundamental to working effectively with MySQL in various contexts,
from small-scale projects to large, complex databases.