Lessons › SQL › Deep Dive: Text, Date & Number Functions
SQL lesson
LPAD() and RPAD() for padding text
LPAD and RPAD stretch a value to a required length by stuffing extra characters onto the left or right side until it hits the target.
Try this lesson free →Example
Padding text to a fixed width
SELECT LPAD(product_id, 10, '0') AS padded_id FROM products| padded_id |
|---|
| 00000P2001 |
| 0000000P25 |
| 00000P10042 |
Step by step
- Run the query without LPAD so you can see what the unfiltered values look like.
SELECT product_id FROM products; - LPAD pads a string with characters on the left until it reaches the target length.
SELECT LPAD(product_id, 10, '0') FROM products; - AS gives the LPAD result a friendly column name so the output reads cleanly.
SELECT LPAD(product_id, 10, '0') AS padded_id FROM products;
Practice
1. On the customers table, write a query that pads email on the left with '0' so every value is 10 characters wide, using LPAD.
SELECT LPAD(email, 10, '0') FROM customers2. On the products table, write a query that pads category on the right with '*' so every value is 10 characters wide, using RPAD.
SELECT RPAD(category, 10, '*') FROM products3. On the suppliers table, write a query that pads supplier_name on the left with '0' so every value is 10 characters wide, using LPAD.
SELECT LPAD(supplier_name, 10, '0') FROM suppliers4. On the employees table, write a query that pads role on the right with '*' so every value is 10 characters wide, using RPAD.
SELECT RPAD(role, 10, '*') FROM employees5. On the reviews table, write a query that pads product_id on the left with '0' so every value is 10 characters wide, using LPAD.
SELECT LPAD(product_id, 10, '0') FROM reviewsLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →