LPAD()

Description

This function LPAD(str,len,padstr) returns the string str, left-padded with the string padstr to a length of len characters. If str is longer than len, the return value is shortened to len characters.

Syntax

  1. > LPAD(str,len,padstr)

Arguments

ArgumentsDescription
strRequired. The string to be padded. CHAR and VARCHAR both are supported.
lenRequired.
padstrRequired. The string used to pad on the left. CHAR and VARCHAR both are supported.

Examples

  1. > drop table if exists t1;
  2. > CREATE TABLE t1(Student_id INT,Student_name VARCHAR(100),Student_Class CHAR(20));
  3. > INSERT INTO t1
  4. VALUES
  5. (1,'Ananya Majumdar', 'IX'),
  6. (2,'Anushka Samanta', 'X'),
  7. (3,'Aniket Sharma', 'XI'),
  8. (4,'Anik Das', 'X'),
  9. (5,'Riya Jain', 'IX'),
  10. (6,'Tapan Samanta', 'X');
  11. > SELECT Student_id, Student_name,LPAD(Student_Class, 10, ' _') AS LeftPaddedString FROM t1;
  12. +------------+-----------------+------------------+
  13. | Student_id | Student_name | LeftPaddedString |
  14. +------------+-----------------+------------------+
  15. | 1 | Ananya Majumdar | _ _ _ _IX |
  16. | 2 | Anushka Samanta | _ _ _ _ X |
  17. | 3 | Aniket Sharma | _ _ _ _XI |
  18. | 4 | Anik Das | _ _ _ _ X |
  19. | 5 | Riya Jain | _ _ _ _IX |
  20. | 6 | Tapan Samanta | _ _ _ _ X |
  21. +------------+-----------------+------------------+
  22. > SELECT Student_id, lpad(Student_name,4,'new') AS LeftPaddedString FROM t1;
  23. +------------+------------------+
  24. | Student_id | LeftPaddedString |
  25. +------------+------------------+
  26. | 1 | Anan |
  27. | 2 | Anus |
  28. | 3 | Anik |
  29. | 4 | Anik |
  30. | 5 | Riya |
  31. | 6 | Tapa |
  32. +------------+------------------+
  33. > SELECT Student_id, lpad(Student_name,-4,'new') AS LeftPaddedString FROM t1;
  34. +------------+------------------+
  35. | Student_id | LeftPaddedString |
  36. +------------+------------------+
  37. | 1 | NULL |
  38. | 2 | NULL |
  39. | 3 | NULL |
  40. | 4 | NULL |
  41. | 5 | NULL |
  42. | 6 | NULL |
  43. +------------+------------------+
  44. > SELECT Student_id, lpad(Student_name,0,'new') AS LeftPaddedString FROM t1;
  45. +------------+------------------+
  46. | Student_id | LeftPaddedString |
  47. +------------+------------------+
  48. | 1 | |
  49. | 2 | |
  50. | 3 | |
  51. | 4 | |
  52. | 5 | |
  53. | 6 | |
  54. +------------+------------------+