7

I am trying to do something like this:

select char_length(select text_field from table where key = 1)

This won't work, and I presume, because the return type of a query is a table, not a string or text variable.

Is there a way to specify row,col of the result from a select statement?

edit: I overlooked to mention, that char_length is a function.

1
  • Why do you do it that complicated? Why not simply pass text_field to the function? Is there a reason why you do it that way? Commented Jun 22, 2012 at 21:34

4 Answers 4

7

When passing the result of a query to a function, simply wrap the query in brackets:

select char_length((select text_field from table where key = 1));

The outer set of brackets is for the function, the inner set converts a query to a result.

This syntax is not specific to postgres - it applies to all SQL servers.

This link shows the above code executing correctly (thanks to @Fahim Parkar for this)


Although, you could re-factor your query to not require this syntax, nevertheless this is how you "pass the result of a query to a function".

Sign up to request clarification or add additional context in comments.

1 Comment

@FahimParkar Thanks for the test case - I'll add it to the question
2
select char_length(text_field) from "table" where key = 1

2 Comments

will this query work?? table is a reserved keyword. EVEN this syntax is INVALID :D :)
@FahimParkar: good point I actually only did copy and paste :)
0

Assuming key is a primary key or unique key the first example below will work. It works only if the sub-query returns only 1 row. The second example will work for 1 or more rows.

select char_length((select text_field from table where key = 1));
select char_length(text_field) from table where key = 1;

Comments

0

It should be

select char_length(text_field) from "table" where key = 1

Also I believe, your table name is not table.

2 Comments

char_length is a function. I am trying to find the length of the text_field. For sanity's sake, I did try your fix, and it did not work.
The syntax is invalid for Postgres because it uses the standard double quotes not those non-standard dreaded backticks. It should be "table" instead

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.