Skip to content

Commit

Permalink
Merge pull request #320 from percona/ps-9224
Browse files Browse the repository at this point in the history
PS-9224 Add SQL basics
  • Loading branch information
patrickbirch authored May 28, 2024
2 parents 700d3fb + 898847c commit 7d3a6d2
Show file tree
Hide file tree
Showing 25 changed files with 1,416 additions and 0 deletions.
107 changes: 107 additions & 0 deletions docs/common-sql.md
Original file line number Diff line number Diff line change
@@ -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', '[email protected]');
```
* [**UPDATE**]: This command modifies existing records in a table.
```text
mysql> UPDATE customers SET email = '[email protected]' 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)
54 changes: 54 additions & 0 deletions docs/create-table.md
Original file line number Diff line number Diff line change
@@ -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)
89 changes: 89 additions & 0 deletions docs/data-types-basic.md
Original file line number Diff line number Diff line change
@@ -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)
62 changes: 62 additions & 0 deletions docs/database.md
Original file line number Diff line number Diff line change
@@ -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)
47 changes: 47 additions & 0 deletions docs/delete.md
Original file line number Diff line number Diff line change
@@ -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)
Loading

0 comments on commit 7d3a6d2

Please sign in to comment.