SSH Tunnels for Remote Database Access: ssh -L, Explained

Posted by Kyle Hankinson August 28, 2026


A production database with port 3306 or 5432 open to the internet is a breach waiting for a scanner to find it, so sane deployments keep the database on a private network and expose exactly one hardened thing: an SSH server, usually called a bastion or jump host. To query the database from your laptop, you tunnel through it. The command is one line, but most explanations skip which machine each part refers to, and that gap is where all the confusing failures live.

ssh -N -L 15432:db.internal:5432 you@bastion.example.com

Reading left to right, the -L argument is local_port:target_host:target_port, and the three parts belong to three different machines:

Piece Where it lives What it means
15432 your laptop ssh opens this port on 127.0.0.1 and listens
db.internal:5432 resolved by the bastion where the bastion forwards each connection
you@bastion.example.com the bastion the only machine you need SSH access to

The part people miss: db.internal is resolved by the bastion, not by your laptop. It can be a private DNS name or a 10.x address that means nothing on your side; it only has to be reachable from the bastion. By the same logic, writing 127.0.0.1 there means the bastion itself, which is what you want when the database runs on the same box as the SSH server. -N just means "forward ports, do not run a remote shell".

Once the tunnel is up, you point your database client at your own machine:

psql -h 127.0.0.1 -p 15432 -U app_user mydb

Your normal database credentials still apply. SSH authentication gets you a path to the database; it does not log you into it. Two locks, two keys.

Proving it works end to end

Claims about networking deserve a demonstration, so I built the whole topology locally with Docker: a postgres:16 container with no published ports (verified: docker port shows nothing, so nothing on my Mac can reach it directly) and an OpenSSH bastion container on the same private network, publishing only its SSH port. Then, from the Mac:

ssh -i tunnel_key -p 2222 -N -L 15555:tun-pg:5432 tunneluser@127.0.0.1

Note that tun-pg is a container name only the bastion's network can resolve, exactly like db.internal above. With the tunnel up, psql connected through the forwarded port 15555 on my machine using the ordinary Postgres password, and:

SELECT version();
PostgreSQL 16.14 (Debian 16.14-1.pgdg13+1) on aarch64-unknown-linux-gnu ...

One more query is worth running, because it exposes a detail that bites later:

SELECT inet_server_addr(), inet_client_addr();
 inet_server_addr | inet_client_addr
------------------+------------------
 172.18.0.2       | 172.18.0.3

The client address is the bastion's IP, not my machine's. As far as the database can tell, the bastion connected to it. That is why a pg_hba.conf rule scoped to your office IP will not match a tunneled connection, and why a MySQL grant like 'app'@'203.0.113.%' fails through a tunnel: the source the server sees is the bastion (or, when the daemon does the forwarding differently, its loopback). PostgreSQL's manual has a short chapter on tunnels that makes the same point.

The MySQL localhost trap

MySQL adds one gotcha of its own: to the MySQL client, the hostname localhost does not mean 127.0.0.1. It means "use the Unix socket", which skips TCP entirely and therefore skips your tunnel. I verified against a MySQL 8 server by running status after connecting both ways:

mysql -h localhost  ->  Connection: Localhost via UNIX socket
mysql -h 127.0.0.1  ->  Connection: 127.0.0.1 via TCP/IP

So a tunneled MySQL connection must use -h 127.0.0.1 -P 13306, never -h localhost. If you have ever had a tunnel "work" while clearly hitting the wrong server, or fail with a socket error mentioning /tmp/mysql.sock, this was it. The behavior is documented on MySQL's connecting page.

The other engines each have one note worth knowing. SQL Server tunnels fine to its fixed port 1433, but named instances use dynamic ports assigned at startup; pin the instance to a static port before trying to forward to it. Oracle tunnels to the listener on 1521, and the tunnel solves only the network layer: you still need the correct service name on the other side, or you trade your firewall problem for an ORA-12514 (decoded in SID vs service name vs TNS). And SQLite is the reminder that not everything needs a tunnel: it is a file, so copy the file.

When the tunnel fails: three errors, decoded

Every message below is one I captured from a real failing tunnel, and each points at a different culprit.

