The Judgement of the Sheep and the Goats

Before the Lord Jesus Christ will establish the Messianic kingdom on earth in terms of the Davidic covenant, He will first preside over a judgement. Why is a judgement necessary? When will this take place? Who will be judged? And what will be the basis of this...