Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove padded NULL bytes using SELECT in MySQL

Tags:

string

mysql

If data is inserted this way,

insert into `t` (`date`, `data`) values ( now(), lpad('Hello', 4096, CHAR(0x00)));

How do you retrive it removing NULL characters from data column. I am infact looking for something that does the reverse of what LPAD does.

The table definition is,

create table `t` (
    `id` int auto_increment,
    `date` datetime,
    `data` blob,
    primary key (`id`)
);

Generalized question is, How can I remove an specific character from either beginning or ending of a string?

like image 446
Shiplu Mokaddim Avatar asked Jan 20 '12 07:01

Shiplu Mokaddim


People also ask

How remove special characters from a string in MySQL select query?

Learn MySQL from scratch for Data Science and Analytics You can remove special characters from a database field using REPLACE() function.

How do I select NULL rows in MySQL?

To look for NULL values, you must use the IS NULL test. The following statements show how to find the NULL phone number and the empty phone number: mysql> SELECT * FROM my_table WHERE phone IS NULL; mysql> SELECT * FROM my_table WHERE phone = ''; See Section 3.3.

How do I Outfile in MySQL?

You can also use SELECT ... INTO OUTFILE with a VALUES statement to write values directly into a file. An example is shown here: SELECT * FROM (VALUES ROW(1,2,3),ROW(4,5,6),ROW(7,8,9)) AS t INTO OUTFILE '/tmp/select-values.

How do you lowercase in MySQL?

The LOWER() function converts a string to lower-case. Note: The LCASE() function is equal to the LOWER() function.


2 Answers

Use trim(), which comes in 3 flavours:

select trim(leading CHAR(0x00) from data)

or

select trim(trailing CHAR(0x00) from data)

or

select trim(both CHAR(0x00) from data)
like image 196
Bohemian Avatar answered Sep 29 '22 07:09

Bohemian


You'd probably want to use TRIM, as in;

select id, date, trim(trailing char(0) from data) as data from t;
like image 23
Joachim Isaksson Avatar answered Sep 29 '22 07:09

Joachim Isaksson