channel 2: open failed: administratively prohibited: open failed

The SSH server is refusing to forward. My bastion image ships with AllowTcpForwarding no in sshd_config, and this is exactly what the client printed until I changed it. If you see this, the fix is on the server (or in your hosting provider's policy), not in your command.

bind [0.0.0.0]:15555: Address already in use
channel_setup_fwd_listener_tcpip: cannot listen to port: 15555

Something on your laptop already owns that local port. Nine times out of ten it is a previous tunnel you forgot about; find it with lsof -i :15555 or just pick another port.

channel 2: open failed: connect failed: Connection refused

The subtle one. SSH is connected and forwarding happily, but the bastion could not reach the target host and port. The tunnel itself accepts your client's connection, then fails only when traffic flows, so your database client reports a dropped connection rather than anything mentioning SSH. I produced this by pointing the tunnel at port 5433 instead of 5432. Wrong target port, wrong target host, or a database that is down all land here.

For tunnels you keep open all day, three flags earn their keep: -N as above, -f to background ssh after authentication, and -o ServerAliveInterval=30 so idle tunnels survive aggressive NAT timeouts. If the database is two hops away, -J first-bastion chains jump hosts without nesting tunnels by hand. The full option reference is the OpenSSH manual.

If you would rather not babysit terminal windows, this is one of the few things a GUI can genuinely automate rather than merely wrap: SQLPro Studio lets you attach an SSH tunnel to a connection (bastion host, port, user, key or password), then opens the forwarding and points the client at it every time you connect, which is precisely the -L mechanics above minus the shell. Whether you script it or click it, the mental model stays the same: one listener on your machine, one hop through the bastion, and a database that still thinks it never talked to the outside world.


Tags: MySQL PostgreSQL Microsoft SQL Server Oracle

SQL NULL traps: = NULL, NOT IN, and sort order

Posted by Kyle Hankinson August 7, 2026


A query that returns zero rows with zero errors is harder to debug than one that fails loudly, and NULL is behind more of those silent empties than everything else combined. The root cause is always the same: SQL comparisons involving NULL do not evaluate to true or false but to a third value, UNKNOWN, and a WHERE clause keeps only rows where the condition is TRUE. UNKNOWN rows are dropped without comment.

That one rule produces three distinct traps. All of the MySQL, PostgreSQL, and SQLite behavior below was run against MySQL 8.4, PostgreSQL 16, and SQLite 3.50.6; the SQL Server behavior is cited from Microsoft's documentation, linked where used.

Two tables are enough to demonstrate everything:

CREATE TABLE customers (id int, name varchar(20));
INSERT INTO customers VALUES (1, 'alice'), (2, 'bob'), (3, 'carol');

CREATE TABLE orders (customer_id int);
INSERT INTO orders VALUES (1), (NULL);   -- one order has no customer

Trap 1: WHERE col = NULL matches nothing

The natural way to find the orphaned order reads fine and returns nothing:

SELECT count(*) FROM orders WHERE customer_id = NULL;   -- 0
SELECT count(*) FROM orders WHERE customer_id IS NULL;  -- 1

Identical results on MySQL, PostgreSQL, and SQLite: the = version finds zero rows even though a NULL row is sitting right there. NULL means "unknown", and asking whether an unknown value equals another unknown value can only be answered "unknown", so the comparison never becomes TRUE for any row. SQL Server follows the same logic under its default settings; Microsoft's NULL and UNKNOWN page states that comparisons between two null values, or between a null value and any other value, return unknown, and directs you to IS NULL / IS NOT NULL.

When you genuinely want NULL-tolerant equality, where NULL equals NULL and nothing else, every engine has an operator for it, they just disagree on the spelling:

Engine NULL-safe equality Status
MySQL 8.4 a <=> b verified: NULL <=> NULL returns 1, 1 <=> NULL returns 0
PostgreSQL 16 a IS NOT DISTINCT FROM b verified: returns true for two NULLs, false for 1 vs NULL
SQLite a IS b verified; 3.50.6 also accepts IS NOT DISTINCT FROM
SQL Server 2022+ a IS NOT DISTINCT FROM b per the IS NOT DISTINCT FROM docs; not available before SQL Server 2022

MySQL's comparison operators documentation notes that <=> is equivalent to the standard IS NOT DISTINCT FROM, so all four spellings mean the same thing.

Trap 2: one NULL turns NOT IN into an empty result

Now the trap with real teeth. Find the customers who have no orders:

SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);

