Disclaimer: I'm not a lawyer, nor do I play one on TV. If you want legal advice, consult a professional.
Your mileage may vary, depending on the country and state you are in. In the US, the merchant generally has no right to stop you unless they suspect you of theft.
However, they don't have the right to search you (including your most recent purchase), unless security is a sworn police officer, and he/she has an suspicion you have committed a crime. It can't just be a "you look shady" suspicion: he/she has to have some evidence, observation, or witness to a crime.
Costco is an exception, because you must sign a membership agreement to make a purchase there. Buried in the membership agreement is a clause in which you agree to a bag search when exiting.
A merchant MAY also be able to do a bag search f they post a big sign at the entrance that says you are subject to a bag search on exit, and that you agree to it by entering the premises. But, I'm not sure that's ever been tested in court.