For most cases of what we would use PHP for, you have it right. However, instead of memorising specific instances, you need to understand the fundamental ideas: sanitise when the data may be interpreted.
In the case of an SQL statement, the data may be interpreted as SQL, so you need to ensure that such interpretation is not possible (unless intended, but you have to be very careful with that). In the case of printing to the browser, the data could be interpreted as clientside code, so it should be sanitised.
Using htmlspecialchars() on data used in an SQL query could make a mess out of the data when it is stored in the database. Using mysql_real_escape_string() on data to be sent to clientside could allow for XSS attacks. So, if you understand what is happening, you can also choose the appropriate mechanisms to sanitise the data.