You would expect bob and carol. On MySQL 8.4, PostgreSQL 16, and SQLite 3.50.6 alike, this returns zero rows. Not a wrong list, an empty one, and the same three-valued logic explains it in SQL Server as well.

The subquery produces the list (1, NULL), and id NOT IN (1, NULL) expands to id <> 1 AND id <> NULL. That second comparison is UNKNOWN for every row in the table, and TRUE AND UNKNOWN is UNKNOWN, so no row ever qualifies. One stray NULL in the subquery quietly vetoes the entire result. This is the nastiest variety of NULL bug because the query works perfectly in development and then returns nothing in production the day the first NULL shows up in that column.

Two fixes, both verified to return bob and carol on all three engines. The direct one is to keep NULLs out of the list:

SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders
                 WHERE customer_id IS NOT NULL);

The better one is to stop using NOT IN for this job entirely:

SELECT name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o
                  WHERE o.customer_id = c.id);

NOT EXISTS asks "is there a matching row?" instead of comparing values, so NULLs in the subquery cannot poison it. It states the anti-join intent directly (the same family of shapes covered in SQL joins explained), and it is safe to use as a habit even on columns that are NOT NULL today, because columns have a way of becoming nullable later.

Trap 3: every engine sorts NULLs somewhere different

The first two traps behave identically everywhere. The third is where the engines part ways. Sort three values, one of them NULL:

CREATE TABLE s (v int);
INSERT INTO s VALUES (2), (NULL), (1);
SELECT v FROM s ORDER BY v ASC;
Engine ASC order DESC order NULLS FIRST/LAST syntax
MySQL 8.4 NULL, 1, 2 2, 1, NULL not supported
PostgreSQL 16 1, 2, NULL NULL, 2, 1 supported
SQLite 3.50.6 NULL, 1, 2 2, 1, NULL supported since 3.30 (2019)
SQL Server NULL first (docs) NULL last (docs) not supported

MySQL and SQLite treat NULL as smaller than every value, so it leads an ascending sort. PostgreSQL treats NULL as larger, so it trails. SQL Server sides with MySQL: the ORDER BY clause documentation states that NULL values are treated as the lowest possible values. The practical consequence: port a "latest items first, blanks at the bottom" query from MySQL to Postgres and the blanks migrate from bottom to top with no error and no warning.

Where the standard syntax exists, pinning the position is trivial. Verified on PostgreSQL 16 and SQLite 3.50.6:

SELECT v FROM s ORDER BY v ASC NULLS LAST;   -- 1, 2, NULL

On MySQL 8.4 that syntax is a hard error (ERROR 1064), but a boolean sort key does the same job, verified to return 1, 2, NULL:

SELECT v FROM s ORDER BY (v IS NULL), v;

v IS NULL is 0 for values and 1 for NULLs, so NULLs sink to the end. SQL Server lacks the syntax too; the equivalent trick there is ORDER BY CASE WHEN v IS NULL THEN 1 ELSE 0 END, v, using the conditional ordering pattern shown in the same ORDER BY documentation.

Chasing this class of bug across engines is considerably less painful when you can run the identical script against MySQL, PostgreSQL, SQL Server, and SQLite connections in one place and compare the grids, which is precisely the sort of side-by-side work SQLPro Studio exists for.

The habits that make all three traps a non-issue: write IS NULL rather than = NULL always, reach for NOT EXISTS rather than NOT IN under a subquery, and never let a query's correctness depend on where the engine happens to put NULLs in a sort. Declare it with NULLS LAST or a boolean sort key, and the query means the same thing everywhere.


Tags: MySQL PostgreSQL Microsoft SQL Server SQLite

SQL Window Functions: SUM, AVG, LAG, and LEAD

Posted by Kyle Hankinson January 25, 2026


