Mahakaleshwar temple is situated at Ujjain, Madhya Pradesh. As per the Puranas, Ujjain was known as Avantikapuri. Maha means big and kaal means time.
There lived a Brahmin in Avantikapuri who was a great devotee of Lord Shiva. He had four sons Devpriya, Medhapriya, Sukrit and Dharmabahu. After the death of the Brahmin the four sons continued to worship Lord Shiva.
There was a mountain called Ratanak, near Avantikapuri where lived a demon known as Dushan. With the boons received from Lord Brahma, he was able to conquer everything in Avantikapuri except the house of the Brahmin. Dushan ordered his fellowmen to go and conquer the house of the Brahmin. The demons went and told Dushan’s order to the Brahmins but as they were busy worshipping Lord Shiva, it fell on deaf ears. The demons then attacked them.
Suddenly the earth cracked open and Lord Shiva appeared in form of Mahakaal. He killed all the demons and then went to Ratanak mountain and killed demon Dushan.He then came back to Avantikapuri and asked the Brahmins for a boon. They expressed their desire to be free from the bondages of the world and also requested him to stay there forever. Lord Shiva accepted their desire and established himself as Mahakaal.