MySQL LPAD is one of the String Function, which is used to add (or pad) required string to the left side of the original string. For example, to pad dollar symbol to left side of a Sales column etc. In this article we will show you, How to use this string LPAD in MySQL with example.
MySQL LPAD Syntax
The basic syntax of the string LPAD Function in MySQL is as shown below:
SELECT LPAD (Original_Str, length, Pad_String) FROM [Source]
- Original_Str: This is the actual string that is available in a column.
- length: This is the length of a final string (after padding). If the final string is greater than this length value then extra characters will be trimmed. Remember, You can use Length function to calculate the string length.
- Pad_String: String that you want to add to left side of the Original_Str
In order to demonstrate this LPAD string function, We are going to use the customer details table data that we shown below
MySQL LPAD Example 1
The LPAD Function in MySQL is used to pad the string expression to the left side of the original string. The following query will show multiple ways to use this function.
SELECT LPAD('World', 11, 'Hello '); -- It will trim the final string to length 8 SELECT LPAD('World', 8, 'Hello'); -- Let me use NULL value as input SELECT LPAD('World', 8, NULL); SELECT LPAD(NULL, 8, 'World');
MySQL LPAD Function Example 2
In this example, we are going to implement the string LPAD function on different columns in a table. Following statement will add Comp string to Education column, and attach dollar symbol to data present in yearly Income column.
-- MySQL String LPAD Example USE company; SELECT First_Name, Last_Name, Education, LPAD(Education, 13, 'Comp ') AS Dollar_Income, Profession, Yearly_Income, LPAD(Yearly_Income, 6, '$') AS Dollar_Income, Sales FROM customerdetails;
Thank You for Visiting Our Blog