I am working in Postgresql and am trying to find what table a specific word is in. For example, I am trying to find out what table the word "banana" is in. The database is agriculture and schema is fruit. Is there a query I can run that would return what table banana is in?
Question posted in PostgreSQL
The official documentation can be found here.
The official documentation can be found here.
2
Answers
Not efficient, but you can do it conveniently by converting the entire table to json and check that:
You can check many tables at once:
The following query will search for the value "banana" in all columns with a data type of either
character varying
ortext
in every table in thepublic
schema:Note that the
search_criteria
expression explicitly casts each searched column to typeTEXT
. This has been done so that the query can be easily modified to search non-text columns (e.g., JSON or XML). The cast has no adverse effects if the column is alreadycharacter varying
ortext
.The function,
QUERY_TO_XML
, enables executing dynamically generated queries without resorting to procedural code (e.g., PL/pgSQL). Because of XML’s low information density,QUERY_TO_XML
is not practical for queries that return large data sets, but can be very useful for queries that return only a few rows.Changing
=
toILIKE
in thesearch_criteria
expression and passing'%banana%'
instead of'banana'
toFORMAT
in the call toQUERY_TO_XML
will perform a case-insensitive search for "banana" contained within a column.This query is likely to take a long time to execute if there are tables in the search space with a large number of rows. Modifying the criteria in the
search_tables
CTE to restrict the tables and columns included in the search space can help reduce the time to complete.