Check a whole table for a single value

前端 未结 2 1830
栀梦
栀梦 2021-01-23 01:46

Background: I\'m converting a database table to a format that doesn\'t support null values. I want to replace the null values with an arbitrary number so my ap

2条回答
  •  我在风中等你
    2021-01-23 02:15

    You can use a special feature of the PostgreSQL type system:

    SELECT *
    FROM   tbl t
    WHERE  t::text LIKE '%999999%';
    

    There is a composite type of the same name for every table that you create in PostgreSQL. And there is a text representation for every type in PostgreSQL (to input / output values).

    Therefore you can just cast the whole row to text and if the string '999999' is contained in any column (its text representation, to be precise) it is guaranteed to show in the query above.

    You cannot rule out false positives completely, though, if separators and / or decorators used by Postgres for the row representation can be part of the search term. It's just very unlikely. And positively not the case for your search term '999999'.

    There was a very similar question on codereview.SE recently. I added some more explanation in my answer there.

提交回复
热议问题