TLDR: Match the socket and chipset for compatibility and you should be fine. Most motherboards/chipsets have these listed.
Ideally you want to find a QVL/supported processor list and find a processor on that.
Most full sized, and many SFF desktops do still come with socketed chips, outside the extreme low end.
AMD tends to have suprisingly long backward compatibility with sockets (though sometimes you need to do a firmware update first). Intel changes sockets every few generations - and I feel like is a better 'general' example of what might catch a new user.
In general upgrading within the same 'generation' of processor, but a different model is fine. I'm going to focus more on intel, but many of these things are common to intel, AMD or other processors.
So what to watch out for -
Is it the correct socket? You can't fit an AMD socket AM4 into an AM5. Likewise, You can't fit a modern intel into an AMD motherboard and vice versa.
There may also be sockets with the same pin count but slight differences (like the HEDT/Server LGA 2011 versions)
There may not be out of the box support or support at all for a specific generation of chip. My "Coffee Lake"/9th generation intel processor wouldn't work on a board for 8th or 7th generation intel processors, and the older chips wouldn't work on my motherboard despite being the same socket.
AMD had better backward support but you sometimes needed a bios flash to support a newer GPU. With the correct socket, and firmware you could run a newer chip but those firmware versions would drop support for older chips. This was especially true with the socket AM4
A good/safe option would be to look up processor support for the chipset or motherboard, and updating the bios before swapping.