We introduce a model of the optimal education policy at the macro level, allowing for heterogeneity of the workforce with respect to its age and qualification skills. Within this framework we study the optimal education rate in the context of changes in labor demand (as represented by the elasticity of substitution across ages and qualification) and labor supply (as represented by a change in the population growth rates). Applying an age-structured optimal-control model, we derive features of the optimal age-specific education rate. Our results show that the relation between the elasticities of substitution of labor across ages plays a crucial role in the way the demographic changes affect (both in the short and in the long run) the optimal educational policy. We also show that under imperfect substitutability across age and qualification groups, the optimal educational policy is adjusted in advance to any change in the labor supply.