Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query bytea field in postgres via command line

Tags:

postgresql

I have a table with a bytea field, and it would be convenient if I could do queries via the command line (or pgAdmin's query executor). I've got the hex value as a string. Is there a built in function to convert hex to bytea?

I'd like to do something like:

SELECT * FROM table WHERE my_bytea_field=some_???_function('fa26e312');

where 'fa26e312' is the hex value of the bytea field I want.

Note: this is just to be helpful while I'm developing / debugging things, I can do it via code but I'd like to be able to do it by hand in a query.

like image 916
John Smith Avatar asked Jul 09 '11 22:07

John Smith


People also ask

What is Bytea datatype in PostgreSQL?

The bytea data type allows the storage of binary strings or what is typically thought of as “raw bytes”. Materialize supports both the typical formats for input and output: the hex format and the historical PostgreSQL escape format. The hex format is preferred.

Can we store bytes in PostgreSQL?

PostgreSQL provides two distinct ways to store binary data. Binary data can be stored in a table using the data type bytea or by using the Large Object feature which stores the binary data in a separate table in a special format and refers to that table by storing a value of type oid in your table.

What is true for binary data types in PostgreSQL?

In short, binary strings are appropriate for storing data that the programmer thinks of as “raw bytes”, whereas character strings are appropriate for storing text. The bytea type supports two formats for input and output: “hex” format and PostgreSQL's historical “escape” format.


2 Answers

Try using built-in decode(string text, type text) function (it returns bytea). You can run queries via CLI using psql in non-interactive mode, that is with -c switch (there are some formatting options if you like):

psql -c "SELECT * FROM table WHERE my_bytea_field=decode('fa26e312', 'hex');"

Example:

CREATE TABLE test(id serial, my_bytea_field bytea);
INSERT INTO test (my_bytea_field) VALUES
    (E'\\320\\170'::bytea),
    (E'\\100\\070'::bytea),
    (E'\\377\\377'::bytea);

psql -tc "SELECT * FROM test WHERE my_bytea_field=decode('ffff', 'hex');"
  3 | \377\377
like image 154
Grzegorz Szpetkowski Avatar answered Oct 19 '22 23:10

Grzegorz Szpetkowski


SELECT * FROM table WHERE my_bytea_field=E'\\xfa26e312';

Just as in the example in the Binary Data Types docs (note the E'\\x' prefix):

SELECT E'\\xDEADBEEF';
like image 32
Garen Avatar answered Oct 20 '22 00:10

Garen