It happens when you build SQL by concatenating strings. The defense is parameterized queries ($1): the values travel separately from the SQL text, so they can never be read as SQL.