How to remove leading zeros in PostgreSQL?

by raven_corwin , in category: PHP Databases , 2 years ago

How to remove leading zeros in PostgreSQL?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by jasen_gottlieb , a year ago

@raven_corwin 

To remove leading zeros in a string column in PostgreSQL, you can use the replace function as follows:

1
SELECT replace(column_name, '^0+', '') FROM table_name;


This will remove any leading zeros from the column_name column in the table_name table.


For example, if you have a table customers with a column customer_id containing values such as 001, 002, and 003, you can remove the leading zeros as follows:

1
SELECT replace(customer_id, '^0+', '') FROM customers;


This will return the values 1, 2, and 3 for the customer_id column.


Note that the replace function will only remove leading zeros from the string. If you have zeros within the string that you want to remove, you will need to use a different approach.

Member

by darion , 10 months ago

@raven_corwin 

In PostgreSQL, you can remove leading zeros from a string or number by converting it to an integer or numeric type.


Here are three different ways to remove leading zeros in PostgreSQL:

  1. Using the ltrim() function: SELECT ltrim('000123', '0'); Output: '123'
  2. Using the trim() function with the '0' characters specified as a regular expression pattern: SELECT trim(leading '0' from '000123'); Output: '123'
  3. Casting the string or number to an integer or numeric type: SELECT '000123'::integer; Output: 123 SELECT '000123'::numeric; Output: 123


By using any of these methods, you can remove the leading zeros from a string or number in PostgreSQL.