From 898847c48649b872963848b2ead3bcde23072895 Mon Sep 17 00:00:00 2001 From: Patrick Birch <48594400+patrickbirch@users.noreply.github.com> Date: Fri, 3 May 2024 08:20:11 -0500 Subject: [PATCH] PS-9224 Add SQL basics On branch ps-9224 new file: docs/common-sql.md new file: docs/data-types-basic.md new file: docs/sql-basics.md modified: mkdocs-base.yml --- docs/common-sql.md | 107 ++++++++++++++++++++++++ docs/create-table.md | 54 ++++++++++++ docs/data-types-basic.md | 89 ++++++++++++++++++++ docs/database.md | 62 ++++++++++++++ docs/delete.md | 47 +++++++++++ docs/functions.md | 60 +++++++++++++ docs/insert.md | 52 ++++++++++++ docs/isolation-levels.md | 61 ++++++++++++++ docs/modify-tables.md | 33 ++++++++ docs/select.md | 32 +++++++ docs/sql-basics.md | 24 ++++++ docs/sql-conventions.md | 84 +++++++++++++++++++ docs/sql-errors.md | 60 +++++++++++++ docs/sql-operators.md | 90 ++++++++++++++++++++ docs/sql-syntax.md | 46 ++++++++++ docs/stored-procedure-error-handling.md | 59 +++++++++++++ docs/stored-procedure-variables.md | 44 ++++++++++ docs/stored-procedures.md | 64 ++++++++++++++ docs/table.md | 54 ++++++++++++ docs/transaction-mgmt.md | 31 +++++++ docs/triggers.md | 73 ++++++++++++++++ docs/troubleshooting-sql.md | 43 ++++++++++ docs/update.md | 52 ++++++++++++ docs/views.md | 55 ++++++++++++ mkdocs-base.yml | 40 +++++++++ 25 files changed, 1416 insertions(+) create mode 100644 docs/common-sql.md create mode 100644 docs/create-table.md create mode 100644 docs/data-types-basic.md create mode 100644 docs/database.md create mode 100644 docs/delete.md create mode 100644 docs/functions.md create mode 100644 docs/insert.md create mode 100644 docs/isolation-levels.md create mode 100644 docs/modify-tables.md create mode 100644 docs/select.md create mode 100644 docs/sql-basics.md create mode 100644 docs/sql-conventions.md create mode 100644 docs/sql-errors.md create mode 100644 docs/sql-operators.md create mode 100644 docs/sql-syntax.md create mode 100644 docs/stored-procedure-error-handling.md create mode 100644 docs/stored-procedure-variables.md create mode 100644 docs/stored-procedures.md create mode 100644 docs/table.md create mode 100644 docs/transaction-mgmt.md create mode 100644 docs/triggers.md create mode 100644 docs/troubleshooting-sql.md create mode 100644 docs/update.md create mode 100644 docs/views.md diff --git a/docs/common-sql.md b/docs/common-sql.md new file mode 100644 index 00000000000..fb29b25b164 --- /dev/null +++ b/docs/common-sql.md @@ -0,0 +1,107 @@ +# Common SQL commands + +SQL commands used by MySQL can be categorized into different types based on their purposes: Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL). + +## Data Manipulation Language (DML) + +DML commands manage data within database tables. + +Common DML commands include: + +* [**SELECT**]: This command retrieves data from one or more tables in the database. + + ```text + mysql> SELECT * FROM customers; + ``` + +* [**INSERT**]: This command adds new records to a table. + + ```text + mysql> INSERT INTO customers (name, email) VALUES ('John Doe', 'john@example.com'); + ``` + +* [**UPDATE**]: This command modifies existing records in a table. + + ```text + mysql> UPDATE customers SET email = 'newemail@example.com' WHERE id = 1; + ``` + +* [**DELETE**]: This command removes records from a table. + + ```text + mysql> DELETE FROM customers WHERE id = 1; + ``` + +## Data Definition Language (DDL) + +DDL commands define, modify, and remove database objects such as tables, indexes, and views. + +Common DDL commands include: + +* **CREATE**: This command creates new database objects like tables, indexes, and views. + + ```text + mysql> CREATE TABLE employees (id INT, name VARCHAR(50)); + ``` + +* **ALTER**: This command modifies the structure of existing database objects. + + ```text + mysql> ALTER TABLE employees ADD COLUMN email VARCHAR(100); + ``` + +* **DROP**: This command removes database objects from the database. + + ```text + mysql> DROP TABLE employees; + ``` + +## Data Control Language (DCL) + +DCL commands control access to database objects and define privileges. + +Common DCL commands include: + +* **GRANT**: This command grants specific privileges to database users. + + ```text + mysql> GRANT SELECT, INSERT ON employees TO 'user1'@'localhost'; + ``` + +* **REVOKE**: This command revokes privileges from database users. + + ```text + mysql> REVOKE INSERT ON employees FROM 'user2'@'localhost'; + ``` + +## Transaction Control Language (TCL) + +TCL commands manage transactions within a database. + +Common TCL commands include: + +* **COMMIT**: This command saves changes made during the current transaction to the database. + + ```text + mysql> COMMIT; + ``` + +* **ROLLBACK**: This command undoes changes made during the current transaction and restores the database to its previous state. + + ```text + mysql> ROLLBACK; + ``` + + [**SELECT**]: select.md + [**INSERT**]: insert.md + [**UPDATE**]: update.md + [**DELETE**]: delete.md + +Fundamental SQL links: + +* [SQL Basics](sql-basics.md) +* [SELECT](select.md) +* [INSERT](insert.md) +* [DELETE](delete.md) +* [UPDATE](update.md) +* [SQL Operators](sql-operators.md) \ No newline at end of file diff --git a/docs/create-table.md b/docs/create-table.md new file mode 100644 index 00000000000..fe4cbe98f00 --- /dev/null +++ b/docs/create-table.md @@ -0,0 +1,54 @@ +# Create a table + +Creating a table is essential to organizing and storing your data effectively when working with a database. Here's a step-by-step guide on how to create a table in such a database: + +## Permissions Required + +To create a table in a database, you need appropriate permissions. Typically, you'll need the `CREATE TABLE` privilege, which allows you to create new tables within a database. This privilege is usually granted to database users by database administrators or through predefined user roles. If you do not have the necessary permissions, you'll need to contact your database administrator to grant them. + +## Define the table structure + +Now, define the structure of your table by specifying its columns along with their data types and any additional properties. Each column represents a different attribute of your data. + +Here's the syntax for creating a table: + +```text +CREATE TABLE table_name ( + column1_name data_type constraints, + column2_name data_type constraints, + ... +); +``` + +Replace `table_name` with the desired name for your table. For each column, provide a name, data type, and constraints such as `NOT NULL`, `PRIMARY KEY`, `AUTO_INCREMENT`. + +## Create the table + +Execute the `CREATE TABLE` command to create the table in the database. For example, to create a table named `employees` with columns for `id`, `name`, and `salary`, you would run the following SQL command: + +```{.bash data-prompt="mysql>"} +CREATE TABLE employees ( + id INT PRIMARY KEY AUTO_INCREMENT, + name VARCHAR(50) NOT NULL, + salary DECIMAL(10, 2) +); +``` + +This command creates a table named `employees` with three columns: `id`, `name`, and `salary`. The `id` column is an integer type and serves as the primary key with auto-increment functionality. The `name` column is a variable-length string, and the `salary` column is a decimal number with a precision of 10 digits and a scale of 2. + +## Verify Table Creation + +After executing the `CREATE TABLE` command, verify that the table has been successfully created. You can use various SQL commands such as `SHOW TABLES` or `DESCRIBE table_name` to check the existence and structure of the newly created table. + +```{.bash data-prompt="mysql>"} +mysql> SHOW TABLES; +mysql> DESCRIBE employees; +``` + +## Database management + +* [Database](database.md) +* [Tables](table.md) +* [Isolation Levels](isolation-levels.md) +* [Transaction Management](transaction-mgmt.md) +* [Views](views.md) \ No newline at end of file diff --git a/docs/data-types-basic.md b/docs/data-types-basic.md new file mode 100644 index 00000000000..985a01d0293 --- /dev/null +++ b/docs/data-types-basic.md @@ -0,0 +1,89 @@ +# Common data types + +Choosing the correct data type for each column ensures data accuracy, efficiency, and reliability within the database. The following describes the purpose of a data type in Percona Server for MySQL: + +* Purpose: + + * Data types define the kind of data that can be stored in a column of a table. + + * They enforce constraints on the values that can be inserted into the column, ensuring data integrity. + + * Data types determine how the data is stored in memory and on disk, optimizing storage space and performance. + + * They provide a way to specify the format and range of acceptable values for numeric, string, date, and other types of data. + + * Data types facilitate efficient sorting, indexing, and searching of data within the database. + +* Importance: + + * Choosing the appropriate data type for each column is crucial for efficient database design and performance. + + * Data types help prevent data corruption and inconsistency by enforcing strict rules for data storage and manipulation. + + * They enable database administrators and developers to define the structure of the database accurately and ensure compatibility with application requirements. + + * Understanding data types allows for effective data modeling and schema design, leading to well-organized and scalable databases. + + +The following is a description of common data types: + +## Integer Types + +Integers are whole numbers without any fractional part. Percona Server for MySQL offers different sizes of integer types to accommodate various ranges of values. + +| Data Type name | Description | +| --- | --- | +| `TINYINT` | A very small integer that can hold values from -128 to 127 (signed) or 0 to 255 (unsigned). | +| `SMALLINT` | A small integer that can hold values from -32768 to 32767 (signed) or 0 to 65535 (unsigned). | +| `MEDIUMINT` | A medium-sized integer that can hold values from -8388608 to 8388607 (signed) or 0 to 16777215 (unsigned). | +| `INT` or `INTEGER` | A standard-sized integer that can hold values from -2147483648 to 2147483647 (signed) or 0 to 4294967295 (unsigned). | +| `BIGINT` | A large integer that can hold values from -9223372036854775808 to 9223372036854775807 (signed) or 0 to 18446744073709551615 (unsigned). | + +## Floating-Point Types + +Floating-point types are used to represent numbers with a fractional part. + +| Data Type name | Description | +| --- | --- | +| `FLOAT` | A single-precision floating-point number that can hold up to 7 decimal digits of precision. | +| `DOUBLE` or `REAL` | A double-precision floating-point number that can hold up to 15 decimal digits of precision. | + +## Fixed-Point Types + +Fixed-point types are used to represent exact numeric values. + +* `DECIMAL` or `NUMERIC`: A fixed-point number with user-defined precision and scale. + +## String Types + +String types are used to store text data. + +| Data Type name | Description | +| --- | --- | +| `CHAR` | A fixed-length string that can hold up to 255 characters. | +| `VARCHAR` | A variable-length string that can hold up to 65535 characters. | +| `TEXT` | A string with a maximum length of 65535 characters. | +| `BLOB` | A binary large object that can hold up to 65535 bytes. | + +## Date and Time Types + +Date and time types are used to store date and time information. + +| Data Type name | Description | +| --- | --- | +| `DATE` | A date value in the format YYYY-MM-DD. | +| `TIME` | A time value in the format HH:MM:SS. | +| `DATETIME` | A combination of date and time values in the format YYYY-MM-DD HH:MM:SS. | +| `TIMESTAMP` | A timestamp value representing the number of seconds since the Unix epoch (January 1, 1970). | + +## Advanced SQL features + +* [Functions](functions.md) +* [SQL Conventions](sql-conventions.md) +* [SQL Errors](sql-errors.md) +* [SQL Syntax](sql-syntax.md) +* [Stored Procedures](stored-procedures.md) +* [Stored Procedure Error Handling](stored-procedure-error-handling.md) +* [Stored Procedure Variables](stored-procedure-variables.md) +* [Triggers](triggers.md) +* [Troubleshooting SQL](troubleshooting-sql.md) diff --git a/docs/database.md b/docs/database.md new file mode 100644 index 00000000000..d7f9c80dc00 --- /dev/null +++ b/docs/database.md @@ -0,0 +1,62 @@ +# Introduction to Databases and SQL + +## Introduction to databases + +A database in the server is a structured collection of data. It helps store, organize, and manage various types of information like customer details, product inventories, financial records, and more. Using a database allows you to store data in an organized manner, making it easy to retrieve, update, and manipulate as needed. + +### Advantages + +Using a database in servers has several benefits. The table below lists these advantages: + +| Advantages | Description | +|--------------------|-----------------------------------------------------------------------------| +| **Efficient Storage** | Databases store data in an organized way, making it easy to manage large volumes of information.| +| **Quick Retrieval** | You can quickly find and retrieve specific data using SQL queries. | +| **Data Integrity** | Databases ensure data accuracy and consistency through constraints and relationships.| +| **Scalability** | Databases can handle growing amounts of data and users efficiently. | +| **Security** | Databases provide robust security features to protect sensitive data. | + +### Disadvantages + +While databases offer many advantages, there are also some drawbacks to consider. The table below outlines these disadvantages: + +| Disadvantages | Description | +|---------------------|-----------------------------------------------------------------------------------| +| **Complex Setup** | Setting up and configuring a database can be complex and time-consuming. | +| **Maintenance** | Databases require regular maintenance and updates to function optimally. | +| **Resource Intensive** | Databases can consume significant server resources, impacting performance. | +| **Backup and Recovery** | Proper backup and recovery processes are necessary to prevent data loss. | +| **Cost** | Licensing and operational costs for databases can be high, especially for large-scale deployments. | + +## Permissions required + +To create a database on a server, a user must have the `CREATE` privilege. This privilege allows the user to create new databases and tables within those databases. + +## Using SQL Commands with a database + +### Create a database + +You use the `CREATE DATABASE` command to create a new database in the server. This command tells the server to create a new database with the specified name. For example, to create a database named `my_database`, you execute the following command: + +```{.bash data-prompt="mysql>"} +mysql> CREATE DATABASE my_database; +``` + +This command creates a new, empty database called `my_database`. You can then start adding tables and data to this database. + +### Select a database + +After creating a database, you need to select it to start working with it. Use the `USE` command to specify which database you want to use for your SQL statements. For example, to select the `my_database` database, you execute the following command: + +```{.bash data-prompt="mysql>"} +mysql> USE my_database; +``` + +This command tells the server to use `my_database` for all subsequent SQL commands. Now, any SQL operations you perform will apply to `my_database`. + +## Database management + +* [Modify Tables](modify-tables.md) +* [Isolation Levels](isolation-levels.md) +* [Transaction Management](transaction-mgmt.md) +* [Views](views.md) \ No newline at end of file diff --git a/docs/delete.md b/docs/delete.md new file mode 100644 index 00000000000..92e85bf4d4c --- /dev/null +++ b/docs/delete.md @@ -0,0 +1,47 @@ +# DELETE statement + +The DELETE statement removes one or more rows from a table based on specified conditions. It allows developers to selectively delete data from a table, providing a way to manage and maintain the database by removing unnecessary or outdated records. + +## Advantages and Disadvantages of Using DELETE Statement + +| Trade-offs | Description | +|--------------|------------------------------------------------------------------------------------------------------------------------------------| +| Advantages | Allows selective removal of specific rows from a table, helping to maintain data integrity and manage database resources efficiently. | +| | Can be combined with WHERE clause to delete rows that meet certain conditions, providing flexibility in data manipulation. | +| | Provides a straightforward way to remove unwanted data without affecting the structure of the table or other related tables. | +| Disadvantages| Deleting large amounts of data can impact performance and may require careful consideration to avoid unintended consequences. | +| | Deletes are permanent and irreversible, so it's crucial to double-check conditions and backup data before executing DELETE queries. | + +## Syntax of DELETE Statement + +The statement has the following options: + +| Option | Description | +|---|---| +| `DELETE FROM table_name` | This clause specifies the table from which you want to delete rows. | +| `WHERE condition` (Optional) | This clause filters the rows to be deleted based on a specific condition. If omitted, all rows in the table will be deleted. | + +The syntax of the DELETE statement is as follows: + +```text +DELETE FROM table_name +[WHERE condition]; +``` + +## Example of DELETE Statement + +This example deletes all rows from the `orders` table where the `order_date` is before January 1, 2023. + +```{.bash data-prompt="mysql>"} +DELETE FROM orders +WHERE order_date < '2023-01-01'; +``` + +Fundamental SQL links: + +* [Common SQL](docs/common-sql.md) +* [SQL Basics](docs/sql-basics.md) +* [SELECT](docs/select.md) +* [INSERT](docs/insert.md) +* [UPDATE](docs/update.md) +* [SQL Operators](docs/sql-operators.md) \ No newline at end of file diff --git a/docs/functions.md b/docs/functions.md new file mode 100644 index 00000000000..c9b2f6141c8 --- /dev/null +++ b/docs/functions.md @@ -0,0 +1,60 @@ +# Functions + +A function in MySQL is a reusable block of code that performs a specific task and returns a value. It allows users to encapsulate logic, modularize code, and perform complex calculations or data manipulations. + +## Advantages of Using Functions: + +| Benefits | Description | +|-----------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Reusability | Functions can be reused multiple times in different parts of a SQL statement or query, reducing code duplication and promoting code modularity and maintainability. | +| Encapsulation | Functions encapsulate logic and calculations, making it easier to understand and manage complex operations within the database. | +| Performance | Functions can improve query performance by reducing the amount of data transferred between the database server and the client application. | +| Customization | Functions allow users to create custom data transformations and calculations tailored to specific business requirements, enhancing the flexibility of the database. | + +## Disadvantages of Using Functions: + +| Disadvantages | Description | +|-----------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Performance | Functions may introduce performance overhead, particularly if they involve complex computations or require access to large datasets. | +| Maintenance | Functions require maintenance to keep them synchronized with changes to the underlying data model or business logic. Changes may impact the behavior of dependent queries. | +| Portability | Functions written in MySQL may not be compatible with other database systems, limiting the portability of applications and databases. | +| Security | Improperly designed or implemented functions may pose security risks, such as SQL injection vulnerabilities or unauthorized access to sensitive data. | + +## Create function + +```{.bash data-prompt="mysql>"} +mysql> CREATE FUNCTION calculate_discount (total_amount DECIMAL(10, 2)) RETURNS DECIMAL(10, 2) + -> BEGIN + -> DECLARE discount DECIMAL(10, 2); + -> IF total_amount > 100 THEN + -> SET discount = total_amount * 0.1; + -> ELSE + -> SET discount = 0; + -> END IF; + -> RETURN discount; + -> END; +``` + +## Call function + +```{.bash data-prompt="mysql>"} +mysql> SELECT calculate_discount(120); +``` + +## Drop function + +```{.bash data-prompt="mysql>"} +mysql> DROP FUNCTION IF EXISTS calculate_discount; +``` + +## Advanced SQL features + +- [Data Types Basic](data-types-basic.md) +- [SQL Conventions](sql-conventions.md) +- [SQL Errors](sql-errors.md) +- [SQL Syntax](sql-syntax.md) +- [Stored Procedures](stored-procedures.md) +- [Stored Procedure Error Handling](stored-procedure-error-handling.md) +- [Stored Procedure Variables](stored-procedure-variables.md) +- [Triggers](triggers.md) +- [Troubleshooting SQL](troubleshooting-sql.md) \ No newline at end of file diff --git a/docs/insert.md b/docs/insert.md new file mode 100644 index 00000000000..40bd5aba4a5 --- /dev/null +++ b/docs/insert.md @@ -0,0 +1,52 @@ +# INSERT statement + +In MySQL, the INSERT statement adds new rows of data to a table. It follows a simple syntax pattern that beginners can easily understand. + +| Trade-Offs | Description | +|-----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Advantages | - Allows for efficient addition of new data into the database. | +| | - Provides flexibility to insert data into specific columns or all columns of a table. | +| | - Supports inserting multiple rows with a single INSERT statement. | +| | - Can be used in conjunction with SELECT statements to insert data from one table into another. | +| Disadvantages | - May result in performance overhead, especially when inserting large volumes of data or when indexes need to be updated. | +| | - Requires proper error handling to deal with constraints, such as primary key or unique constraints, to prevent duplicate entries. | +| | - Limited functionality for bulk inserts compared to specialized tools or techniques like bulk loading utilities. | + +Syntax of the INSERT Statement: + +| Option | Description | +|----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| INSERT INTO | This keyword indicates that you are performing an insertion operation into a table. | +| table_name | This is the name of the table where you want to insert the data. | +| column1, column2, ...| These are optional and specify the columns into which you want to insert data. If omitted, values must be provided for all columns in the table, in the same order as they are defined in the table. | +| VALUES | This keyword introduces the list of values to be inserted into the specified columns. Alternatively, you can use the SELECT statement to retrieve data from another table and insert it into the specified columns. | +| value1, value2, ... | These are the values to be inserted into the corresponding columns. The number and order of values must match the number and order of columns specified in the INSERT INTO clause. | + +The number of values in the `VALUES` clause must always match the number of columns specified or the total number of columns in the table. + +To insert data into a table, you use the INSERT INTO statement followed by the table name and a list of column names (if specified) or the `VALUES` keyword, followed by the values you want to insert into the table. + +```sql +INSERT INTO table_name (column1, column2, ...) +VALUES (value1, value2, ...); +``` + +In this example, we are doing the following: + +- Inserting a new row into the "employees" table. + +- The values 1, 'John Doe', and 50000 are being inserted into the "id", "name", and "salary" columns, respectively. + +```{.bash data-prompt="mysql>"} +mysql> INSERT INTO employees (id, name, salary) + VALUES (1, 'John Doe', 50000); +``` + +Fundamental SQL links: + +* [Common SQL](docs/common-sql.md) +* [SQL Basics](docs/sql-basics.md) +* [SELECT](docs/select.md) +* [DELETE](docs/delete.md) +* [UPDATE](docs/update.md) +* [SQL Operators](docs/sql-operators.md) \ No newline at end of file diff --git a/docs/isolation-levels.md b/docs/isolation-levels.md new file mode 100644 index 00000000000..70d31740b51 --- /dev/null +++ b/docs/isolation-levels.md @@ -0,0 +1,61 @@ +# Isolation levels + +In databases, isolation levels define how transactions interact with each other and the data they access. They determine the level of concurrency and consistency in a multi-user database environment. + +In MySQL, there are four isolation levels available, each offering different trade-offs between concurrency and consistency: + +Each isolation level offers a different balance between concurrency and consistency, and the choice depends on the application's specific requirements. By selecting the appropriate isolation level, developers can ensure their MySQL database applications' desired data integrity and performance level. + + +## Read Uncommitted + +In the Read Uncommitted isolation level, transactions can read data that has been modified by other transactions but not yet committed. This level allows for the highest concurrency but can lead to dirty reads. + +```{.bash data-prompt="mysql>"} +SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; + +-- Perform a SELECT query to read uncommitted data +SELECT * FROM table_name; +``` + +## Read Committed + +In Read Committed isolation level, transactions can only read data that has been committed by other transactions. This level prevents dirty reads but allows for non-repeatable reads and phantom reads. + +```{.bash data-prompt="mysql>"} +SET TRANSACTION ISOLATION LEVEL READ COMMITTED; + +-- Perform a SELECT query to read committed data +SELECT * FROM table_name; +``` + +## Repeatable Read + +In Repeatable Read isolation level, transactions can only read data that has been committed by other transactions at the start of the transaction. This level prevents dirty reads and non-repeatable reads but allows for phantom reads. + +```{.bash data-prompt="mysql>"} +SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; + +-- Perform a SELECT query to read data consistently within the transaction +SELECT * FROM table_name; +``` + +## Serializable + +In Serializable isolation level, transactions are executed serially, preventing any concurrent access to the data. This level provides the highest level of isolation but can lead to reduced concurrency and potential deadlock situations. + +```{.bash data-prompt="mysql>"} +SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; + +-- Perform a SELECT query within a serializable transaction +SELECT * FROM table_name; +``` + +These examples demonstrate how to set and use different isolation levels in SQL transactions, each providing consistency and concurrency control. + +## Database management + +* [Database](database.md) +* [Modify Tables](modify-tables.md) +* [Transaction Management](transaction-mgmt.md) +* [Views](views.md) diff --git a/docs/modify-tables.md b/docs/modify-tables.md new file mode 100644 index 00000000000..cdcbadde378 --- /dev/null +++ b/docs/modify-tables.md @@ -0,0 +1,33 @@ +# Modify a table + +The `ALTER TABLE` command acts like a toolkit that allows you to change the structure of existing tables. You can add new sections (columns), remove old ones, or change how information is stored [(data types)](data-types-basic.md). This command helps you adapt your database to new needs or improve efficiency. + +## Things to Watch Out For + +* Data loss: Be careful when modifying tables! Deleting a section (column) or changing its format might erase existing data in that section. + +* Slowdowns: Altering large tables or making complex changes can slow down the database, especially during busy times. It might take longer for things to work while the changes are applied. + +* Locks: MySQL might temporarily lock the tables you're working on when making changes. This operation means other users can't access or modify that data until the changes are complete, which can cause delays for others. + +## Modify table example + +After a table has been created, you may need to modify its structure or properties. Percona Server for MySQL provides the `ALTER TABLE` command for making such modifications. You can add, modify, or drop columns, change data types, add constraints, and more using this command. + +The following is an example using an `ALTER TABLE` command: + +```{.bash data-prompt="mysql>"} +mysql> ALTER TABLE users +ADD COLUMN age INT, +MODIFY COLUMN email VARCHAR(255), +DROP COLUMN username; +``` + +## Database management + +* [Database](database.md) +* [Tables](table.md) +* [Create table](create-table.md) +* [Isolation Levels](isolation-levels.md) +* [Transaction Management](transaction-mgmt.md) +* [Views](views.md) diff --git a/docs/select.md b/docs/select.md new file mode 100644 index 00000000000..847d5beb449 --- /dev/null +++ b/docs/select.md @@ -0,0 +1,32 @@ +# SELECT statement + +The syntax of a SELECT statement in MySQL is straightforward. You start with the keyword SELECT, followed by the columns from which you want to retrieve data. You can specify the table from which to retrieve data using the FROM keyword. Optionally, you can include conditions to filter the results using the WHERE clause. + +The following table is a breakdown of the syntax: + +| Syntax | Description | +|---------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **SELECT** | This keyword indicates that you want to retrieve data from the database. | +| **Columns** | Specify the columns you want to retrieve data from. You can use the asterisk (*) to select all columns or specify individual column names separated by commas. | +| **FROM** | Use the FROM keyword to specify the table from which you want to retrieve data. | +| **WHERE (optional)** | If you want to filter the results based on specific conditions, you can use the WHERE clause. This clause allows you to specify conditions using comparison operators like =, >, <, etc., and logical operators like AND, OR, NOT. | + + +```text +SELECT column1, column2 +FROM table_name +WHERE condition; +``` + +- `SELECT column1, column2` specifies that you want to retrieve data from column1 and column2. +- `FROM table_name` specifies the table from which you want to retrieve data. +- `WHERE condition` is an optional clause that filters the results based on the specified condition. + +Fundamental SQL links: + +* [Common SQL](docs/common-sql.md) +* [SQL Basics](docs/sql-basics.md) +* [INSERT](docs/insert.md) +* [DELETE](docs/delete.md) +* [UPDATE](docs/update.md) +* [SQL Operators](docs/sql-operators.md) \ No newline at end of file diff --git a/docs/sql-basics.md b/docs/sql-basics.md new file mode 100644 index 00000000000..23735e24af7 --- /dev/null +++ b/docs/sql-basics.md @@ -0,0 +1,24 @@ +# SQL basics + +SQL stands for Structured Query Language. It's a powerful tool used to communicate with databases. Think of a database as a digital filing cabinet where you store and organize information. SQL is like the language you use to talk to that filing cabinet and ask questions or tell it what you want to do with the data inside. + +With SQL, you can do a variety of tasks: + +* Retrieve Data: You can ask the database to give you specific information, like all the names of customers who bought a certain product. + +* Insert Data: You can add new information into the database, such as adding a new customer's details. + +* Update Data: If information changes, like a customer's address, you can update it in the database. + +* Delete Data: If information is no longer needed, you can remove it from the database. + +SQL provides a standardized way to interact with a database. It uses simple commands and statements to perform these tasks, making it easy to learn and use for managing data effectively. + +Fundamental SQL links: + +* [Common SQL](docs/common-sql.md) +* [SELECT](docs/select.md) +* [INSERT](docs/insert.md) +* [DELETE](docs/delete.md) +* [UPDATE](docs/update.md) +* [SQL Operators](docs/sql-operators.md) \ No newline at end of file diff --git a/docs/sql-conventions.md b/docs/sql-conventions.md new file mode 100644 index 00000000000..0dcd53fb3f0 --- /dev/null +++ b/docs/sql-conventions.md @@ -0,0 +1,84 @@ +# SQL conventions + +Sure, here's a description of common SQL style conventions with examples using common MySQL commands: + +## Naming Conventions + +Naming conventions refer to the rules and guidelines for naming database objects such as tables, columns, indexes, and stored procedures. + +- **Use descriptive names**: Choose names that clearly describe the purpose or content of the database object. + + ```{.bash data-prompt="mysql>"} + mysql> CREATE TABLE users ( + mysql> user_id INT AUTO_INCREMENT PRIMARY KEY, + mysql> username VARCHAR(50), + mysql> email VARCHAR(100) + mysql> ); + ``` + +- **Avoid abbreviations**: Prefer full and meaningful words over abbreviations to enhance readability and understanding. + + ```{.bash data-prompt="mysql>"} + mysql> ALTER TABLE customers + mysql> ADD COLUMN date_of_birth DATE; + ``` + +## Indentation and Formatting + +Indentation and formatting conventions improve the readability and maintainability of SQL code. + +- **Indent SQL statements**: Indent SQL statements consistently to show the logical structure of queries and commands. + + ```{.bash data-prompt="mysql>"} + mysql> SELECT + mysql> user_id, + mysql> username, + mysql> email + mysql> FROM + mysql> users + mysql> WHERE + mysql> user_id = 1; + ``` + +- **Use consistent casing**: Use consistent casing for keywords, identifiers, and SQL functions to improve code consistency. + + ```{.bash data-prompt="mysql>"} + mysql> SELECT + mysql> first_name, + mysql> last_name, + mysql> CONCAT_WS(' ', first_name, last_name) AS full_name + mysql> FROM + mysql> customers; + ``` + +## Comments + +Comments are annotations added to SQL code to explain its purpose, logic, or any other relevant information. + +- **Document intent**: Use comments to document the intent or purpose of SQL statements and code blocks. + + ```{.bash data-prompt="mysql>"} + mysql> -- Retrieve all active users + mysql> SELECT * FROM users WHERE status = 'active'; + ``` + +- **Avoid redundant comments**: Avoid adding comments that merely repeat the code without adding meaningful information. + + ```{.bash data-prompt="mysql>"} + mysql> -- This query retrieves all users + mysql> SELECT * FROM users; + ``` + +These SQL style conventions help maintain consistency, readability, and clarity in SQL code, making it easier to understand, debug, and maintain. + +## Advanced SQL features + +* [Data Types Basic](data-types-basic.md) +* [Functions](functions.md) +* [SQL Errors](sql-errors.md) +* [SQL Syntax](sql-syntax.md) +* [Stored Procedures](stored-procedures.md) +* [Stored Procedure Error Handling](stored-procedure-error-handling.md) +* [Stored Procedure Variables](stored-procedure-variables.md) +* [Triggers](triggers.md) +* [Troubleshooting SQL](troubleshooting-sql.md) \ No newline at end of file diff --git a/docs/sql-errors.md b/docs/sql-errors.md new file mode 100644 index 00000000000..98f5aa47967 --- /dev/null +++ b/docs/sql-errors.md @@ -0,0 +1,60 @@ +# Common SQL errors + +Error handling in SQL commands involves managing and responding to errors that may occur during database operations. It ensures that the database remains consistent and provides feedback to users when errors occur. + +## SELECT statement + +When executing a SELECT statement, errors may occur due to invalid syntax, missing tables, or insufficient permissions. + +```{.bash data-prompt="mysql>"} +mysql> SELECT * FROM non_existent_table; +ERROR 1146 (42S02): Table 'database_name.non_existent_table' doesn't exist +``` + +## INSERT Statement + +Errors can occur during INSERT operations if data violates constraints or exceeds column limits. + +```{.bash data-prompt="mysql>"} +mysql> INSERT INTO table_name (id, name) VALUES (1, 'John'); +ERROR 1136 (21S01): Column count doesn't match value count at row 1 +``` + +## UPDATE Statement + +UPDATE statements may encounter errors when attempting to modify non-existent rows or violating constraints. + +```{.bash data-prompt="mysql>"} +mysql> UPDATE table_name SET non_existent_column = 'value'; +ERROR 1054 (42S22): Unknown column 'non_existent_column' in 'field list' +``` + +## DELETE Statement + +Errors in DELETE statements can occur if the WHERE clause condition is invalid or violates constraints. + +```{.bash data-prompt="mysql>"} +mysql> DELETE FROM table_name WHERE id = 'non_numeric_value'; +ERROR 1054 (42S22): Unknown column 'non_numeric_value' in 'where clause' +``` + +## DDL Statements (CREATE, ALTER, DROP) + +DDL statements may fail due to syntax errors, existing object conflicts, or insufficient privileges. + +```{.bash data-prompt="mysql>"} +mysql> CREATE TABLE existing_table (id INT PRIMARY KEY); +ERROR 1050 (42S01): Table 'existing_table' already exists +``` + +## Advanced SQL features + +- [Data Types Basic](data-types-basic.md) +- [Functions](functions.md) +- [SQL Conventions](sql-conventions.md) +- [SQL Syntax](sql-syntax.md) +- [Stored Procedures](stored-procedures.md) +- [Stored Procedure Error Handling](stored-procedure-error-handling.md) +- [Stored Procedure Variables](stored-procedure-variables.md) +- [Triggers](triggers.md) +- [Troubleshooting SQL](troubleshooting-sql.md) \ No newline at end of file diff --git a/docs/sql-operators.md b/docs/sql-operators.md new file mode 100644 index 00000000000..612ff7cbc5f --- /dev/null +++ b/docs/sql-operators.md @@ -0,0 +1,90 @@ +# SQL operators + +## Purpose of SQL Operators + +SQL operators are symbols or keywords used to perform operations on data in SQL queries. They allow developers to manipulate and compare data, perform calculations, and filter results based on specified conditions. + +Advantages and Disadvantages of Using SQL Operators: + +| Trade-Offs | Description | +|-----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Advantages | - Enables developers to perform various operations on data, such as arithmetic calculations, comparisons, logical operations, and string concatenation. | +| | - Provides flexibility in crafting complex queries to extract, transform, and manipulate data according to specific requirements. | +| | - Enhances query efficiency by allowing filtering and sorting of data directly within SQL queries, reducing the need for post-processing in application code. | +| Disadvantages | - May introduce complexity to queries, especially when multiple operators are combined or when dealing with complex logical conditions. | +| | - Requires careful consideration of operator precedence and evaluation order to ensure the desired results are obtained. | +| | - Can sometimes result in less readable or maintainable queries, particularly for developers unfamiliar with the SQL syntax or operators being used. | + +Syntax of Using SQL Operators: + +| Option | Description | +|------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Arithmetic | Arithmetic operators such as `+`, `-`, `*`, `/`, and `%` are used to perform mathematical calculations on numeric data. | +| Comparison | Comparison operators like `=`, `<>`, `<`, `>`, `<=`, and `>=` are used to compare values and determine their relationship. | +| Logical | Logical operators such as `AND`, `OR`, and `NOT` are used to perform logical operations on boolean values or expressions. | +| Concatenation | The `CONCAT()` function or `||` operator is used to concatenate strings together. | +| Bitwise | Bitwise operators like `&`, `|`, `^`, `~`, `<<`, and `>>` are used to perform bitwise operations on binary data. | +| Assignment | The `=` and `:=` operators are used to assign values to variables or columns. | +| In | The `IN` operator is used to check whether a value matches any value in a list or subquery. | +| Like | The `LIKE` operator is used to compare a value to a pattern using wildcard characters `%` and `_`. | + +Example of Using SQL Operators: + +- **Arithmetic Operator Example**: + +```text +mysql> SELECT 10 * 5; -- Multiplication +``` + +- **Comparison Operator Example**: + +```text +mysql> SELECT * FROM products WHERE price > 100; -- Select products with price greater than 100 +``` + +- **Logical Operator Example**: + +```text +mysql> SELECT * FROM customers WHERE age >= 18 AND age <= 30; -- Select customers aged between 18 and 30 +``` + +- **Concatenation Operator Example**: + +```text +mysql> SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees; -- Concatenate first name and last name +``` + +- **Bitwise Operator Example**: + +```text +mysql> SELECT id, name FROM permissions WHERE permission_flags & 4 = 4; -- Select permissions with specific flag +``` + +- **Assignment Operator Example**: + +```text +mysql> SET @total_sales := 500; -- Assigning a value to a variable +``` + +- **In Operator Example**: + +```text +mysql> SELECT * FROM products WHERE category_id IN (1, 2, 3); -- Select products in specified categories +``` + +- **Like Operator Example**: + +```text +mysql> SELECT * FROM customers WHERE email LIKE '%@example.com'; -- Select customers with email domain example.com +``` + +These examples illustrate how SQL operators are used in Percona Server for MySQL queries to perform various data operations. + +Fundamental SQL links: + +- [Common SQL](docs/common-sql.md) +- [SQL Basics](docs/sql-basics.md) +- [SELECT](docs/select.md) +- [INSERT](docs/insert.md) +- [DELETE](docs/delete.md) +- [UPDATE](docs/update.md) \ No newline at end of file diff --git a/docs/sql-syntax.md b/docs/sql-syntax.md new file mode 100644 index 00000000000..a58509aaa15 --- /dev/null +++ b/docs/sql-syntax.md @@ -0,0 +1,46 @@ +# SQL syntax + +SQL (Structured Query Language) is a standardized language used to communicate with databases. Percona Server for MySQL follows SQL syntax, which consists of commands and statements for performing various operations on databases and their objects. + +The SQL syntax includes commands for data manipulation (e.g., SELECT, INSERT, UPDATE, DELETE), data definition (e.g., CREATE, ALTER, DROP), data control (e.g., GRANT, REVOKE), and transaction control (e.g., COMMIT, ROLLBACK). + + +| Syntax type | Description | +|--------------------------|------------------------------------------------------------------------------------------------------------------| +| Data Manipulation | MySQL supports powerful data manipulation features, allowing you to retrieve, insert, update, and delete data | +| Data Definition | With MySQL, you can define the structure of your database objects such as tables, indexes, views, and stored procedures | +| Data Control | MySQL provides commands for controlling access to database objects and defining user privileges | +| Transaction Management | MySQL supports transactions, which allow you to group multiple SQL statements into a single unit of work | +| Stored Procedures | MySQL allows you to define stored procedures and functions using SQL syntax | +| Triggers | MySQL supports triggers, which are special types of stored procedures that automatically execute in response to specific events | +| Indexes | MySQL provides features for optimizing query performance, including the ability to create indexes on columns | +| Views | MySQL allows you to create views, which are virtual tables generated from SQL queries | +| Data Types | MySQL supports a wide range of data types for storing different types of data | + +These features make MySQL a powerful and versatile database management system, capable of handling a wide range of database tasks efficiently and effectively using SQL syntax. + +While MySQL SQL syntax may deviate from the standard SQL syntax in some aspects, it generally aims to be compatible with standard SQL to ensure interoperability with other database systems and tools. However, developers should be aware of these differences and consult the MySQL documentation for guidance when writing SQL queries and statements. + +MySQL SQL syntax largely adheres to the standard SQL syntax, but there are some differences and extensions that set it apart: + +| Syntax | Description | +|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Data Types | MySQL supports additional data types beyond the standard SQL specification, such as `ENUM`, `SET`, and `BOOLEAN`. These data types provide additional flexibility but may not be compatible with other database systems. | +| String Quoting | MySQL allows both single quotes (`'`) and double quotes (`"`) for string literals, while standard SQL typically only uses single quotes. Additionally, MySQL supports backticks (`` ` ``) for quoting identifiers, which is not standard SQL syntax. | +| Case Sensitivity | By default, MySQL treats table and column names as case-insensitive, while standard SQL treats them as case-sensitive. However, this behavior can be changed by adjusting the server configuration. | +| LIMIT Clause | MySQL uses the `LIMIT` clause to restrict the number of rows returned by a query, while standard SQL uses the `FETCH FIRST` or `OFFSET` clauses for similar functionality. | +| AUTO_INCREMENT | MySQL uses the `AUTO_INCREMENT` attribute to automatically generate unique values for a column, while standard SQL uses `IDENTITY` or sequences for this purpose. | +| SQL Functions | MySQL provides additional built-in functions and extensions beyond the standard SQL functions. For example, MySQL has functions like `GROUP_CONCAT()` and `IFNULL()`, which may not be available in other database systems. | +| Storage Engines | MySQL supports multiple storage engines, each with its own set of features and capabilities. This option allows users to choose the most suitable storage engine for their specific requirements, but it introduces differences in behavior and syntax. | + +## Advanced SQL features + +- [Data Types Basic](data-types-basic.md) +- [Functions](functions.md) +- [SQL Conventions](sql-conventions.md) +- [SQL Errors](sql-errors.md) +- [Stored Procedures](stored-procedures.md) +- [Stored Procedure Error Handling](stored-procedure-error-handling.md) +- [Stored Procedure Variables](stored-procedure-variables.md) +- [Triggers](triggers.md) +- [Troubleshooting SQL](troubleshooting-sql.md) \ No newline at end of file diff --git a/docs/stored-procedure-error-handling.md b/docs/stored-procedure-error-handling.md new file mode 100644 index 00000000000..69a5f6afe08 --- /dev/null +++ b/docs/stored-procedure-error-handling.md @@ -0,0 +1,59 @@ +# Error handling in stored procedures + +Error handling in stored procedures allows developers to gracefully handle exceptions and errors that may occur during the execution of the procedure. It enables better control over error messages and the ability to perform custom actions in response to errors. + +## Advantages of Using Error Handling: + +| Benefits | Description | +|------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Graceful | Error handling provides a way to handle exceptions gracefully, preventing unexpected termination of the procedure and providing users with meaningful error messages. | +| Customized | Developers can customize error handling to perform specific actions based on the type of error encountered, such as logging errors, rolling back transactions, or retrying operations. | +| Control | Error handling gives developers greater control over error propagation and recovery, allowing them to handle errors at different levels of granularity and complexity. | +| Robustness | By implementing error handling, developers can make stored procedures more robust and resilient to unexpected conditions, enhancing the overall stability and reliability of the system. | + +## Disadvantages of Using Error Handling: + +| Disadvantages | Description | +|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Complexity | Error handling can introduce additional complexity to stored procedures, making them harder to understand, debug, and maintain, especially when dealing with nested error handling. | +| Overhead | Implementing error handling may add overhead in terms of code complexity and execution time, particularly for procedures with extensive error-checking logic or frequent error conditions. | +| Performance | Error handling may impact performance, especially in scenarios where error-checking logic needs to be executed repeatedly or in tight loops, leading to increased CPU and resource utilization. | +| Dependency | Error handling can create dependencies between stored procedures and error-handling routines, making it challenging to modify or refactor procedures without affecting error handling. | + +To add error handling to a stored procedure, developers can use constructs like `DECLARE`, `SIGNAL`, `RESIGNAL`, and `HANDLER` to declare variables, raise errors, and handle exceptions. Here's an example of error handling in a stored procedure: + +```{.bash data-prompt="mysql>"} +mysql> DELIMITER // +mysql> CREATE PROCEDURE my_procedure() + -> BEGIN + -> DECLARE exit handler for sqlexception + -> BEGIN + -> -- Handle SQL exceptions + -> ROLLBACK; + -> SELECT 'An error occurred: ' || SQLSTATE(); + -> END; + -> + -> -- Procedure logic here + -> END // +mysql> DELIMITER ; +``` + +In this example, the `DECLARE` statement declares an exit handler for SQL exceptions. Inside the handler block, the procedure rolls back any changes made and returns a custom error message with the SQL state. + +```{.bash data-prompt="mysql>"} +mysql> CALL my_procedure(); +``` + +This command executes the stored procedure and triggers the error handling logic if an exception occurs during execution. + +## Advanced SQL features + +* [Data Types Basic](data-types-basic.md) +* [Functions](functions.md) +* [SQL Conventions](sql-conventions.md) +* [SQL Errors](sql-errors.md) +* [SQL Syntax](sql-syntax.md) +* [Stored Procedures](stored-procedures.md) +* [Stored Procedure Variables](stored-procedure-variables.md) +* [Triggers](triggers.md) +* [Troubleshooting SQL](troubleshooting-sql.md) \ No newline at end of file diff --git a/docs/stored-procedure-variables.md b/docs/stored-procedure-variables.md new file mode 100644 index 00000000000..cf07c159d7f --- /dev/null +++ b/docs/stored-procedure-variables.md @@ -0,0 +1,44 @@ +# Variables in stored procedures, functions, and triggers + +To add a variable in MySQL, you use the `DECLARE` keyword within the context of a stored program, such as a stored procedure, function, or trigger. The `DECLARE` keyword is used to define a new variable along with its data type and optionally, its initial value. + + +| Value | Description | +|-----------------|---------------------------------------------------------------------------------------------------------------------------------------| +| variable_name | This is the name of the variable you want to declare. Variable names must follow the rules for identifiers in MySQL. | +| data_type | This specifies the data type of the variable, such as `INT`, `VARCHAR`, `DECIMAL`, `DATE`, etc. | +| default_value | This is an optional parameter that specifies the default value for the variable. If not provided, the variable will be initialized to `NULL` by default. | + +```{.bash data-prompt="mysql>"} +DECLARE variable_name data_type [DEFAULT default_value]; +``` + +- When you declare a variable using the `DECLARE` keyword, you are essentially telling MySQL to reserve space in memory to store a value of the specified data type. + +- Variables in MySQL are scoped to the block in which they are declared. This means they can only be used within the block of code (for example, stored procedure, function) in which they are declared. + +- Variables can be used to store and manipulate values within the context of the stored program. They are commonly used for temporary storage of intermediate results, loop counters, or parameters passed to the program. + +```{.bash data-prompt="mysql>"} +mysql> DECLARE total_sales DECIMAL(10, 2) DEFAULT 0.0; +``` + +This statement has the following settings: + +| Description | Value | +|----------------------------------------------------------------------|--------------------------------------------| +| `total_sales` is the name of the variable. | `total_sales` | +| `DECIMAL(10, 2)` specifies that `total_sales` will hold decimal numbers with a precision of 10 digits and a scale of 2 decimal places. | `DECIMAL(10, 2)` | +| `DEFAULT 0.0` sets the initial value of `total_sales` to 0.0. If not provided, the default value would be `NULL`. | `DEFAULT 0.0` | + +## Advanced SQL features + +* [Data Types Basic](data-types-basic.md) +* [Functions](functions.md) +* [SQL Conventions](sql-conventions.md) +* [SQL Errors](sql-errors.md) +* [SQL Syntax](sql-syntax.md) +* [Stored Procedures](stored-procedures.md) +* [Stored Procedure Error Handling](stored-procedure-error-handling.md) +* [Triggers](triggers.md) +* [Troubleshooting SQL](troubleshooting-sql.md) \ No newline at end of file diff --git a/docs/stored-procedures.md b/docs/stored-procedures.md new file mode 100644 index 00000000000..f37ed28d415 --- /dev/null +++ b/docs/stored-procedures.md @@ -0,0 +1,64 @@ +# Stored Procedures + +A stored procedure is a set of pre-defined SQL statements stored in the database and executed as a single unit. It allows users to execute complex operations without rewriting the same code multiple times. + +| Benefit | Description | +|-----------------------|----------------------------------------------------------------------------------------------------------------------------------| +| Code Reusability | Stored procedures can be reused multiple times in different parts of an application, reducing code duplication. | +| Improved Performance | By executing multiple SQL statements in a single call, stored procedures can reduce network traffic and improve performance. | +| Enhanced Security | Users can execute stored procedures without needing direct access to underlying tables, improving security and data integrity. | +| Centralized Logic | Business logic is encapsulated within stored procedures, making it easier to manage and maintain. | + +| Disadvantage | Description | +|------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Difficulty in Debugging | Stored procedures can be challenging to debug, as they are executed on the database server rather than within the application code. | +| Vendor Lock-in | Stored procedures are specific to a particular database system, making it difficult to migrate to another database platform. | +| Limited Portability | Stored procedures written in one database system may not be compatible with other systems, limiting portability and interoperability. | + +## Stored Procedure examples + +### Create a Stored Procedure + +```{.bash data-prompt="mysql>"} +mysql> DELIMITER // +mysql> CREATE PROCEDURE GetCustomerDetails (IN customerId INT) + -> BEGIN + -> SELECT * FROM customers WHERE id = customerId; + -> END // +mysql> DELIMITER ; +``` + +### Call a Stored Procedure + +```{.bash data-prompt="mysql>"} +mysql> CALL GetCustomerDetails(123); +``` + +### Modify a Stored Procedure + +```{.bash data-prompt="mysql>"} +mysql> DELIMITER // +mysql> ALTER PROCEDURE GetCustomerDetails (IN customerId INT) + -> BEGIN + -> SELECT name, email FROM customers WHERE id = customerId; + -> END // +mysql> DELIMITER ; +``` + +### Drop a Stored Procedure + +```{.bash data-prompt="mysql>"} +mysql> DROP PROCEDURE IF EXISTS GetCustomerDetails; +``` + +## Advanced SQL features + +* [Data Types Basic](data-types-basic.md) +* [Functions](functions.md) +* [SQL Conventions](sql-conventions.md) +* [SQL Errors](sql-errors.md) +* [SQL Syntax](sql-syntax.md) +* [Stored Procedure Error Handling](stored-procedure-error-handling.md) +* [Stored Procedure Variables](stored-procedure-variables.md) +* [Triggers](triggers.md) +* [Troubleshooting SQL](troubleshooting-sql.md) diff --git a/docs/table.md b/docs/table.md new file mode 100644 index 00000000000..b489f828ccb --- /dev/null +++ b/docs/table.md @@ -0,0 +1,54 @@ +# Introduction to database tables + +A database table is a collection of data organized into rows and columns. Each table consists of records (rows) and fields (columns). Tables help organize and manage data efficiently. + +### Advantages + +| Advantages | Description | +|-------------|--------------| +| **Organized Data** | Tables allow you to organize data into rows and columns, making it easy to understand and manage. | +| **Efficient Queries** | You can use SQL queries to quickly search, filter, and retrieve data from tables. | +| **Data Integrity** | Tables support constraints like primary keys and foreign keys, ensuring data integrity and consistency. | +| **Scalability** | You can add or modify tables as your data grows, making it easy to scale your database. | +| **Relational Management** | Tables allow you to create relationships between different sets of data, making it easier to manage complex datasets. | + +### Disadvantages + +| Disadvantages | Description | +|----------------|--------------| +| **Complexity** | Designing and maintaining tables, especially with relationships, can become complex and time-consuming. | +| **Performance Issues** | Large tables with many rows can lead to performance issues, requiring optimization and indexing. | +| **Storage Overhead** | Tables with many columns or large data types can consume significant storage space. | +| **Maintenance** | Regular maintenance tasks, such as backups and indexing, are necessary to ensure optimal performance and data integrity. | +| **Learning Curve** | Beginners may find it challenging to learn SQL and understand how to design and manage tables effectively. | + +## Permissions required + +To create a table in a database, you need appropriate permissions granted to your database user account. These permissions are typically managed by the database administrator (DBA) or system administrator. Database permissions control what actions a user can perform on a database. In the context of creating a table, the user needs specific permissions related to database management. + +| Permission | Description | +|--------------|-------------| +| CREATE TABLE | The most fundamental permission required to create a table is the CREATE TABLE permission. This permission allows the user to create new tables within the database. | +| CREATE | In addition to CREATE TABLE, the user might also need the more general CREATE permission. This permission grants the ability to create other database objects besides tables, such as indexes, views, or stored procedures. | +| ALTER | Depending on the database configuration, the user might also need the ALTER permission. This permission allows the user to modify the structure of existing tables, such as adding or removing columns. | + + +## Create a table + +To create a table, use the `CREATE TABLE` command. Follow it with the table name and define the columns and their data types. For example, to create a table named `customers` with columns for `id`, `name`, and `email`, use this command: + +```mysql +CREATE TABLE customers ( + id INT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100), + email VARCHAR(100) +); +``` + +## Database management + +* [Database](database.md) +* [Create table](create-table.md) +* [Isolation Levels](isolation-levels.md) +* [Transaction Management](transaction-mgmt.md) +* [Views](views.md) \ No newline at end of file diff --git a/docs/transaction-mgmt.md b/docs/transaction-mgmt.md new file mode 100644 index 00000000000..c79610ffadb --- /dev/null +++ b/docs/transaction-mgmt.md @@ -0,0 +1,31 @@ +# Transaction management + +A database transaction is a unit of work performed within a database management system (DBMS) that must be executed atomically and consistently. A transaction represents a series of operations (such as queries, inserts, updates, or deletes) that are treated as a single, indivisible unit. Transactions ensure data integrity by guaranteeing that all of the transaction's operations are completed successfully and permanently saved to the database (committed) or none of them are applied (rolled back). + +Percona Server for MySQL provides features for managing transactions to ensure the consistency and reliability of data.Transactions in Percona Server for MySQL are typically managed using the following commands and techniques: + +- START TRANSACTION: This command begins a new transaction. Once started, all subsequent SQL statements will be part of the transaction until it is either committed or rolled back. + +- COMMIT: The COMMIT command is used to save the changes made during the transaction to the database permanently. Once committed, the changes become visible to other transactions. + +- ROLLBACK: The ROLLBACK command is used to undo the changes made during the transaction and restore the database to its state before the transaction begins. It cancels any modifications made within the transaction. + +- SAVEPOINT: SAVEPOINTs are markers within a transaction that allow you to set points to which you can later roll back. They provide a way to partially undo changes within a transaction without rolling back the entire transaction. + +Transactions in Percona Server for MySQL are ACID-compliant, meaning they adhere to the principles of Atomicity, Consistency, Isolation, and Durability: + +| Type | Description | +|-------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Atomicity | Transactions are atomic, meaning that all the operations within a transaction are treated as a single unit of work. Either all operations are completed successfully, or none of them are applied. | +| Consistency | Transactions ensure that the database remains in a consistent state before and after the transaction. Constraints, triggers, and other rules are enforced to maintain data integrity. | +| Isolation | Transactions are isolated from each other, meaning that the changes made within one transaction are not visible to other transactions until the transaction is committed. | +| Durability | Once a transaction is committed, the changes made to the database are permanent and cannot be lost, even in the event of system failure. | + +Percona Server for MySQL supports different transaction isolation levels, such as READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE, which control how transactions interact with each other and with the data in the database. + +## Database management + +- [Database](database.md) +- [Modify Tables](modify-tables.md) +- [Isolation Levels](isolation-levels.md) +- [Views](views.md) \ No newline at end of file diff --git a/docs/triggers.md b/docs/triggers.md new file mode 100644 index 00000000000..e4df201d00f --- /dev/null +++ b/docs/triggers.md @@ -0,0 +1,73 @@ +# Triggers + + + +## Using triggers + +A trigger is a database object that automatically performs a specified action in response to certain events on a table or view. It allows users to enforce business rules, maintain data integrity, and automate tasks within the database. + +### Advantages of Using Triggers + +| Benefits | Description | +|---------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Data Integrity | Triggers can enforce data integrity constraints by automatically validating or modifying data before it is inserted, updated, or deleted in a table. | +| Audit Trails | Triggers can be used to create audit trails by recording changes made to the database, including who made the changes and when they occurred. | +| Simplified | Triggers simplify application logic by moving complex business rules and validation checks into the database, reducing the amount of code needed in the application layer. | +| Automated | Triggers automate repetitive tasks, such as updating denormalized data or sending notifications, by executing predefined actions in response to specified events. | + +### Disadvantages of Using Triggers + +| Disadvantages | Description | +|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Complexity | Triggers can add complexity to the database schema and make it harder to understand and maintain, especially when dealing with multiple triggers and complex logic. | +| Performance | Triggers may impact database performance, particularly if they involve complex operations or are triggered frequently, leading to increased overhead and slower response times. | +| Debugging | Triggers can be difficult to debug and troubleshoot, as they are executed automatically in response to events and may not provide detailed error messages or logging information. | +| Dependency | Triggers create dependencies between database objects, making it challenging to modify or refactor the database schema without considering the impact on existing triggers. | + + +### Create a before_insert trigger + +```{.bash data-prompt="mysql>"} +mysql> CREATE TRIGGER before_insert_customer + -> BEFORE INSERT ON customers + -> FOR EACH ROW + -> BEGIN + -> SET NEW.created_at = NOW(); + -> END; +``` + +### Create an after_update trigger + +```{.bash data-prompt="mysql>"} +mysql> CREATE TRIGGER after_update_inventory + -> AFTER UPDATE ON inventory + -> FOR EACH ROW + -> BEGIN + -> INSERT INTO inventory_changes (product_id, old_quantity, new_quantity, change_date) + -> VALUES (OLD.product_id, OLD.quantity, NEW.quantity, NOW()); + -> END; +``` + +### Drop a before_insert trigger + +```{.bash data-prompt="mysql>"} +mysql> DROP TRIGGER IF EXISTS before_insert_customer; +``` + +### Drop an after_update trigger + +```{.bash data-prompt="mysql>"} +mysql> DROP TRIGGER IF EXISTS after_update_inventory; +``` + +## Advanced SQL features + +* [Data Types Basic](data-types-basic.md) +* [Functions](functions.md) +* [SQL Conventions](sql-conventions.md) +* [SQL Errors](sql-errors.md) +* [SQL Syntax](sql-syntax.md) +* [Stored Procedures](stored-procedures.md) +* [Stored Procedure Error Handling](stored-procedure-error-handling.md) +* [Stored Procedure Variables](stored-procedure-variables.md) +* [Troubleshooting SQL](troubleshooting-sql.md) \ No newline at end of file diff --git a/docs/troubleshooting-sql.md b/docs/troubleshooting-sql.md new file mode 100644 index 00000000000..9cbd0230c4c --- /dev/null +++ b/docs/troubleshooting-sql.md @@ -0,0 +1,43 @@ +# Troubleshoot SQL code + +## Troubleshooting SQL Code + +To troubleshoot SQL code, follow these steps: + +| Action | Description | +|--------------|--------------------------------------------------------------------------------------------------------------------------------| +| Review Error Messages | Carefully read any error messages returned by the MySQL server. They often provide valuable clues about what went wrong. | +| Check Syntax | Verify that the SQL syntax is correct. A single typo or missing keyword can cause errors. | +| Verify Table and Column Names | Ensure that table and column names are spelled correctly and match the actual names in the database. | +| Test in Isolation | Test each part of the SQL statement separately to identify which part is causing the issue. | +| Use Logging Tools | Enable query logging or use debugging tools to track the execution of SQL queries and identify any issues. | +| Review Documentation | Consult the MySQL documentation to understand the correct usage of SQL statements and functions. | +| Seek Help | Don't hesitate to ask for help from more experienced developers or consult online forums and communities for assistance. | + +Troubleshooting SQL Code example: + +Suppose you have the following SQL query that is not returning the expected results: + +```text +SELECT * FORM users WHERE age = 30; +``` + +After reviewing the error message returned by MySQL, you notice a typo in the query. The keyword "FORM" should be "FROM". After correcting the typo, the query becomes: + +```text +SELECT * FROM users WHERE age = 30; +``` + +Now, the query should execute successfully and return the desired results. + +## Advanced SQL features + +* [Data Types Basic](data-types-basic.md) +* [Functions](functions.md) +* [SQL Conventions](sql-conventions.md) +* [SQL Errors](sql-errors.md) +* [SQL Syntax](sql-syntax.md) +* [Stored Procedures](stored-procedures.md) +* [Stored Procedure Error Handling](stored-procedure-error-handling.md) +* [Stored Procedure Variables](stored-procedure-variables.md) +* [Triggers](triggers.md) \ No newline at end of file diff --git a/docs/update.md b/docs/update.md new file mode 100644 index 00000000000..2eb460fef68 --- /dev/null +++ b/docs/update.md @@ -0,0 +1,52 @@ +# UPDATE statement + +## Purpose of the UPDATE Statement + +The UPDATE statement modifies existing records in a table. It allows developers to change the values of one or more columns in a specific row or set of rows based on certain conditions. + +Advantages and Disadvantages of Using the UPDATE Statement: + +| Trade-offs | Description | +|-------------|-------------------------------------------------------------------------------------------------------------------------------------------------| +| Advantages | - Allows for updating existing data without the need to delete and re-insert records. | +| | - Provides flexibility in modifying specific columns or rows based on specified conditions. | +| | - Can be used in conjunction with WHERE clause to update only selected rows, reducing unnecessary updates and improving performance. | +| | - Supports bulk updates, allowing multiple rows to be modified in a single statement. | +| Disadvantages | - Incorrectly formulated UPDATE statements can lead to unintended data changes or data loss. | +| | - Lack of proper WHERE clause can result in updating all rows in a table, potentially causing data corruption or performance issues. | +| | - May cause locking and contention issues in high-concurrency environments, impacting the performance of other queries accessing the same table. | + +Syntax of an UPDATE Statement: + +| Option | Description | +|---|---| +| `UPDATE table_name` | This clause specifies the name of the table you want to modify. | +| `SET column_name1 = value1, column_name2 = value2, ...` | This clause defines which columns you want to update and their corresponding new values. You can update multiple columns by separating them with commas. | +| `WHERE condition` (optional) | This clause specifies a condition that filters which rows in the table will be affected by the update. If omitted, all rows in the table will be updated. | + +```text +UPDATE table_name +SET column1 = value1, column2 = value2, ... +[WHERE condition]; +``` + +In this example, the statement does the following: + +- Modifies the `salary` column for employees in the 'Sales' department. + +- Increases the salary of each employee by 10% (`salary * 1.1`). + +```{.bash data-prompt="mysql>"} +UPDATE employees +SET salary = salary * 1.1 +WHERE department = 'Sales'; +``` + +Fundamental SQL links: + +* [Common SQL](docs/common-sql.md) +* [SQL Basics](docs/sql-basics.md) +* [SELECT](docs/select.md) +* [INSERT](docs/insert.md) +* [DELETE](docs/delete.md) +* [SQL Operators](docs/sql-operators.md) \ No newline at end of file diff --git a/docs/views.md b/docs/views.md new file mode 100644 index 00000000000..2477b43da0a --- /dev/null +++ b/docs/views.md @@ -0,0 +1,55 @@ +# Views + +A view is a virtual table generated from a SQL query. It allows users to simplify complex queries, hide sensitive data, and provide a customized view of the database without altering the underlying schema. + +## Advantages of Using Views + +| Benefits | Description | +|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Simplification | Views simplify complex queries by encapsulating them into a single, reusable object. They provide a convenient way to abstract and hide the complexity of underlying tables. | +| Security | Views can enhance security by restricting access to sensitive data. Users can be granted access to views containing only the necessary columns, without direct access to the tables. | +| Customization | Views enable users to create customized perspectives of the data, presenting only the relevant information needed for specific tasks or reports. | +| Performance | Views can improve query performance by pre-computing and caching results, reducing the need to repeatedly execute complex queries. | + +## Disadvantages of Using Views + +| Disadvantages | Description | +|-----------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Complexity | Views can introduce complexity to the database schema and query execution plan, making it harder to optimize and troubleshoot performance issues. | +| Overhead | Views may incur overhead in terms of storage and processing resources, particularly for materialized views or views involving joins and aggregation functions. | +| Maintenance | Views require maintenance to keep them synchronized with the underlying tables. Changes to the base tables may impact the results returned by the view. | +| Limited Use | Views have limitations in terms of updateability and support for certain SQL operations, such as ordering or grouping by columns not present in the underlying tables. | + +## Create view + +```{.bash data-prompt="mysql>"} +mysql> CREATE VIEW customer_orders AS + SELECT customers.name, orders.order_id, orders.total_amount + FROM customers + JOIN orders ON customers.customer_id = orders.customer_id; +``` + +```{.bash data-prompt="mysql>"} +mysql> CREATE VIEW recent_orders AS + SELECT * + FROM orders + WHERE order_date >= CURDATE() - INTERVAL 30 DAY; +``` + +## Drop view + +```{.bash data-prompt="mysql>"} +mysql> DROP VIEW IF EXISTS customer_orders; +``` + +```{.bash data-prompt="mysql>"} +mysql> DROP VIEW IF EXISTS recent_orders; +``` + + +## Database management + +* [Database](database.md) +* [Modify Tables](modify-tables.md) +* [Isolation Levels](isolation-levels.md) +* [Transaction Management](transaction-mgmt.md) \ No newline at end of file diff --git a/mkdocs-base.yml b/mkdocs-base.yml index 3c79ad361fb..444048a0165 100644 --- a/mkdocs-base.yml +++ b/mkdocs-base.yml @@ -223,7 +223,47 @@ nav: - post-installation.md - apparmor.md - selinux.md + - Develop: + - Fundamental SQL operations: + - sql-basics.md + - common-sql.md + - select.md + - insert.md + - update.md + - delete.md + + + - sql-operators.md + + - Advanced SQL features: + - data-types-basic.md + - functions.md + - sql-conventions.md + - sql-errors.md + - sql-syntax.md + + - stored-procedures.md + - stored-procedure-error-handling.md + - stored-procedure-variables.md + - triggers.md + - troubleshooting-sql.md + - Manage: + - Database management: + - database.md + - table.md + - modify-tables.md + - isolation-levels.md + - transaction-mgmt.md + - views.md + + + + + + + + - extended-show-grants.md - restrict-dynamic-log-locations.md - clone-plugin.md