How to align a column right-adjusted in MySQL?


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)

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements