The story of the rise of the lunatic asylum and its gradual transformation into, and eventual replacement by, the modern psychiatric hospital also the story of the rise of organised, institutional psychiatry. While there were earlier institutions that housed the 'insane' the arrival at the answer of institutionalisation as the correct solution to the problem of madness was very much an event of the nineteenth century. To illustrate this with one regional example, in England at the beginning of the nineteenth century there were, perhaps, a few thousand 'lunatics' housed in a variety of disparate institutions but by 1900 that figure had grown to about 100,000. That this growth should coincide with the growth of alienism, later known as psychiatry, as a medical specialism is not coincidental.
Inspired by fact that the Qur'an decreed the necessity of providing humane treatment for the insane, the first specialist institutions for the care of the mad appeared in Islamic regions. These hospitals, called maristans, were well regarded with European travellers reporting back on their wonder at the care and kindness shown to lunatics. The first such documented hospital for the insane was built in Cairo by Ahmad ibn Tulun in 872. Nonetheless, Roy Porter cautions against idealising the role of hospitals generally in medieval Islam stating that: "They were a drop in the ocean for the vast population that they had to serve, and their true function lay in highlighting ideals of compassion and bringing together the activities of the medical profession."
In Europe during the medieval era a variety of settings were employed to house the small subsection of the population of the mad who were housed in a institutional setting. Porter gives examples of such locales where some of the insane were cared for such as in monasteries and a few towns had towers where madmen were kept (called Narrentürme or fools' tower) The ancient Parisian hospital Hôtel-Dieu also had a small amount of cells set aside for lunatics, whilst the town of Elbing boasted a madhouse Tollhaus attached to the Teutonic Knight's hospital. However, the first hospital in Europe dedicated to the care of the insane was founded under the aegis of Islam in Spain in Granada in 1365. Other such institutions for the insane followed in the latter period of Islamic rule there, including hospitals in Valencia (1407), Zaragoza (1425), Seville (1436), Barcelona (1481) and Toledo (1483). The Priory of Saint Mary of Bethlehem, which would become later become known more notoriously as Bedlam, was founded in 1247. At the start of the fifteenth century it housed just six insane men. 
In the United States, Virginia is recognized as the first state to establish an institution for the mentally ill. Eastern State Hospital, located in Williamsburg, was founded in 1773. Their land was given to them by the House of Burgesses in 1769.
Phillipe Pinel (1793) is often credited as being the first in Europe to introduce more humane methods into the treatment of the mentally ill (which came to be known as moral treatment) as the superintendent of the Asylum de Bicêtre in Paris. A hospital employee of Asylum de Bicêtre, Jean-Baptiste Pussin, was actually the first one to remove patient restraints. Pussin influenced Pinel and they both served to spread reforms such as categorising the disorders, as well as observing and talking to patients as methods of cure. Vincenzo Chiarugi in Italy may have banned chains before this time. Johann Jakob Guggenbühl in 1840 started in Interlaken the first retreat for mentally disabled children.
Around the same time as Pussin and Pinel, the Quakers, particularly William Tuke, pioneered an enlightened approach (moral treatment) in England at the York Retreat which opened in 1796. The Retreat was not a psychiatric hospital, and in fact the medical approaches of the day were abandoned in favor of understanding, hope, moral responsibility and occupational therapy.The Brattleboro Retreat and the former Hartford Retreat were named after it.
In 1817, William Ellis was appointed as superintendent to the newly built West Riding Pauper Asylum at Wakefield. As a Methodist, he had strong religious convictions. With his wife as matron, they put into action those things they had learned from the Sculcoates Refuge in Hull which operated on a similar model as the York. After 13 years, as a result of their highly regarded reputation, they were invited to oversee the newly built first pauper asylum in Middlesex called the Hanwell Asylum. Accepting the posts, the asylum opened in May 1831. Here the Ellis's introduced their own brand of humane treatment and 'moral therapy' combined with 'therapeutic employment.' As its initial capacity was for 450 patients, it was already the largest asylum in the country and subject to even more building soon after. Therefore, the immediate and continuing success of humane therapy working on such a large scale, encouraged its adoption at other asylums. In recognition of all this work he received a knighthood. He continued to develop therapeutic treatments for mental disorders and always with moral treatment as the guiding principle.
In Lincoln, Lincolnshire, England, Robert Gardiner Hill with the support of Edward Parker Charlesworth, developed a mode of treatment that suited 'all types' of patients, where by the reliance on mechanical restraints and coercion could be made obsolete altogether, a situation he finally achieved in 1838.
By the following year of 1839 Sergeant John Adams and Dr. John Conolly was so impressed by the work of Hill, that they immediately introduced the method into their Hanwell Asylum, which was by then the largest in the kingdom. The greater size required Hill's system to be developed and refined. This was necessary as it was beyond Conolly to be able to supervise each attendant as closely as Hill had done. Even so, he bid a pair of extra soft slippers made so that he could walk around the building at night without his foot falls warning the attendance of his imminent approach. By September 1839, mechanical restraint was no longer required for any patient. For years, this day was remembered at the Hanwell asylum by a celebration on its anniversary. Conolly also was a very accomplished communicator who wrote and lectured widely about his work in mental health.  
By compiling written records of such things as what the patients were given to eat, what exercise they were given, daily activities undergone and recreational opportunities; together with observations detailing what effect any changes to these practices had, different research doctors could compare each others' results and by copying parts of another hospital’s regime they could by a process of elimination, ascertain what interventions made real improvements in recovery. Using such means these and others, more effective treatment methods gradually took hold in different countries, and attitudes toward the treatment of the mentally ill began to drastically improve during the mid-19th century. Courts began to administer involuntary commitments with a greater eye towards medical justification.
Reformers, such as American Dorothea Dix began to advocate a more humane and progressive attitude towards the mentally ill. Some were motivated by a Christian Duty to mentally ill citizens. In the United States, for example, numerous states established state mental health systems paid for by taxpayer money (and often money from the relatives of those institutionalized inside them). These centralized institutions were often linked with loose governmental bodies, though oversight and quality consequently varied. They were generally geographically isolated as well, located away from urban areas because the land was cheap and there was less political opposition. Many state hospitals in the United States were built in the 1850s and 1860s on the Kirkbride Plan, an architectural style meant to have curative effect. States made large outlays on architecture that often resembled the palaces of Europe, although operating funding for ongoing programs was more scarce. Many patients objected to transfers from private hospitals to state facilities. Some Brattleboro Retreat patients tried to hide when state officials arrived to transfer them to the new Waterbury State Hospital. This decline in patient census led to the collapse of many private institutions, which still accepted indigent patients even when state reimbursement for private hospitals dropped in the face of rising state hospital costs.
A series of radical physical therapies were developed in central and continental Europe in the late 1910s, the 1920s and, most particularly, the 1930s. Among these we may note the Austrian psychiatrist Julius Wagner-Jauregg's groundbreaking malarial therapy for general paralysis of the insane (or neurosyphilis) first used in 1917, and for which he won a Nobel Prize in 1927. This treatment heralded the beginning of a radical and experimental era in psychiatric medicine that increasingly broke with an asylum based culture of therapeutic nihilism in the treatment of chronic psychiatric disorders, most particularly dementia praecox (increasingly known as schizophrenia from the 1910s, although the two terms were used more or less interchangeably until at least the end of the 1930s), which were typically regarded as hereditary degenerative disorders and therefore unamenable to any therapeutic intervention. Malarial therapy was followed in 1920 by barbituate induced deep sleep therapy to treat dementia praecox, which was popularized by the Swiss psychiatrist Jacob Klaesi. In 1933 the Viennese based psychiatrist Manfred Sakel introduced insulin shock therapy and in August 1934 Ladislas J. Meduna, a Jewish Hungarian neuropathologist and psychiatrist working in Budapest, introduced cardiazol shock therapy (cardiazol is the tradename of the chemical compound pentylenetetrazol, known by the tradename metrazol in the United States), which was the first convulsive or seizure therapy for a psychiatric disorder. Again, both of these therapies were initially targetted at curing dementia praecox. Cardiazol shock therapy, founded on the theoretical notion that there existed a biological antagonism between schizophrenia and epilepsy and that therefore inducing epiletiform fits in schizophrenic patients might effect a cure, was superseded by electroconvulsive therapy, invented by the Italian neurologist Ugo Cerletti in 1938. In 1935 the Portuguese neurologist Egas Moniz devised the leucotomy, a surgical procedure targetting the brain's frontal lobes. This was shortly thereafter adapted by Walter Freeman and James W. Watts in what is known as Freeman-Watts procedure or the standard prefrontal lobotomy. From 1946, Freeman developed the transorbital lobotomy, using a device akin to an ice-pick. This was an "office" procedure which did not have to be performed in a surgical theatre and took as little as fifteen minutes to complete. Freeman is credited with the popularisation of the technique in the United States. In 1949, 5074 lobotomies were carried out in the United States and by 1951 18,608 people had undergone the controversial procedure in that country.
In modern times, insulin shock therapy and lobotomies are viewed as being almost as barbaric as the Bedlam "treatments", although the insulin shock therapy was still seen as the first options which produced any noticeable effect on their patients. ECT is still used in the West, but it is seen as a last resort for treatment of mood disorders, and is administered much more safely than in the past. Elsewhere, particularly in India, use of ECT is reportedly increasing, as a cost-effective alternative to drug treatment. The effect of a shock on an overly excitable patient often allowed these patients to be discharged to their homes, which was seen by administrators (and often guardians) as a preferable solution to institutionalization. Lobotomies were performed in the hundreds from the 1930s to the 1950s, and were ultimately replaced with modern psychotropic drugs.
The eugenics movement of the early 20th century led to a number of countries enacting laws for the compulsory sterilization of the "feeble minded", which resulted in the forced sterilization of numerous psychiatric inmates. As late as the 1950s, laws in Japan allowed the forcible sterilization of patients with psychiatric illnesses.
The twentieth century saw the development of the first effective psychiatric drugs.
The first antipsychotic drug, chlorpromazine (known under the trade name Largactil in Europe and Thorazine in the United States), was first synthesised in France in 1950. Pierre Deniker, a psychiatrist of the Saint-Anne Psychiatric Centre in Paris, is credited with first recognising the specificity of action of the drug in psychosis in 1952. Deniker travelled with a colleague to the United States and Canada promoting the drug at medical conferences in 1954. The first publication regarding its use in North America was made in the same year by the Canadian psychiatrist Heinz Lehmann, who was based in Montreal. Also in 1954 another antipsychotic, reserpine, was first used by an American psychiatrist based in New York, Nathan S. Kline. At a Paris based colloquium on neuroleptics (antipsychotics) in 1955 a series of psychiatric studies were presented by, among others, Hans Hoff (Vienna), Aksel (Istanbul), Felix Labarth (Basle), Linford Rees (London), Sarro (Barcelona), Manfred Bleuler (Zurich), William Mayer-Gross (Birmingham), Winford (Washington) and Denber (New York) attesting to the effective and concordant action of the new drugs in the treatment of psychosis.
The new antipsychotics had an immense impact on the lives of psychiatrists and patients. For instance, Henry Ey, a French psychiatrist at Bonneval, related that between 1921 and 1937 only 6 per cent of patients suffering from schizophrenia and chronic delirium were discharged from his institution. The comparable figure for the period from 1955 to 1967, after the introduction of chlorpromazine, was 67 per cent. Between 1955 and 1968 the residential psychiatric population in the United States dropped by 30 per cent. Newly developed antidepressants were used to treat cases of depression, and the introduction of muscle relaxants allowed ECT to be used in a modified form for the treatment of severe depression and a few other disorders.
The discovery of the mood stabilizing effect of lithium carbonate by John Cade in 1948 would eventually revolutionize the treatment of bipolar disorder, although its use was banned in the United States until the 1970s.
The use of psychosurgery was narrowed to a very small number of people for specific indications. New treatments led to reductions in the number of patients in mental hospitals.
From 1942 to 1947, conscientious objectors in the US assigned to psychiatric hospitals under Civilian Public Service exposed abuses throughout the psychiatric care system and were instrumental in reforms of the 1940s and 1950s. The CPS reformers were especially active at the Philadelphia State Hospital where four Quakers initiated The Attendant magazine as a way to communicate ideas and promote reform. This periodical later became the The Psychiatric Aide, a professional journal for mental health workers. On May 6, 1946, Life magazine printed an exposé of the psychiatric system based on the reports of COs. Another effort of CPS, namely the Mental Hygiene Project, became the National Mental Health Foundation. Initially skeptical about the value of Civilian Public Service, Eleanor Roosevelt, impressed by the changes introduced by COs in the mental health system, became a sponsor of the National Mental Health Foundation and actively inspired other prominent citizens including Owen J. Roberts, Pearl Buck and Harry Emerson Fosdick to join her in advancing the organization's objectives of reform and humane treatment of patients.
In some nations, such as North Korea, the former Soviet Union, East Germany, and Romania during Communist rule, mental hospitals were, and in some cases still are, used as sites for the stifling of political dissent or even genocide.
By the beginning of the 20th century, ever-increasing admissions had resulted in serious overcrowding. Funding was often cut, especially during periods of economic decline, and during wartime in particular many patients starved to death. Asylums became notorious for poor living conditions, lack of hygiene, overcrowding, and ill-treatment and abuse of patients.
The first community-based alternatives were suggested and tentatively implemented in the 1920s and 1930s, although asylum numbers continued to increase up to the 1950s. The movement for deinstitutionalization came to the fore in various countries in the 1950s and 1960s.
The prevailing public arguments, time of onset, and pace of reforms varied by country. Class action lawsuits in the United States, and the scrutiny of institutions through disability activism and antipsychiatry, helped expose the poor conditions and treatment. Sociologists and others argued that such institutions maintained or created dependency, passivity, exclusion and disability, causing people to be institutionalized.
There was an argument that community services would be cheaper. It was suggested that new psychiatric medications made it more feasible to release people into the community.
There were differing views on deinstitutionalization, however, in groups such as mental health professionals, public officials, families, advocacy groups, public citizens, and unions.
In Japan, the number of hospital beds has risen steadily over the last few decades.
In Hong Kong, a number of residential care services such as half-way houses, long-stay care homes, supported hostels are provided for the discharged patients. In addition, a number of community support services such as Community Rehabilitation Day Services, Community Mental Health Link, Community Mental Health Care, etc. have been launched to facilitate the patients to re-integrate into the community.
New Zealand established a reconciliation initiative in 2005 in the context of ongoing compensation payouts to ex-patients of state-run mental institutions in the 1970s to 1990s. The forum heard of poor reasons for admissions; unsanitary and overcrowded conditions; lack of communication to patients and family members; physical violence and sexual misconduct and abuse; inadequate complaints mechanisms; pressures and difficulties for staff, within an authoritarian psychiatric hierarchy based on containment; fear and humiliation in the misuse of seclusion; over-use and abuse of ECT, psychiatric medication and other treatments/punishments, including group therapy, with continued adverse effects; lack of support on discharge; interrupted lives and lost potential; and continued stigma, prejudice and emotional distress and trauma.
There were some references to instances of helpful aspects or kindnesses despite the system. Participants were offered counseling to help them deal with their experiences, and advice on their rights, including access to records and legal redress.
Countries where deinstitutionalization has happened may be experiencing a process of "re-institutionalization" or relocation to different institutions, as evidenced by increases in the number of supported housing facilities, forensic psychiatric beds and rising numbers in the prison population.
Some developing European countries still rely on asylums.
The United States has experienced 2 waves of deinstitutionalization. Wave 1 began in the 1950s and targeted people with mental illness. The second wave began roughly 15 years after and focused on individuals who had been diagnosed with a developmental disability (e.g. mental retardation).  Although these waves began over 50 years ago, deinstitutionalization continues today; however, these waves are growing smaller as fewer people are sent to institutions.
A process of indirect cost-shifting may have led to a form of "re-institutionalization" through the increased use of jail detention for those with mental disorders deemed unmanageable and noncompliant. In Summer 2009, author and columnist Heather Mac Donald stated in City Journal, "jails have become society’s primary mental institutions, though few have the funding or expertise to carry out that role properly... at Rikers, 28 percent of the inmates require mental health services, a number that rises each year."
In several South American countries, the total number of beds in asylum-type institutions has decreased, replaced by psychiatric inpatient units in general hospitals and other local settings.