How to align a column right-adjusted in MySQL?

MySQLMySQLi Database

You can use LPAD() from MySQL for this. Let us first create a table −

mysql> create table DemoTable
(
   FullName varchar(100)
);
Query OK, 0 rows affected (0.81 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable values('John Smith');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('David Miller');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('Sam Williams');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Carol Taylor');
Query OK, 1 row affected (0.47 sec)

Display records from the table using select command −

mysql> select *from DemoTable;

This will produce the following output −

+--------------+
| FullName     |
+--------------+
| John Smith   |
| David Miller |
| Sam Williams |
| Carol Taylor |
+--------------+
4 rows in set (0.00 sec)

Following is the query to align a column right-adjusted −

mysql> select lpad(FullName,70,' ') from DemoTable;

This will produce the following output −

+------------------------------------------------------------------------+
| lpad(FullName,70,' ')                                                  |
+------------------------------------------------------------------------+
| John Smith                                                             |
| David Miller                                                           |
| Sam Williams                                                           |
| Carol Taylor                                                           |
+------------------------------------------------------------------------+
4 rows in set (0.00 sec)
raja
Published on 30-Apr-2019 06:40:28
Advertisements