MariaDB Aliases


Objectives

  • Understanding of MariaDB Aliases

  • MariaDB Columns Aliases

  • MariaDB Table Aliases


Create database and table and insert data if it is not created already

--- Create database if not exist
CREATE DATABASE IF NOT EXISTS mariadb_tutorial;

--- Select the database for further operation
USE mariadb_tutorial;

--- Create table if not exist
CREATE TABLE IF NOT EXISTS person (
    id int(12) NOT NULL AUTO_INCREMENT,
    first_name varchar(150) NOT NULL,
    last_name varchar(150),
    email varchar(100),
    age int,
    income double,
    PRIMARY KEY (id)
)

--- Remove old Data
TRUNCATE person;

--- Insert data into table if not exist
INSERT INTO person (first_name, last_name, email, age, income)
VALUES
	('Faiyaz', 'Mia', 'faiyaz@pf.local', 1, 5000),
	('John', 'Doe', 'john@pf.local', 19, 100),
	('Tahsin', NULL, 'tahsin@pf.local', 10, 150),
	('Jane', 'Doe', 'jane@gmail.com', 26, 300),
	('Rakib', 'Mia', 'rakib@bf.local', 24, 200),
	('Sagor', 'Sowrov', 'email10@bf.local', 20, 250),
	('Touhid', NULL, 'hmtmcse.com@gmail.com', 30, 500);


Understanding of MariaDB Aliases

Aliases are used to give a table, or a column in a table, a temporary name. An alias is created with the AS keyword.

  • Columns Aliases : In the person table income is the one of column, but you want to display that column as Salary, for that you can use Columns Alias

  • Table Aliases : Sometimes you need to write big query, this type of moment every time write the table full name make the query length bigger. That’s why you may write person as p by the alias.


MariaDB Columns Aliases

Problem: Produce a result sheet where need Firstname, Lastname and Salary

Syntax

SELECT column_name AS alias_name FROM table_name;

Example

SELECT first_name AS Firstname, last_name AS Lastname, income AS Salary FROM person;

Output

+-----------+----------+--------+
| Firstname | Lastname | Salary |
+-----------+----------+--------+
| Faiyaz    | Mia      |   5000 |
| John      | Doe      |    100 |
| Tahsin    | NULL     |    150 |
| Jane      | Doe      |    300 |
| Rakib     | Mia      |    200 |
| Sagor     | Sowrov   |    250 |
| Touhid    | NULL     |    500 |
+-----------+----------+--------+
7 rows in set (0.001 sec)


MariaDB Table Aliases

Syntax

SELECT * FROM table_name AS alias_name;

Example

SELECT p.first_name, p.last_name FROM person AS p;

Output

+------------+-----------+
| first_name | last_name |
+------------+-----------+
| Faiyaz     | Mia       |
| John       | Doe       |
| Tahsin     | NULL      |
| Jane       | Doe       |
| Rakib      | Mia       |
| Sagor      | Sowrov    |
| Touhid     | NULL      |
+------------+-----------+
7 rows in set (0.283 sec)

Must : If you use table alias then you must have to specify alias name during the column selection.


MariaDB Aliases Video tutorial