Itching, which doctors call pruritic, can have many causes, and the exact mechanism is still a matter of controversy.
Most researchers believe the common itch starts with the release of a substance called histamine, and possibly other chemicals, from special cells called mast cells in the skin.
The release can be triggered by allergies, contact dermatitis, eczema, dry skin, medication, sunburn, parasites like scabies and many other things, and some people simply have excitable mast cells.
The chemical is believed to initiate the pathway that stimulates a nerve, finding receptors so that a sensation is transmitted to the brain.
However, some researchers say that a different kind of nerve receptor is being stimulated, perhaps by physical rather than chemical means.
The process is similar to the pathway of pain, and appears to depend to some extent on the intensity of the stimulus. A small stimulus might be perceived as an itch and a greater one as pain.
For example, shingles, a disease that inflames nerve endings, can cause perceptions that range from a pain to an itch.
Other kinds of itching may arise from internal diseases, like liver disease, in which chemicals are not metabolized properly so that they build up; hyperthyroidism, or increased thyroid activity; and some kinds of cancers or tumors.
Scratching may work to relieve the itching sensation at least temporarily because it acts as a competing stimulus and tends to block out and suppress the itch.
That is probably why itchy rashes are worse when you are trying to relax or going to sleep at night, when other stimuli are decreased.