MySQL Open Source Database Guide
MySQL Open Source Database Guide
Introduction – MySQL
What is MySQL?
1
Page
Who Uses MySQL?
Applications of MySQL
MySQL has used in various applications across a wide range of industries and
domains, because of to its versatility, reliability, and performance. Here are some
2
Page
common applications :
E-commerce: MySQL is extensively used in e-commerce platforms for
managing product catalogs, customer data, orders, and transactions.
Content Management Systems (CMS): Many popular CMS platforms rely on
MySQL as their backend database to store website content, user profiles,
comments, and configuration settings.
Financial Services: MySQL is employed in financial applications, including
banking systems, payment processing platforms, and accounting software,
to manage transactional data, customer accounts, and financial records.
Healthcare: MySQL is used in healthcare applications for storing and
managing patient records, medical histories, treatment plans, and diagnostic
information.
Setting up an account
Now, Let' 's break down MySQL software downloading steps for a better
understanding and see install MySQL on Windows 10 step by step.
The installation process of MySQL on Linux involves using the terminal and
running a series of commands. This articles covers the installation on Ubuntu and
other Debian-based distributions, but the steps are similar for other Linux
distributions as well.
Step 1: Update Your Package List
Before installing any software, it’s always a good idea to update your package list to
ensure you’re getting the latest version available from the repository.
Once you run the command, it will prompt you for your password. Enter it and
press Enter then Press "y" to continue.
mysql --version
Then press "y" to set the password. Next press "0" for the low-level password or
choose as you want to set the password.
Create a password. Then Re-enter the password, then to continue press "y".
Now the whole setup is done. Hence, MySQL installaion is successfully done!
Step 5: Test the MySQL Server
Once the security configuration is complete, test whether MySQL is running
properly:
CREATE TABLE
Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
6
);
Page
PersonID LastName FirstName Address City
Example
The TRUNCATE TABLE statement is used to delete the data inside a table, but not
the table itself.
Syntax
TRUNCATE TABLE table_name;
ALTER TABLE - DROP COLUMN
To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):
Example
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
7
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to
the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the primary
key is called the referenced or parent table.
Persons Table
PersonID LastName FirstName Age
1 Hansen Ola 30
8
2 Svendson Tove 23
Page
3 Pettersen Kari 20
Orders Table
OrderID OrderNumber PersonID
1 77895 3
2 44678 3
3 22456 2
Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
DESCRIBE Statement
name VARCHAR(50),
email VARCHAR(100),
age INT
);
DESC users;
Country
Germany
Mexico
Mexico
UK
Sweden
5
11
de
Page
1 Alfreds Maria Obere Str. Berlin 1220 Germa
Futterkiste Anders 57 9 ny
SELECT CustomerName,ContactName,Address
FROM Customers
WHERE Address IS NULL;
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
FROM CUSTOMERS;
2 Chang 1 50 24 - 12 oz 19
bottles
SELECT AVG(Price)
FROM Products;
162.5
SELECT SUM()
FROM Products;
650
2 Chang 1 50 24 - 12 oz 19
bottles
bottles
Page
SELECT * FROM Products
WHERE Order BETWEEN 100 AND 200
2 Chang 1 50 24 - 12 oz 19
bottles
FROM Customers;
extraction.
Page
Function Description
pattern in a string.
1. CONCAT_WS()
SELECT CONCAT_WS(', ', 'apple', 'banana', 'orange') AS Concatenated_String;
Output:
+----------------------+
| Concatenated_String |
+----------------------+
| apple, banana, orange |
+----------------------+
2. CONCAT()
SELECT CONCAT('Hello', ' ', 'World') AS Concatenated_String;
Output:
+-------------------+
| Concatenated_String |
+-------------------+
| Hello World |
+-------------------+
3. CHARACTER_LENGTH()
SELECT CHARACTER_LENGTH('Hello World') AS String_Length;
Output:
+--------------+
| String_Length |
+--------------+
21
| 11 |
Page
+--------------+
4. ELT()
SELECT ELT(3, 'apple', 'banana', 'orange', 'grape') AS Selected_String;
Output:
+----------------+
| Selected_String |
+----------------+
| orange |
+----------------+
5. EXPORT_SET()
SELECT EXPORT_SET(5, 2, '0', ',', '1') AS Binary_Set;
Output:
+------------+
| Binary_Set |
+------------+
| 1,0,1 |
+------------+
6. FIELD()
SELECT FIELD('banana', 'apple', 'banana', 'orange') AS Position;
Output:
+----------+
| Position |
+----------+
|2 |
+----------+
7. FIND_IN_SET()
SELECT FIND_IN_SET('banana', 'apple,banana,orange') AS Position;
Output:
+----------+
| Position |
+----------+
|2 |
+----------+
8. FORMAT()
SELECT FORMAT(1234567.89, 2) AS Formatted_Number;
Output:
+-------------------+
| Formatted_Number |
+-------------------+
| 1,234,567.89 |
22
+-------------------+
Page
9. POSITION()
SELECT POSITION('bar' IN 'foobarbar') AS Position;
Output:
+----------+
| Position |
+----------+
| 4|
+----------+
10. QUOTE()
SELECT QUOTE('It\'s a beautiful day!') AS Quoted_String;
Output:
+--------------------------+
| Quoted_String |
+--------------------------+
| 'It\'s a beautiful day!' |
+--------------------------+
11. REPLACE()
SELECT REPLACE('Hello World', 'World', 'Universe') AS Modified_String;
Output:
+------------------+
| Modified_String |
+------------------+
| Hello Universe |
+------------------+
12. REPEAT()
SELECT REPEAT('Hello ', 3) AS Repeated_String;
Output:
+------------------+
| Repeated_String |
+------------------+
| Hello Hello Hello |
13. RPAD()
SELECT RPAD('apple', 10, '*') AS Padded_String;
Output:
+---------------+
| Padded_String |
+---------------+
| apple***** |
+---------------+
23
14. RTRIM()
Page
15.MAKE_SET()
SELECT MAKE_SET(1, 'a', 'b', 'c') AS Set_Values;
Output:
+------------+
| Set_Values |
+------------+
|a |
+------------+
Name Description
Add time values (intervals) to a
ADDDATE() date value
ADDTIME() Add time
Convert from one time zone to
CONVERT_TZ() another
CURDATE() Return the current date
CURRENT_DATE(), CURRENT_DATE Synonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIME Synonyms for CURTIME()
CURRENT_TIMESTAMP(), CURRENT_TIMEST
AMP Synonyms for NOW()
CURTIME() Return the current time
Extract the date part of a date or
DATE() datetime expression
Add time values (intervals) to a
DATE_ADD() date value
DATE_FORMAT() Format date as specified
Subtract a time value (interval)
DATE_SUB() from a date
24
-> 0, 0
-> '2008-02-02'
-> '03:00:01.999997'
-> '2008-06-13'
-> 20080613
-> '2018-05-02'
-> '2017-05-01'
-> 2019
-> 201907
25
The ORDER BY clause in SQL is used to sort the results of a query, either in
ascending or descending order. It's placed after the WHERE clause (if present) and
allows you to specify which column(s) to sort by and the direction (ascending or
descending) for each.
Here's a breakdown:
1. Basic Syntax:
Code
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name [ASC | DESC];
ID Name ID ID
1 Chais 1 1 10 boxes x 18
20 bags
2 Chang 1 1 24 - 12 oz 19
bottles
Mix
SELECT * FROM Products
ORDER BY Price;
1 Chais 1 1 10 boxes x 18
20 bags
2 Chang 1 1 24 - 12 oz 19
bottles
4 Chef Anton's 2 2 48 - 6 oz 22
Cajun jars
Seasoning
2 Chang 1 1 24 - 12 oz 19
bottles
1 Chais 1 1 10 boxes x 18
20 bags
ORDER BY ProductName;
3 Aniseed 1 2 12 - 550 ml 10
Syrup bottles
1 Chais 1 1 10 boxes x 18
20 bags
2 Chang 1 1 24 - 12 oz 19
bottles
4 Chef Anton's 2 2 48 - 6 oz 22
Cajun jars
Seasoning
Gumbo Mix
Page
SELECT * FROM Customers
Generating Summary
Let's start by examining an example payments table. Our goal is to roll up old months
and put them into a summary table. To begin, we need to filter down to just older
months:
SELECT
amount,
YEAR(payment_date),
MONTH(payment_date)
FROM
payments
WHERE
Once we have our filtered data, we need to group it by year and month so we can roll
it up into the summary table:
SELECT
sum(amount) as amount,
29
YEAR(payment_date) as `year`,
Page
MONTH(payment_date) as `month`
FROM
payments
WHERE
GROUP BY
`year`, `month`
SELECT
COUNT(*) AS total_rows,
AVG(price) AS avg_price,
SUM(quantity) AS total_quantity,
MAX(price) AS max_price,
MIN(price) AS min_price
FROM Products
SUM()
The SUM() function returns the total sum of a numeric column.
Example:
SELECT SUM(salary) AS total_sales FROM employees;
Output:
+-------------+
| total_sales |
+-------------+
| 300000.00 |
MIN()
The MIN() function returns the minimum value in a set of values.
Example:
31
SELECT
category,
COUNT(*) AS total_products,
AVG(price) AS avg_price
FROM products
GROUP BY category;
Working with metadata in MySQL involves accessing information about the structure
and characteristics of your databases, tables, columns, and other database
objects. MySQL provides several mechanisms to retrieve this metadata:
1. INFORMATION_SCHEMA Database:
The INFORMATION_SCHEMA is a virtual database within each MySQL instance
that acts as a central repository for metadata. It contains several read-only tables
(views) that provide detailed information about:
Databases: SCHEMATA table.
Tables: TABLES table (including table names, engine, row format, etc.).
Columns: COLUMNS table (including column names, data types, nullability,
character sets, etc.).
Indexes: STATISTICS table.
Constraints: TABLE_CONSTRAINTS and KEY_COLUMN_USAGE tables (for
primary keys, foreign keys, unique constraints).
Stored Procedures and Functions: ROUTINES table.
32
MySQL does not have a built-in sequence feature but provides an alternative in
the form of the AUTO_INCREMENT column, which serves a similar purpose.
sequence begins with an initial value of 1 and increments by 1 for each new
Page
Example
In the following example, we are creating a table named "CUSTOMERS" and,
in addition, defining the AUTO_INCREMENT attribute for the "ID" column of
the table –
CREATE TABLE CUSTOMERS (
ID INT AUTO_INCREMENT,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Output
We can see in the table displayed below that the values in the "ID" column are
automatically incremented −
34
Page
ID NAME AGE ADDRESS SALARY
35
Page