The Hantzsch pyridine synthesis, or we'd better say Hantzsch dihydropyridine synthesis (from the name of the chemist that first discovered it) is one of the best approach to get a substituted dihydropyridine and consequently a substituted pyridine. Notwithstanding the reaction mechanism is particularly complex and we're just proposing the more likely, this reaction represents a pioneering work in organic chemistry and in addition, the overall yield is very good.
Starting from β - ketoester ( there's a whole wide family of reaction producing β - ketoester or 1,3 dicarbonyl compouds some of them shown in → carbanion chemistry), and an aldehyde (even formaldehyde works well) and ammonia, without particular reaction conditions, we can easily obtain the desired dihydropyridine (dihydro because it has two more hydrogen than pyridine, and therefore has to be oxidized).
Mixing reagents in ethanol or water gives, as if by magic, the product. The all process is driven by thermodynamics and in paricular by the strong tendency to aromatize.
As we anticipated, the reaction mechanism is not exactly defined, but studying the reaction intermediates allows to suggest the most plausible. Let's have a step by step look.
The enolate (or enol) of the β-ketoester attacks the aldehyde. Why? Because the aldehyde is more electrophilic than, eventually, another molecule of ester, and therefore more reactive. After all, is also easier to have the enolate formed on the β-ketoester (rather that on the aldehyde), considering that it corresponds to a conjugated system. As you may have noticed the addition product is an highly conjugated system and also a Michael acceptor.
Right because the product is a Michael acceptor, it can react as an electrophile towards another molecule of enolate (nucleophile). This intermediate, coming from the condensation of the two fragments, is a 1,5 dicarbonyl compound and it resembles the final product.
N.B. that's why Hantzsch synthesis is that important. If we did the same reaction producing and purifying individually the intermediates, it would be difficult, expensive and probably unsuccesful. In this reaction all the reagents are synthesized in situ.
The last step consists in the nucleophilic attack of ammonia to one of the two aldehyde groups. The intermediate is an imine/enamine that quickly cyclises (essentially another nucleophilic attack to the still "free" aldehyde group) to give 1,4 dihydropyridine, who differs from pyridine just because of two more hydrogen atoms. Simply treating the dihydropyridine with an oxidizing agent (ox means a generic oxidizing agent) such as HNO3, ferric chloride, manganese dioxide, Ce(IV), DDQ etc.
In the end, if I needed a non-substituted pyridine I could easily decarboxylate the product.