How to fetch TEXT column value from postgresql - postgresql

I have a the following simple table in postgreSQL:
CREATE TABLE data ( id bigint NOT NULL, text_column text, );
The values of the text_column , as I see them in the phpPgAdmin web site, are numbers (long).
As I read, postgreSQL keeps a pointer to the actual data.
How can I fetch the actual string value of the text_column?
Doing:
select text_column from data
returns numbers...
Thanks

Following helped us:
select convert_from(loread(lo_open(value::int, x'40000'::int), x'40000'::int), 'UTF8') from t_field;
where value is field, which contains TEXT, and t_field is obviously name of table.

From psql run \lo_export ID FILE where ID is the number stored in the text column in your table and FILE is the path and filename for the results. The number is a reference to the large object table. You can view its contents by running \lo_list.

Provided it's text_column is text, which means it's an oid, this should work too :
select convert_from(lo_get(text_column::oid), 'UTF8') from data;

Works fine , May be the field values are in numbers:
> \d+ type
Column | Type
name | text
test_id | integer
select name from type;
name
AAA

Related

Do you need surrounding parantheses in Postgres SELECT statement?

I noticed that there is different output for this
SELECT id,name,description FROM table_name;
as opposed to this
SELECT (id,name,description) FROM table_name;
Is there any big difference between the two?
What is the purpose of this?
create table table_name(id int, name text, description text);
insert into table_name
values (1, 'John', 'big one');
select (id, name, description), id, name, description
from table_name;
row | id | name | description
--------------------+----+------+-------------
(1,John,"big one") | 1 | John | big one
(1 row)
The difference is important. Columns enclosed in parenthesis form a row constructor known also as a composite value, returned in a single column. Usually, separate columns are preferred as a query result. Row constructors are necessary when a row as a whole is needed (e.g. in the VALUES of the above INSERT command). They are also used as values of composite types.
The following query actually is selecting a ROW type value:
SELECT (id, name, description) FROM table_name;
This syntax by itself would not be very useful, and more typically you would use this if you were doing an INSERT INTO ... SELECT into a table which had a row type in its definition. Here is an example of how you might use this.
CREATE TYPE your_type AS (
id INTEGER,
name VARCHAR,
description VARCHAR
);
CREATE TABLE your_table (
id INTEGER,
t your_type
);
INSERT INTO your_table (id, t)
SELECT 1, (id, name, description)
FROM table_name;
From the Postgres documentation on composite types:
Whenever you create a table, a composite type is also automatically created, with the same name as the table, to represent the table's row type.
So you have already been working with row types, whether or not you knew it.

Why doesn't postgresql complain when I try to order by the tablename if there is no column with that name?

If I have a table:
CREATE TABLE
abc
(
xyz INTEGER,
abc INTEGER
);
and I do:
select * from abc order by abc;
it works and sorts by the column named abc.
However, if I don't have a column named 'abc':
CREATE TABLE
abc
(
xyz INTEGER,
abcxyz INTEGER
);
but I run the same query:
select * from abc order by abc;
there is no error message returned from postgres.
I'm just wondering why postgres doesn't return an error message because clearly, 'abc' is not a valid column so I can't possibly order by that column.
I'm using PostgreSQL 9.6.7
Postgresql creates a default TYPE with the structure when we create a table. So when we use it in the query, it is returned as a TYPE, To verify this,
Insert a row into the table and run this
select pg_typeof(abc) from abc;
It gives the result.
pg_typeof
abc

access postgres field given field name as text string

