For a general open set, we characterize the compactness of the embedding W01,p↪Lq in terms of the summability of its torsion function. In particular, for 1≤q<p we obtain that the embedding is continuous if and only if it is compact. The proofs crucially exploit a {\it torsional Hardy inequality} that we investigate in details.