7

I'm doing a select in Go using the database/sql package and the pq Postgres driver:

rows, err := db.Query("SELECT (name, age) FROM people WHERE id = 1")

I tried retrieving the values in the normal way:

rows.Next()
name := ""
age := 0
err = rows.Scan(&name, &age)

but I got the error:

sql: expected 1 destination arguments in Scan, not 2

The documentation for sql.(*Rows).Scan says that you can pass a byte slice pointer and it will be filled with the raw results. So I did this:

b := make([]byte, 1024*1024)
rows.Scan(&b)
fmt.Println(string(b))

which succeeded, printing:

(John,18)

So I looked at the source code for sql.(*Rows).Scan, and it turns out that the error is returned if the number of arguments doesn't match the number of results returned by the database driver (which makes sense). So, for some reason, the pq driver seems to be returning the result set as a single value. Why would this be?

6
  • 7
    Remove the parentheses around the columns in the select list. SELECT (name, age) returns a single record (an anonymous composite type), but SELECT name, age will return two columns Commented Jan 6, 2014 at 22:45
  • Is this a Postgres-only feature? Commented Jan 6, 2014 at 23:41
  • @joshlf13 You'd probably need to look into the standard to find out, and it's "fun" reading. I think the standard supports it for things like UPDATE ... SET (a, b) = (x, y), and PostgreSQL has just generalized that by treating (a,b) as shorthand for ROW(a,b). Commented Jan 7, 2014 at 0:15
  • @a_horse_with_no_name : but what about if the query is calling a function which returns a query, such as RETURN QUERY SELECT arg1, arg2 removing parentheses doesn't work for functions Commented Sep 30, 2019 at 13:35
  • @Joe: no idea what you mean with that. If you then run select * from function() there is no need to remove any parentheses Commented Sep 30, 2019 at 14:00

2 Answers 2

6

Thanks to a_horse_with_no_name for the right answer! I'm posting it here for ... posterity?

In Postgres, doing SELECT (a, b) with parentheses returns a single record, which is an anonymous composite type. Removing the parentheses will return the columns individually: Select a, b.

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

Comments

2

When using a function with out parameters which only ever returns one row I was running into the same issue. The following resolved it for me:

var foo, bar string
err := db.QueryRow("select * from my_function()").Scan(&foo, &bar)

The function was of this form:

create or replace function my_function(
  out first_out varchar,
  out second_out json
) as $$
  -- etc.
$$ language plpgsql;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.