If you’re an EU citizen, you already have the right to residency. You’ll probably find it useful, though, to apply for an NIE (see later).
If you’re a non-EU citizen and you want to stay in Spain for more than 30 days (90 days for some nationalities), you need a visa. If you want to live in Spain, the process is this: first get a visa from the Spanish Embassy or Consulate closest to your home. When you arrive in Spain, you work on getting residency. After you get that, you can begin work on getting citizenship.
Getting residency in Spain allows you to live anywhere in the EU; likewise, getting residency somewhere else in the EU gives you a right to residency in Spain. That means that if your goal is residency in Spain and you have relatives or ancestors in some other country in the EU, then the easiest way may be to first apply for residency in that other country.
NIE (Número de Identidad/Identificación de Extranjero). The immigration service issues this number to you once you obtain residency (you will find the number on your Resident Card). This is your identification number in Spain. It is needed in order to file taxes, establish a business, open a bank account (not necessary for foreign accounts) and for almost any other form you fill out. Both EU citizens and non-EU citizens get issued with an NIE.
NIF (Número de Identificación Fiscal). This is the tax ID number for all individuals. For foreigners, it’s the same number as your NIE. Once you have an NIE, you do not need to re-apply for an NIF; if and when you have to pay taxes, use your NIE number. If you’re a nonresident who has to pay taxes in Spain, you may get an NIF issued to you without having an NIE. This, of course, does not mean you get automatic residency in Spain, nor will it make it any easier to get residency.
CIF (Certificado de Identificación Fiscal). This is the the same as the NIF, but for companies.
Social Security Number. Your employer applies for this number when you start your first job in Spain. This number then stays with you for all subsequent jobs. If you are self-employed, you apply for this number yourself.