"Sings a different [song] every year. It's got to be a pretty boring life, hasn't it, being a hat? I suppose it spends all year making up the next one."
-- Ron Weasley
Originally the pointed wizard’s hat of Godric Gryffindor, the Sorting Hat was bewitched by all four of the Founders of Hogwarts with brains and some amount of personality. Its function is to determine which of the four Houses each new student will enter. It does so at the beginning of the start-of-term feast, when it is placed on a three-legged (sometimes four-legged) stool in front of the Great Hall. It then sings a long, rambling song of introduction, a different one each year but with the same basic information in it: how it was bewitched to perform the sorting and what the criteria are for the various houses. The first year students one by one place the Sorting Hat on their heads. Within a minute, it loudly proclaims the house for which they are best suited.
The hat is battered and old; it’s patched, frayed, and extremely dirty. In order to speak and sing, a tear along the brim opens like a mouth. It speaks inside of the hat with a small, quiet voice to the wearer and it can read thoughts and respond to them. When not sorting students, the Sorting Hat rests on its stool in Dumbledore’s office.
According to Nearly-Headless Nick, who’s been around a long time as the Gryffindor House ghost, the Sorting Hat feels itself honor-bound to give due warning when it detects great danger for the school. Nick says he’s heard it happen several times before, and that the advice is always the same: “Stand together, be strong from within” (OP11).
Uses Legilimency to read the minds of students and place them in what it considers to be the correct House (Pm).
The Sorting Hat is one of those slightly unnerving sentient objects in the Harry Potter universe which reveals a person's innermost feelings or thoughts. Fans find these objects fascinating because not only because we want to know our favorite characters better ("What would Snape see in the Mirror?") but also because we want to know how we ourselves would fit into the magical world. So we want to be Sorted, we want to know what wand would choose us, what our Patronus would be, and so on.
From the Web
Can We Trust the Sorting Hat? by Allie
Is Sorting Students a Flawed System? by Abbii
Sorting Hat as Founders' Relic by lunar_music