I have a table in postgres:
create table fubar (
name1 text,
name2 text, ...,
key integer);
I want to write a function which returns field values from fubar given the column names:
function getFubarValues(col_name text, key integer) returns text ...
where getFubarValues returns the value of the specified column in the row identified by key. Seems like this should be easy.
I'm at a loss. Can someone help? Thanks.
Klin's answer is a good (i.e. safe) approach to the question as posed, but it can be simplified:
PostgreSQL's -> operator allows expressions. For example:
CREATE TABLE test (
id SERIAL,
js JSON NOT NULL,
k TEXT NOT NULL
);
INSERT INTO test (js,k) VALUES ('{"abc":"def","ghi":"jkl"}','abc');
SELECT js->k AS value FROM test;
Produces
value
-------
"def"
So we can combine that with row_to_json:
CREATE TABLE test (
id SERIAL,
a TEXT,
b TEXT,
k TEXT NOT NULL
);
INSERT INTO test (a,b,k) VALUES
('foo','bar','a'),
('zip','zag','b');
SELECT row_to_json(test)->k AS value FROM test;
Produces:
value
-------
"foo"
"zag"
Here I'm getting the key from the table itself but of course you could get it from any source / expression. It's just a value. Also note that the result returned is a JSON value type (it doesn't know if it's text, numeric, or boolean). If you want it to be text, just cast it: (row_to_json(test)->k)::TEXT
Now that the question itself is answered, here's why you shouldn't do this, and what you should do instead!
Never trust any data. Even if it already lives inside your database, you shouldn't trust it. The method I've posted here is safe against SQL injection attacks, but an attacker could still set k to 'id' and see a column which was not intended to be visible to them.
A much better approach is to structure your data with this type of query in mind. Postgres has some excellent datatypes for this; HSTORE and JSON/JSONB. Merge your dynamic columns into a single column with one of those types (I'd suggest HSTORE for its simplicity and generally being more complete).
This has several advantages: your schema is well-defined and does not need to change if you add more dynamic columns, you do not need to perform expensive re-casting (i.e. row_to_json), and you are able to take advantage of indexes on your columns (thanks to PostgreSQL's functional indexes).
The equivalent to the code I wrote above would be:
CREATE EXTENSION HSTORE; -- necessary if you're not already using HSTORE
CREATE TABLE test (
id SERIAL,
cols HSTORE NOT NULL,
k TEXT NOT NULL
);
INSERT INTO test (cols,k) VALUES
('a=>"foo",b=>"bar"','a'),
('a=>"zip",b=>"zag"','b');
SELECT cols->k AS value FROM test;
Or, for automatic escaping of your values when inserting, you can use one of:
INSERT INTO test (cols,k) VALUES
(hstore( 'a', 'foo' ) || hstore( 'b', 'bar' ), 'a'),
(hstore( ARRAY['a','b'], ARRAY['zip','zag'] ), 'b');
See http://www.postgresql.org/docs/9.1/static/hstore.html for more details.
You can use dynamic SQL to select a column by name:
create or replace function get_fubar_values (col_name text, row_key integer)
returns setof text language plpgsql as $$begin
return query execute 'select ' || quote_ident(col_name) ||
' from fubar where key = $1' using row_key;
end$$;

Cassandra CQL ALTER Table with timeuuid column

I tried ALTER TABLE with a valid timeuuid column name -
cqlsh:dbase> ALTER TABLE jdata ADD 4f8eca60-1498-11e4-b6e6-ed7706c00c12 timeuuid;
Bad Request: line 1:24 no viable alternative at input '4f8eca60-1498-11e4-b6e6-ed7706c00c12'
So, I next tried with quotes and it worked -
cqlsh:dbase> ALTER TABLE jdata ADD "4f8eca60-1498-11e4-b6e6-ed7706c00c12" timeuuid;
cqlsh:dbase>
But the table description now looks ugly with column name in quotes -
cqlsh:dbase> describe columnfamily jdata;
CREATE TABLE jdata (
abc text,
"4f8eca60-1498-11e4-b6e6-ed7706c00c12" timeuuid,
xyz text,
PRIMARY KEY ((abc), xyz)
) WITH
bloom_filter_fp_chance=0.010000 AND
blah blah;
So I need help with a ALTER command to create timeuuid column using CQL without quotes.
The NAME of the column is a String by definition.
So you can't put anything different from a String as column name.
create table invalidnames (2 text primary key, 5 int);
**Bad Request**: line 1:47 mismatched input '5' expecting ')'
while with strings works
create table validnames (two text primary key, five int);
The name of the column and the type of the column are not related in any way
HTH,
Carlo

PostgreSQL Text column to integer column

I have to convert one text column to integer column.
Showed code work when I have text (all numbers) in fields but now I find some empty strings '' where query stops.
ALTER TABLE mytable
ALTER COLUMN mycolumn TYPE integer USING (TRIM(mycolumn)::integer);
Can here be done so that empty strings be converted to integer 0 so this query will pass?
How to do this?
You can update your values before altering table:
UPDATE mytable SET mycolumn = '0' WHERE mycolumn = '';