The SQL you use in application support is different from the SQL you learn on a course. You’re rarely designing tables. You’re checking whether today’s trades landed, finding who is blocking whom, pulling a quick extract for a trader, and fixing a bad record safely under a change ticket. This page collects those everyday commands for the three databases you’ll meet most in banks: Oracle, SQL Server and PostgreSQL.
Preparing for an interview? See the companion page: SQL interview prep with practice questions.
Jump to
- 1. Connecting from the command line
- 2. Exploring an unfamiliar schema
- 3. Everyday data checks
- 4. Fixing data safely in production
- 5. Sessions, locks and blocking
- 6. Slow queries and execution plans
- 7. Space and growth
- 8. Exporting to CSV
- 9. Dialect cheat sheet: Oracle vs SQL Server vs PostgreSQL
- 10. SQL in shell scripts and health checks
1. Connecting from the command line
# Oracle (SQL*Plus)
sqlplus support_user@TRADEDB # prompts for the password
sqlplus -s /@TRADEDB @check.sql # silent mode, wallet login, run a script
# SQL Server (sqlcmd)
sqlcmd -S dbserver -d TradeDB -E # -E = Windows/Kerberos login
sqlcmd -S dbserver -d TradeDB -E -i check.sql -b # -b = exit with error code on failure
# PostgreSQL (psql)
psql -h dbhost -U support -d trading
psql -h dbhost -U support -d trading -v ON_ERROR_STOP=1 -f check.sql
Never put passwords on the command line or in scripts: they end up in shell history and process lists. Use an Oracle wallet, Kerberos/integrated authentication, or a protected ~/.pgpass file (permissions 600).
2. Exploring an unfamiliar schema
First day on a new application? These tell you what’s there.
| Task | Oracle | SQL Server | PostgreSQL |
|---|---|---|---|
| List tables | SELECT table_name FROM user_tables; | SELECT name FROM sys.tables; | \dt |
| Describe a table | DESC trades | EXEC sp_help 'dbo.trades'; | \d trades |
| Find a column anywhere | SELECT owner, table_name FROM all_tab_columns WHERE column_name LIKE '%CPTY%'; | SELECT table_name FROM INFORMATION_SCHEMA.COLUMNS WHERE column_name LIKE '%cpty%'; | SELECT table_name FROM information_schema.columns WHERE column_name LIKE '%cpty%'; |
| List indexes on a table | SELECT index_name, column_name FROM user_ind_columns WHERE table_name = 'TRADES'; | EXEC sp_helpindex 'dbo.trades'; | \di+ trades* |
| Who am I / which DB? | SELECT user, sys_context('USERENV','DB_NAME') FROM dual; | SELECT SUSER_SNAME(), DB_NAME(); | SELECT current_user, current_database(); |
Oracle stores unquoted names in UPPER CASE in its dictionary views, so search for 'TRADES', not 'trades'.
3. Everyday data checks
The queries behind most “is it working?” questions. Examples use PostgreSQL syntax; see the dialect cheat sheet for Oracle and SQL Server equivalents.
-- Did today's trades arrive? How many in each status?
SELECT status, COUNT(*)
FROM trades
WHERE trade_date = CURRENT_DATE
GROUP BY status;
-- The 20 most recent rows (has the feed stopped?)
SELECT trade_id, created_at, status
FROM trades
ORDER BY created_at DESC
LIMIT 20;
-- When did we last receive anything?
SELECT MAX(created_at) AS last_trade, NOW() - MAX(created_at) AS age
FROM trades;
-- Trades per hour today (spot a gap or a spike)
SELECT DATE_TRUNC('hour', created_at) AS hour, COUNT(*)
FROM trades
WHERE created_at >= CURRENT_DATE
GROUP BY 1
ORDER BY 1;
-- Rows with a missing mandatory value
SELECT COUNT(*) FROM trades WHERE cpty_id IS NULL OR isin IS NULL;
-- Duplicates on what should be unique
SELECT external_ref, COUNT(*)
FROM trades
GROUP BY external_ref
HAVING COUNT(*) > 1;
-- Orphans: trades pointing at a counterparty that doesn't exist
SELECT t.trade_id, t.cpty_id
FROM trades t
LEFT JOIN counterparties c ON c.cpty_id = t.cpty_id
WHERE c.cpty_id IS NULL;
4. Fixing data safely in production
Data fixes are where careers are made or broken. Always work under an approved change or incident, get the script peer-reviewed, and follow the same five steps:
- Count exactly the rows you expect to change, using the same WHERE clause as the fix.
- Back up those rows.
- Change them inside a transaction.
- Verify the row count matches step 1.
- Commit only if it does; otherwise roll back.
-- PostgreSQL example (incident INC0012345)
-- 1. Count
SELECT COUNT(*) FROM trades WHERE trade_id = 105 AND status = 'FAILED'; -- expect 1
-- 2. Back up
CREATE TABLE trades_bkp_inc0012345 AS
SELECT * FROM trades WHERE trade_id = 105;
-- 3. Change inside a transaction
BEGIN;
UPDATE trades
SET status = 'BOOKED', updated_by = 'INC0012345'
WHERE trade_id = 105 AND status = 'FAILED'; -- psql prints: UPDATE 1
-- 4. Verify
SELECT trade_id, status FROM trades WHERE trade_id = 105;
-- 5. Commit if the count matched, otherwise ROLLBACK;
COMMIT;
| Oracle | SQL Server | PostgreSQL | |
|---|---|---|---|
| Start a transaction | Implicit: starts with your first DML statement | BEGIN TRAN; | BEGIN; |
| Back up rows | CREATE TABLE bkp AS SELECT ... | SELECT * INTO bkp FROM ... | CREATE TABLE bkp AS SELECT ... |
| Auto-commit by default? | No in SQL*Plus (DDL always commits) | Yes, unless you BEGIN TRAN | Yes in psql, unless you BEGIN |
Two traps: in Oracle, any DDL statement (such as CREATE TABLE) silently commits your open transaction, so take the backup before the update. And an open, uncommitted transaction holds locks: don’t leave a session sitting at step 4 while you go to a meeting.
5. Sessions, locks and blocking
“The app is hanging” is very often one session blocking everyone else, typically an uncommitted transaction.
Oracle
-- Active user sessions
SELECT sid, serial#, username, status, sql_id, event, seconds_in_wait
FROM v$session
WHERE username IS NOT NULL AND status = 'ACTIVE';
-- Who is blocked, and by whom
SELECT sid, serial#, username, blocking_session, event, seconds_in_wait
FROM v$session
WHERE blocking_session IS NOT NULL;
-- Kill a session (DBA rights; only with approval)
ALTER SYSTEM KILL SESSION '123,45678' IMMEDIATE;
SQL Server
-- Quick overview (look at the BlkBy column)
EXEC sp_who2;
-- Blocked requests and what they're waiting on
SELECT session_id, blocking_session_id, wait_type, wait_time, status, command
FROM sys.dm_exec_requests
WHERE blocking_session_id <> 0;
-- Kill a session (only with approval)
KILL 57;
PostgreSQL
-- What's running, longest first
SELECT pid, usename, state, NOW() - query_start AS runtime, wait_event_type, LEFT(query, 80)
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY runtime DESC;
-- Blocked sessions and who blocks them
SELECT pid, pg_blocking_pids(pid) AS blocked_by, LEFT(query, 80)
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
-- Sessions sitting in an open transaction doing nothing (a classic blocker)
SELECT pid, usename, NOW() - xact_start AS open_for
FROM pg_stat_activity
WHERE state = 'idle in transaction';
SELECT pg_cancel_backend(4321); -- cancel the current query (gentler)
SELECT pg_terminate_backend(4321); -- end the whole session
Before killing anything, find out what the blocking session is doing. Killing a session rolls back its open transaction, which can take as long as the work it had already done, and might be a batch job someone is waiting for.
6. Slow queries and execution plans
-- Oracle: top SQL by total elapsed time
SELECT sql_id, executions, ROUND(elapsed_time/1e6) AS secs, SUBSTR(sql_text, 1, 80)
FROM v$sql
ORDER BY elapsed_time DESC
FETCH FIRST 10 ROWS ONLY;
-- Oracle: execution plan
EXPLAIN PLAN FOR SELECT * FROM trades WHERE cpty_id = 3;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
-- SQL Server: I/O and timing for a query you run
SET STATISTICS IO, TIME ON;
-- SQL Server: what's running right now, with its text
SELECT r.session_id, r.total_elapsed_time/1000 AS secs, t.text
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
ORDER BY r.total_elapsed_time DESC;
-- PostgreSQL: plan only
EXPLAIN SELECT * FROM trades WHERE cpty_id = 3;
-- PostgreSQL: plan plus real timings (this RUNS the query)
EXPLAIN ANALYZE SELECT * FROM trades WHERE cpty_id = 3;
What to look for in a plan: a full table scan on a big table where you expected an index, estimated row counts wildly different from actual ones (stale statistics), and nested loops over large row counts. Never run EXPLAIN ANALYZE on an UPDATE or DELETE in production: it executes the statement.
7. Space and growth
-- Oracle: tablespace usage (needs DBA views)
SELECT tablespace_name, ROUND(used_percent, 1) AS pct_used
FROM dba_tablespace_usage_metrics
ORDER BY used_percent DESC;
-- SQL Server: size of one table / the whole database
EXEC sp_spaceused 'dbo.trades';
EXEC sp_spaceused;
-- PostgreSQL: table (incl. indexes) and database size
SELECT pg_size_pretty(pg_total_relation_size('trades'));
SELECT pg_size_pretty(pg_database_size(current_database()));
A tablespace or transaction log filling up stops all writes, which for a trading system means no new trades. Check growth trends weekly, not just when the alert fires.
8. Exporting to CSV
-- Oracle SQL*Plus 12.2+
SET MARKUP CSV ON
SET FEEDBACK OFF
SPOOL failed_trades.csv
SELECT trade_id, cpty_id, status FROM trades WHERE status = 'FAILED';
SPOOL OFF
# SQL Server: comma-separated, trimmed, to a file
sqlcmd -S dbserver -d TradeDB -E -s"," -W -o failed_trades.csv \
-Q "SET NOCOUNT ON; SELECT trade_id, cpty_id, status FROM trades WHERE status = 'FAILED'"
-- PostgreSQL (psql): \copy writes the file on YOUR machine
\copy (SELECT trade_id, cpty_id, status FROM trades WHERE status = 'FAILED') TO 'failed_trades.csv' CSV HEADER
Check what you’re exporting: trade and client data is usually confidential, so keep extracts on approved storage and send them only through approved channels.
9. Dialect cheat sheet
| Task | Oracle | SQL Server | PostgreSQL |
|---|---|---|---|
| Current date and time | SYSDATE | GETDATE() | NOW() |
| Today’s date only | TRUNC(SYSDATE) | CAST(GETDATE() AS DATE) | CURRENT_DATE |
| Add one day | d + 1 | DATEADD(day, 1, d) | d + INTERVAL '1 day' |
| Text to date | TO_DATE('2026-11-17','YYYY-MM-DD') | CAST('2026-11-17' AS DATE) | DATE '2026-11-17' |
| Replace NULL | NVL(x, 0) | ISNULL(x, 0) | COALESCE(x, 0) |
| Join strings | a || b | a + b | a || b |
| First 10 rows | FETCH FIRST 10 ROWS ONLY | SELECT TOP 10 ... | LIMIT 10 |
| Select without a table | SELECT 1 FROM dual; | SELECT 1; | SELECT 1; |
| Auto-increment ID | GENERATED AS IDENTITY | IDENTITY(1,1) | GENERATED AS IDENTITY |
COALESCE and CASE work in all three, so prefer them in scripts that need to be portable. Oracle versions before 12c use ROWNUM <= 10 instead of FETCH FIRST.
10. SQL in shell scripts and health checks
Wrap a query in a script that exits non-zero when something’s wrong, and your scheduler or monitoring tool can alert on it.
#!/usr/bin/env bash
set -euo pipefail
failed=$(psql -h dbhost -U support -d trading -At -v ON_ERROR_STOP=1 -c \
"SELECT COUNT(*) FROM trades WHERE status = 'FAILED' AND trade_date = CURRENT_DATE")
if [ "$failed" -gt 0 ]; then
echo "$(date '+%F %T') ALERT: $failed failed trades today"
exit 1
fi
echo "$(date '+%F %T') OK: no failed trades"
# Oracle equivalent: make SQL*Plus fail loudly
sqlplus -s /@TRADEDB <<'EOF'
WHENEVER SQLERROR EXIT SQL.SQLCODE
SET HEADING OFF FEEDBACK OFF
SELECT COUNT(*) FROM trades WHERE status = 'FAILED' AND trade_date = TRUNC(SYSDATE);
EXIT
EOF
-At in psql prints just the value (no headers or padding), which makes the result easy to use in Bash. WHENEVER SQLERROR EXIT stops SQL*Plus from carrying on, and returning success, after an error.