Given an affine algebraic variety V over R with real points V(R) compact and a non-negative polynomial function fis an element of[V] with finitely many real zeros, we establish a local-global criterion for f to be a sum of squares in R[V]. We then specialize to the case where V is a curve. The notion of virtual compactness is introduced, and it is shown that in the local-global principle, compactness of V(R) can be relaxed to virtual compactness. The irreducible curves on which every non-negative polynomial is a sum of squares are classified. All results are extended to the more general framework of preorders. Moreover, applications to the K-moment problem from analysis are given. In particular, Schmudgen's solution of the K-moment problem for compact K is extended, for dim (K)=1, to the case when K is virtually compact.