Sorry, the correct version handling all cases. Seems to work when there are gaps between segments and when segments are touching each other:<div><br></div><div><div><font face="'courier new', monospace">create or replace function st_makeShortestLine(g1 geometry, g2 geometry) returns geometry as $$</font></div>
<div><font face="'courier new', monospace"><br></font></div><div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span>with dist as (</font></div><div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span>select st_distance(st_endPoint($1), st_endPoint($2)) as dee,</font></div>
<div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> st_distance(st_endPoint($1), st_startPoint($2)) as des,</font></div><div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> st_distance(st_startPoint($1), st_endPoint($2)) as dse,</font></div>
<div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> st_distance(st_startPoint($1), st_startPoint($2)) as dss</font></div><div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span>) select case when st_distance(st_startPoint($1), st_startPoint($2)) = 0 then st_makeline(st_reverse($1), $2)</font></div>
<div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> when st_distance(st_startPoint($1), st_endPoint($2)) = 0 then st_makeline($2, $1)</font></div><div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> when st_distance(st_endPoint($1), st_endPoint($2)) = 0 then st_makeline($1, st_reverse($2))</font></div>
<div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> when st_distance(st_endPoint($1), st_startPoint($2)) = 0 then st_makeline($1, $2)</font></div><div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> when dee < des and dee < dse and dee < dss then st_makeline($1, st_reverse($2))</font></div>
<div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> when des < dee and des < dse and des < dss then st_makeline($1, $2)</font></div><div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> when dss < dee and dss < dse and dss < des then st_makeline(st_reverse($1), $2)</font></div>
<div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span> else st_makeline($2, $1) end</font></div><div><font face="'courier new', monospace"><span class="Apple-tab-span" style="white-space:pre"> </span>from dist;</font></div>
<div><font face="'courier new', monospace">$$ language SQL;</font></div></div>