Window functions perform calculations across a set of rows related to the current row — without collapsing the result into groups like GROUP BY does. They are one of the most powerful features in modern SQL.

The OVER() Clause

Every window function uses OVER() to define which rows to include:

SELECT name, department, salary,
    SUM(salary) OVER () AS total_salary
FROM employees;

This adds a total_salary column with the sum of all salaries — without grouping. Every row still appears individually.

PARTITION BY

PARTITION BY divides rows into groups (like GROUP BY, but without collapsing):

SELECT name, department, salary,
    SUM(salary) OVER (PARTITION BY department) AS dept_total,
    AVG(salary) OVER (PARTITION BY department) AS dept_avg
FROM employees;

Each row shows the department total and average alongside the individual salary.

ORDER BY in OVER()

Adding ORDER BY creates a running calculation:

SELECT order_date, amount,
    SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM orders;
order_date amount running_total
Jan 1 100 100
Jan 2 150 250
Jan 3 75 325
Jan 4 200 525

LAG and LEAD

Compare the current row to previous or next rows:

SELECT
    month,
    revenue,
    LAG(revenue) OVER (ORDER BY month) AS prev_month,
    revenue - LAG(revenue) OVER (ORDER BY month) AS month_over_month
FROM monthly_revenue;
month revenue prev_month month_over_month
Jan 10000 NULL NULL
Feb 12000 10000 2000
Mar 11500 12000 -500

LAG(col, n) looks back n rows (default 1). LEAD(col, n) looks forward n rows.

Default Values

Avoid NULLs for the first/last row:

LAG(revenue, 1, 0) OVER (ORDER BY month)  -- returns 0 instead of NULL

FIRST_VALUE and LAST_VALUE

SELECT name, department, salary,
    FIRST_VALUE(name) OVER (PARTITION BY department ORDER BY salary DESC) AS highest_paid
FROM employees;

Percent of Total

SELECT name, department, salary,
    ROUND(100.0 * salary / SUM(salary) OVER (PARTITION BY department), 1) AS pct_of_dept
FROM employees;

Moving Average

Use a frame specification to average over a sliding window:

