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:
-
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.
- Enable query logging in the PostgreSQL configuration (
-
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.
-
Output the query before execution:
- If the query is built dynamically, you can log it before execution.
-
Using the PostgreSQL
pg_stat_activityfunction:- Execute a query against the system table
pg_stat_activityto see current active queries.
- Execute a query against the system table
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.