Tips N’ Tricks – looking for value in all columns of a table

Every so often you might need to find a value regardless of which column it's in.

Of course not in application code, as this would be very slow. But you might be in situation where you just don't know where did application get some value from, and you want to find it in table. Table that has 1-2 fields is trivial to search, but if you have 15 columns, naming them all in WHERE clause is tedious.

In such case you can use simple trick which represents whole row as text.

From PostgreSQL 8.3 you can simply:

SELECT t.*
FROM your_table t
WHERE t::text ~* 'what_you_are_looking_for';

If you're on 8.2 (sorry, I don't have any Pg installation with 8.1 or earlier versions), you will need to cast it “manually":

SELECT t.*
FROM your_table t
WHERE textin( record_out(t) ) ~* 'what_you_are_looking_for';

And that's all. Of course – this is not indexable, and will require full table scan, but sometimes you just have to find out where this value came from.

4 thoughts on “Tips N’ Tricks – looking for value in all columns of a table”

  1. Where do You get that knowledge from? And don’t tell me it is all in manual.

  2. In 8.4 you can also use “magic” column t.name to achieve the same result, ie:

    SELECT t.name FROM table t;

    (using alias is mandatory, table can not contain column “name”).

    In 8.3 there is another “magic” column – t.text

    If you want to know where it comes from just read Depesz’s answer to my post:
    http://bit.ly/bYMGL3

Comments are closed.