SELECT order_date, amount,
    AVG(amount) OVER (
        ORDER BY order_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS seven_day_avg
FROM daily_sales;

Frame Types

Frame Meaning
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW Current row + 2 rows before
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW All rows from start to current (default for running totals)
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING 3-row window centered on current
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING All rows in partition

Combining Multiple Window Functions

SELECT
    name, department, salary,
    RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank,
    SUM(salary) OVER (PARTITION BY department) AS dept_total,
    ROUND(100.0 * salary / SUM(salary) OVER (), 2) AS pct_of_company
FROM employees
ORDER BY department, salary DESC;

WINDOW Clause (Reusable Definitions)

Avoid repeating the same OVER clause:

SELECT
    order_date, amount,
    SUM(amount) OVER w AS running_total,
    AVG(amount) OVER w AS running_avg,
    COUNT(*) OVER w AS running_count
FROM orders
WINDOW w AS (ORDER BY order_date);

Supported in PostgreSQL, MySQL 8.0+, and SQLite 3.28+. Not supported in SQL Server or Oracle.

Database Compatibility

Feature MySQL PostgreSQL SQL Server Oracle SQLite
Basic window functions 8.0+ 8.4+ 2005+ 8i+ 3.25+
LAG / LEAD 8.0+ 8.4+ 2012+ 8i+ 3.25+
Frame specification 8.0+ 8.4+ 2012+ 8i+ 3.28+
WINDOW clause 8.0+ Yes No No 3.28+

Tags: MySQL PostgreSQL Microsoft SQL Server

UNION vs UNION ALL in SQL

Posted by Kyle Hankinson November 15, 2025


Short answer

UNION UNION ALL
Duplicate rows Removed (like SELECT DISTINCT over the combined result) Kept
Speed Slower: the database has to sort or hash the whole result to find duplicates Faster: results are simply appended
Use it when You need each row only once The queries cannot overlap, or duplicates are meaningful

Default to UNION ALL, and switch to UNION only when you really need duplicates removed. Both need the same number of columns, in the same order, with compatible types.

UNION and UNION ALL both combine results from multiple SELECT statements, but they handle duplicate rows differently — and the performance difference can be significant.

The Difference

  • UNION removes duplicate rows from the combined result (like an implicit DISTINCT)
  • UNION ALL keeps all rows, including duplicates
-- Table A: 1, 2, 3
-- Table B: 2, 3, 4

SELECT id FROM table_a
UNION
SELECT id FROM table_b;
-- Result: 1, 2, 3, 4 (duplicates removed)

SELECT id FROM table_a
UNION ALL
SELECT id FROM table_b;
-- Result: 1, 2, 3, 2, 3, 4 (all rows kept)

Performance

UNION must sort or hash the entire result set to find and remove duplicates. On large datasets, this is expensive.

UNION ALL simply appends the results — no additional processing.

Rule of thumb: Use UNION ALL unless you specifically need duplicate removal. In practice, this is the majority of cases.

When UNION ALL is Correct

If the source queries cannot produce overlapping rows, deduplication is wasted work:

-- Orders from different months — no overlap possible
SELECT * FROM orders WHERE order_date >= '2025-01-01' AND order_date < '2025-02-01'
UNION ALL
SELECT * FROM orders WHERE order_date >= '2025-02-01' AND order_date < '2025-03-01';
-- Different tables entirely
SELECT 'customer' AS source, name, email FROM customers
UNION ALL
SELECT 'vendor' AS source, name, email FROM vendors;

When UNION is Correct

Use UNION when you genuinely need to deduplicate:

-- Find all cities where we have customers OR offices
SELECT city FROM customers
UNION
SELECT city FROM offices;

Rules for UNION / UNION ALL

Both require:

  1. Same number of columns in each SELECT
  2. Compatible data types (the database will attempt implicit conversion)
-- This works
SELECT name, email FROM customers
UNION ALL
SELECT company_name, contact_email FROM vendors;

-- This fails (different column counts)
SELECT name, email, phone FROM customers
UNION ALL
SELECT company_name, contact_email FROM vendors;

Column names in the result come from the first SELECT statement.

ORDER BY with UNION

ORDER BY applies to the final combined result. Place it after the last SELECT:

SELECT name, 'customer' AS type FROM customers
UNION ALL
SELECT name, 'vendor' AS type FROM vendors
ORDER BY name;

You cannot put ORDER BY inside individual SELECT statements (except in subqueries).

UNION ALL with Aggregation

A common pattern — combine data then aggregate:

WITH all_transactions AS (
    SELECT amount, transaction_date FROM sales
    UNION ALL
    SELECT -amount, transaction_date FROM refunds
)
SELECT
    DATE_TRUNC('month', transaction_date) AS month,
    SUM(amount) AS net_revenue
FROM all_transactions
GROUP BY 1
ORDER BY 1;

Combining More Than Two Queries

You can chain multiple UNIONs:

SELECT name FROM customers
UNION ALL
SELECT name FROM vendors
UNION ALL
SELECT name FROM employees
ORDER BY name;

INTERSECT and EXCEPT

Related set operations worth knowing:

-- Rows in both queries
SELECT city FROM customers
INTERSECT
SELECT city FROM offices;

-- Rows in the first query but not the second
SELECT city FROM customers
EXCEPT            -- SQL Server, PostgreSQL, SQLite
SELECT city FROM offices;

-- Oracle uses MINUS instead of EXCEPT
SELECT city FROM customers
MINUS
SELECT city FROM offices;

MySQL 8.0.31+ supports INTERSECT and EXCEPT. Earlier versions do not.


Tags: MySQL PostgreSQL Microsoft SQL Server

Common Table Expressions (CTEs) in SQL

Posted by Kyle Hankinson July 10, 2025


A Common Table Expression (CTE) is a named temporary result set that exists for the duration of a single query. CTEs make complex queries easier to read, write, and debug.

Basic CTE Syntax

WITH active_users AS (
    SELECT id, name, email
    FROM users
    WHERE status = 'active'
)
SELECT * FROM active_users WHERE email LIKE '%@company.com';

The WITH clause defines the CTE, and the main query uses it like a table. The CTE only exists for that one statement.

Why Use CTEs?

Compare a nested subquery to a CTE:

-- Nested subquery (hard to read)
SELECT d.name, stats.avg_salary
FROM departments d
JOIN (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    WHERE status = 'active'
    GROUP BY department_id
) stats ON d.id = stats.department_id
WHERE stats.avg_salary > 75000;

-- CTE (much clearer)
WITH dept_salaries AS (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    WHERE status = 'active'
    GROUP BY department_id
)
SELECT d.name, ds.avg_salary
FROM departments d
JOIN dept_salaries ds ON d.id = ds.department_id
WHERE ds.avg_salary > 75000;

Multiple CTEs

Chain multiple CTEs with commas:

WITH
active_users AS (
    SELECT * FROM users WHERE status = 'active'
),
user_orders AS (
    SELECT user_id, COUNT(*) AS order_count, SUM(total) AS total_spent
    FROM orders
    GROUP BY user_id
)
SELECT au.name, uo.order_count, uo.total_spent
FROM active_users au
JOIN user_orders uo ON au.id = uo.user_id
ORDER BY uo.total_spent DESC;

Each CTE can reference the ones defined before it.

Recursive CTEs

Recursive CTEs solve hierarchical data problems like org charts, category trees, and bill-of-materials.

Employee Org Chart

WITH RECURSIVE org_chart AS (
    -- Anchor: start with the CEO (no manager)
    SELECT id, name, manager_id, 0 AS depth
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- Recursive: find each employee's direct reports
    SELECT e.id, e.name, e.manager_id, oc.depth + 1
    FROM employees e
    JOIN org_chart oc ON e.manager_id = oc.id
)
SELECT REPEAT('  ', depth) || name AS org_tree, depth
FROM org_chart
ORDER BY depth, name;

Building a Path (Breadcrumbs)

WITH RECURSIVE category_path AS (
    SELECT id, name, parent_id, name AS path
    FROM categories
    WHERE parent_id IS NULL

    UNION ALL

    SELECT c.id, c.name, c.parent_id,
           cp.path || ' > ' || c.name
    FROM categories c
    JOIN category_path cp ON c.parent_id = cp.id
)
SELECT name, path FROM category_path ORDER BY path;

Result: Electronics > Computers > Laptops

Number Series

Generate a sequence of numbers without a table:

WITH RECURSIVE numbers AS (
    SELECT 1 AS n
    UNION ALL
    SELECT n + 1 FROM numbers WHERE n < 100
)
SELECT n FROM numbers;

Database Compatibility

Database Basic CTE Recursive CTE Keyword
PostgreSQL Yes Yes WITH RECURSIVE
MySQL 8.0+ Yes Yes WITH RECURSIVE
SQL Server 2005+ Yes Yes WITH (no RECURSIVE keyword)
Oracle 11g+ Yes Yes WITH (no RECURSIVE keyword)
SQLite 3.8.3+ Yes Yes WITH RECURSIVE

SQL Server and Oracle do not use the RECURSIVE keyword — the database detects recursion automatically.

Preventing Infinite Loops

A bug in the recursive condition can cause infinite recursion. Protect against it:

-- PostgreSQL / MySQL: limit depth
WITH RECURSIVE tree AS (
    SELECT id, parent_id, 1 AS depth FROM nodes WHERE parent_id IS NULL
    UNION ALL
    SELECT n.id, n.parent_id, t.depth + 1
    FROM nodes n JOIN tree t ON n.parent_id = t.id
    WHERE t.depth < 50  -- safety limit
)
SELECT * FROM tree;

-- SQL Server: OPTION (MAXRECURSION)
WITH tree AS (...)
SELECT * FROM tree OPTION (MAXRECURSION 100);

CTE vs Subquery vs Temp Table

CTE Subquery Temp Table
Readability Best Worst (nested) Good
Reusable in same query Yes No Yes
Persists across queries No No Yes
Indexable No No Yes
Recursive support Yes No No

Tags: MySQL PostgreSQL Microsoft SQL Server

More articles: