Sobes.tech
Junior — Middle

How to find the executed SQL query in PostgreSQL?

sobes.tech AI

Answer from AI

To find out the executed SQL query in PostgreSQL from a Java application, you can use several approaches:

  1. Logging on the PostgreSQL side:

    • Enable query logging in the PostgreSQL configuration (postgresql.conf), for example, log_statement = 'all'.
    • Logs will contain all executed queries.
  2. Logging on the Java side:

    • Use SQL logging libraries such as P6Spy or datasource-proxy, which intercept and log all SQL queries executed via JDBC.
  3. Output the query before execution:

    • If the query is built dynamically, you can log it before execution.
  4. Using the PostgreSQL pg_stat_activity function:

    • Execute a query against the system table pg_stat_activity to see current active queries.

Example query to pg_stat_activity:

SELECT pid, query, state, query_start
FROM pg_stat_activity
WHERE state = 'active';

Thus, for debugging and monitoring SQL queries in Java with PostgreSQL, it is best to use driver or database-level logging.

How to find the executed SQL query in PostgreSQL… - sobes.tech