Mariadb Tutorial: Learn Syntax, Commands With Examples
Mariadb Tutorial: Learn Syntax, Commands With Examples
Mariadb Tutorial: Learn Syntax, Commands With Examples
with Examples
ByRichard PetersonUpdatedJune 6, 2022
What is MariaDB?
MariaDB is a fork of the MySQL database management system. It is created by its
original developers. This DBMS tool offers data processing capabilities for both
small and enterprise tasks.
What is MariaDB?
MariaDB vs. MySQL
How to install MariaDB
Working with Command Prompt
Data Types
Create a Database and Tables
MariaDB Select Database
MariaDB – Create Table
CRUD and Clauses
Advanced Tasks
JOIN
MariaDB shows an improved speed when compared to MySQL. It MySQL exhibits a slower s
comes with numerous features for optimizing speed. Such features compared to MariaDB. It r
Speed Improvements
include derived views/tables, subquery, execution control, disk features for speed optimiz
access, and optimizer control. hash indexes.
With the Memory storage engine of MariaDB, an INSERT statement The memory storage engin
Faster cache/indexes
can be completed 24% than in the standard MySQL. slower compared to that M
Larger and Faster MariaDB comes with an advanced thread pool capable of running The thread pool provided
Connection Pool faster and supporting up to 200,000+ connections. support up to 200,000 con
New MariaDB comes with new features and extensions including the JSON, The new MariaDB feature
Features/Extensions WITH and KILL statements. in MySQL.
1. Enter the password and confirm it by retyping the same password. If you
want to permit access from remote machines, activate the necessary
checkbox.
2. Once done, click the Next button.
Step 7) Enter Name & Choose Port number
In the next window, type a name for the instance, choose the port number, and set
the necessary size. Click the Next button:
Step 8) Click Next
In the next window, simply click the Next button.
MySQL -u root -p
Step 4) Enter the password and hit the return key. You should be logged in, as
shown below:
Data Types
MariaDB supports the following data types:
char(size) The size denotes the number of characters to be stored. It stores a maximum of 255 characters. Fixed-le
varchar(size) The size denotes the number of characters to be stored. It stores a maximum of 255 characters. Variabl
text(size) The size denotes the number of characters to be stored. It stores a maximum of 255 characters. Fixed-le
binary(size) The size denotes the number of characters to be stored. It stores a maximum of 255 characters. Fixed-s
Numeric Data
Description
Types
A very small integer value equivalent to tinyint(1). Signed values range between -128 and 127. Unsign
bit
between 0 and 255.
A standard integer value. Signed values range between -2147483648 and 2147483647. Unsigned valu
int(m)
and 4294967295.
Date/Time Data
Description
Type
Date Displayed in the form ‘yyyy-mm-dd.’ Values range between ‘1000-01-01’ and ‘9999-12-31’.
Displayed in the form ‘yyyy-mm-dd hh:mm:ss’. Values range between ‘1000-01-01 00:00:00’ and ‘99
Datetime
23:59:59’.
Displayed in the form ‘yyyy-mm-dd hh:mm:ss’. Values range between ‘1970-01-01 00:00:01’ utc and
timestamp(m)
03:14:07’ utc.
Time Displayed in the form ‘hh:mm:ss’. Values range between ‘-838:59:59’ and ‘838:59:59’.
To create a new database, you should use the CREATE DATABASE command which
takes the following syntax:
Start the MariaDB command prompt and login as the root user by typing the
following command:
mysql -u root -p
Type the root password and hit the return key. You will be logged in.
SHOW DATABASES;
The above output shows that the Demo database is part of the list, hence the
database was created successfully.
To select a database, you should use the USE command. It takes the syntax given
below:
USE database_name;
You need to use the Demo database. You can select it by running the following
command:
USE Demo;
The above image shows that the MariaDB command prompt has changed from
none to the name of the database that has been selected.
You can now go ahead and create tables within the Demo database.
We will create two tables within the Demo database, Book, and Price tables. Each
table will have two columns.
Let’s begin by creating the Book table with two columns, id and name. Run the
following command:
The PRIMARY KEY constraint has been used to set the id column as the primary key
for the table. The AUTO_INCREMENT property will increment the values of the id
column by 1 automatically for each new record inserted into the table. All the
columns will not allow null values.
Showing Tables
Now that you have created the two tables, it will be good for you to conform
whether the tables were created successfully or not. You can show the list of tables
contained in a database by running the following command:
SHOW TABLES;
The above screenshot shows that the two tables were created successfully within
the Demo database.
DESC TableName;
For example, to see the structure of the table named Book, you can run the
following command;
DESC Book;
The table has two columns. To see the structure of the Price table, you can run the
following command:
DESC Price;
CRUD and Clauses
INSERT
To insert data into a MariaDB table, you should use the INSERT INTO statement.
This command takes the syntax given below:
You have inserted a single record into the table. Insert a record into the Price table:
The records were inserted successfully. Insert multiple records into the Price table
by running this example:
UPDATE
The UPDATE command helps us to change or modify the records that have already
been inserted into a table. You can combine it with the WHERE clause to specify the
record that is to be updated. Here is the syntax:
Let’s change the price of the book with an id of 1 from 200 to 250:
UPDATE price
SET price = 250
WHERE id = 1;
The command ran successfully. You can now query the table to see whether the
change took place:
The above screenshot shows that the change has been implemented. Consider the
table Book with the following records:
Let us change the name of the book named Book to MariaDB Book1. Notice that
the book has an id of 1. Here is the command for this:
UPDATE book
SET name = “MariaDB Book1”
WHERE id = 1;
The above screenshot shows that the change has been implemented successfully.
In the above examples, we have only changed one column at a time. However, it is
possible for us to change multiple columns at a go. Let us demonstrate this using
an example.
UPDATE price
SET id = 6,
price = 280
WHERE id = 5;
Now, query the table to check whether the change was made successfully:
Delete
We use the DELETE command when we need to delete either one or many records
from a table. Here is the syntax for the command:
We need to delete the last record from the table. It has an id of 6 and a price of 280.
Let us delete the record:
The command ran successfully. Let us query the table to confirm whether the
deletion was successful:
Where
The WHERE clause helps us to specify the exact location where we need to make a
change. It is used together with statements such as INSERT, SELECT, UPDATE, and
DELETE. Consider the Price table with the following data:
Suppose we need to see the records in which the price is less than 250. We can run
the following command:
SELECT *
FROM price
WHERE price < 250;
All the records in which the price is below 250 have been returned.
The WHERE clause can be combined with the AND statement. Suppose we need to
see all records in the Price table where the price is below 250 and id is above 3. We
can run the following command:
SELECT *
FROM price
WHERE id > 3
AND price < 250;
Only one record has been returned. The reason is that it has to meet all the
conditions that have been specified, that is, id above 3 and price below 250. If any
of these conditions is violated, then the record will not be returned.
The clause can also be combined with the OR command. Let us replace the AND in
our previous command with OR and see the kind of output that we receive:
SELECT *
FROM price
WHERE id > 3
OR price < 250;
We now get 2 records rather than 1. This is because, for a record of qualifying, it
only has to meet one of the specified conditions.
Like
This clause is used to specify the data pattern when accessing table data in which
an exact match is necessary. It can be combined with the INSERT, UPDATE, SELECT
and DELETE statements.
You should pass the pattern of data you are looking for to the clause, and it will
return either true or false. Here are the wildcard characters that can be used
together with the clause:
SELECT name
FROM book
WHERE name LIKE 'M%';
All records have been returned because their names begin with the letter M. To see
all names that end with 4, you can run the following command:
SELECT name
FROM book
WHERE name LIKE '%4';
Only one name has been returned because it’s the only one meeting the condition.
Other than the % wildcard, the LIKE clause can be used together with the _
wildcard. This is the underscore wildcard, and it will only look for a single
character.
Let’s work with the Price table with the following records:
Let us check for the record in which the price is like 1_0. We run the following
command:
SELECT *
FROM price
WHERE price LIKE '1_0';
It has returned the record in which the price is 190. We can also try another pattern:
SELECT *
FROM price
WHERE price LIKE '_2_';
It is possible for us to use the LIKE clause together with the NOT operator. This will
return all the records that don’t meet the specified pattern. For example:
Let us find all the records where the price does not start with 2:
SELECT *
FROM price
WHERE price NOT LIKE '2%';
Order By
This clause helps us to sort out our records in either ascending or descending
order. We use it with the SELECT statement, as shown below:
SELECT expression(s)
FROM tables
[WHERE condition(s)]
ORDER BY exp [ ASC | DESC ];
It is possible for us to use this clause without adding either the ASC or DESC part.
For example:
In the above command, we have ordered by the price. The records have been
ordered with the prices in ascending order. That means that when we don’t specify
the order, the sorting is done in ascending order by default.
Let us use the ORDER BY clause together with the ASC attribute:
The records have been ordered but with the prices in ascending order. This is
similar to when we use the ORDER BY clause without either ASC or DESC attributes.
DISTINCT
This clause helps us to do away with duplicates when selecting records from a
table. This means that it helps us get unique records. Its syntax is given below:
We have two records with a price of 250, creating a duplicate. We need to have only
unique records. We can filter these by use of the DISTINCT clause as shown below:
From
The FROM clause used for fetching data from a database table. It can also help
when joining tables. Here is the syntax for the command:
Advanced Tasks
Stored Procedure
A procedure is a MariaDB program that you can pass parameters to. A procedure
doesn’t return values. To create a procedure, we use the CREATE PROCEDURE
command.
DELIMITER $
CREATE PROCEDURE myProcedure()
BEGIN
SELECT name FROM book;
END;
;
The procedure has been created. We have simply enclosed the SELECT statement
within the BEGIN and END clauses of the procedure.
CALL myProcedure();
The procedure returns the name column of the book table when called.
DELIMITER $
CREATE PROCEDURE myProcedure2(book_id int)
BEGIN
SELECT name FROM book WHERE id = book_id;
END;
;
Above, we have created a procedure named myProcedure2(). This procedure takes
one integer parameter named book_id which is the id of the book whose name we
need to see. To see the name of the book with an id of 3, we can call the procedure
as follows:
CALL myProcedure2(3);
Function
Unlike procedures, we must pass parameters to functions and a function must
return a value. To create a function in MariaDB, we use the CREATE FUNCTION
statement. The statement takes the following syntax:
CREATE
[ DEFINER = { CURRENT-USER | username } ]
FUNCTION function-name [(parameter datatype [, parameter datatype]) ]
RETURNS datatype [LANGUAGE SQL
| DETERMINISTIC
| NOT DETERMINISTIC
| {CONTAINS SQL
| NO SQL
| READS SQL DATA
| MODIFIES SQL DATA}
| SQL SECURITY {DEFINER | INVOKER}
| COMMENT 'comment'
BEGIN
declaration-section
executable-section
END;
The above parameters are described below:
Parameter Description
This parameter is optional. If you don’t specify it, the definer will become the user who created the fun
DEFINER clause
need to specify a different definer, include the DEFINER clause in which the user_name will be the defi
function_name The name that is to be assigned to this function in the MariaDB.
The parameter(s) passed to the function. During the creation of the function, all parameters are treate
parameter
parameters (rather than OUT/INOUT parameters).
DETERMINISTIC The function will return one result only when given a number of parameters.
NOT
It is possible for the function to return a different result when given a number of parameters.
DETERMINISTIC
CONTAINS SQL Informs MariaDB that this function contains SQL. The database will not verify whether this is true.
NO SQL This clause is not used, and it has no impact on your function.
READS SQL DATA Tells MariaDB that this function will use SELECT statements to read data, but it won’t modify the data.
MODIFIES SQL
Tells MariaDB that this function will use INSERT, DELETE, UPDATE, and other DDL statements to modify
DATA
declaration-
This is where local variables should be declared.
section
executable-
The function code should be added here.
section
DELIMITER //
BEGIN
select sumFunc(1000);
The command will return the following:
Once you are done with a function, it will be good for you to delete it. This is easy
as you only have to call the DROP FUNCTION statement that takes the following
syntax:
JOIN
When you need to retrieve data from more than one tables at a go, use MariaDB
JOINS. This means that a JOIN works on two or more tables. The following three
types of JOINS are supported in MariaDB:
INNER/SIMPLE JOIN
LEFT OUTER JOIN/LEFT JOIN
RIGHT OUTER JOIN/RIGHT JOIN
INNER JOIN
The inner join returns all rows from the tables in which the join condition is true. Its
syntax is as follows:
SELECT columns
FROM table-1
INNER JOIN table-2
ON table-1.column = table-2.column;
For example:
The goal is to join the name column from the Book table and the price column from
Price table into a single table. This is possible with an inner join, as demonstrated
below:
SELECT columns
FROM table-1
LEFT [OUTER] JOIN table-2
ON table-1.column = table-2.column;
The OUTER keyword has been placed within square brackets because it is optional.
For example:
SELECT columns
FROM table-1
RIGHT [OUTER] JOIN table-2
ON table-1.column = table-2.column;
The OUTER keyword has been placed within square brackets because it is optional.
For example:
The reason is that all rows in the right-hand table were matched to those in the
other table. If some of the rows did not match, we would have NULLs in the first
column.