Alias (SQL)

An alias is a feature of SQL that is supported by most, if not all, relational database management systems (RDBMSs). Aliases provide users with the ability to reduce the amount of code required for a query, and to make queries simpler to understand. In addition, aliasing is required when doing self joins (i.e. joining a table with itself.)

In SQL, you can alias tables and columns. A table alias is called a correlation name, according to the SQL standard.[1] A programmer can use an alias to temporarily assign another name to a table or column for the duration of the current SELECT query. Assigning an alias does not actually rename the column or table. This is often useful when either tables or their columns have very long or complex names. An alias name could be anything, but usually it is kept short. For example, it might be common to use a table alias such as "pi" for a table named "price_information".

The general syntax of an alias is SELECT * FROM table_name [AS] alias_name. Note that the AS keyword is completely optional and is usually kept for readability purposes. Here is some sample data that the queries below will be referencing:

Department Table
DepartmentID DepartmentName
31 Sales
33 Engineering
34 Clerical
35 Marketing

Using a table alias:

 SELECT D.DepartmentName FROM Department AS D

We can also write the same query like this (Note that the AS clause is omitted this time):

 SELECT D.DepartmentName FROM Department D

A column alias is similar:

 SELECT d.DepartmentId AS Id, d.DepartmentName AS Name FROM Department d

In the returned result sets, the data shown above would be returned, with the only exception being "DepartmentID" would show up as "Id", and "DepartmentName" would show up as "Name".

Also, if only one table is being selected and the query is not using table joins, it is permissible to omit the table name or table alias from the column name in the SELECT statement. Example as follows:

 SELECT DepartmentId AS Id, DepartmentName AS Name FROM Department d

Some systems, such as Postgres[2] and Presto,[3] support specifying column aliases together with table aliases. E.g.

 SELECT D.Id FROM Department AS D(Id)

would produce the same result set as before. In this syntax it is permissible to omit aliases for some column names. In the example, an alias was provided for DepartmentId, but omitted for DepartmentName. Columns with unspecified aliases will be left unaliased. This syntax is often used with expressions that do not produce useful table and column names, such as VALUES[4] and UNNEST.[5] As an example, one may conveniently test the above SQL statements without creating an actual Departments table by using expressions such as

WITH Department(DepartmentId, DepartmentName) AS (VALUES (1, 'HR'), (2, 'IT'))
SELECT DepartmentId AS Id, DepartmentName AS Name FROM Department d;

References

  1. ^ ANSI Standard SQL – Foundation Document – Date: 2010-10-14
  2. ^ PostgreSQL: Documentation: 13: 7.2. Table Expressions
  3. ^ https://prestodb.io/docs/0.248/sql/select.html SELECT — Presto 0.248 Documentation
  4. ^ https://prestodb.io/docs/0.248/sql/values.html#examples VALUES — Presto 0.248 Documentation
  5. ^ https://prestodb.io/docs/0.248/sql/select.html#unnest SELECT — Presto 0.248 Documentation

Read other articles:

Rami Klasifikasi ilmiah Domain: Eukaryota Kerajaan: Plantae Divisi: Magnoliophyta Kelas: Magnoliopsida Ordo: Rosales Famili: Urticaceae Genus: Boehmeria Spesies: Boehmeria nivea(L.) Gaudich. Rami (diucapkan: /ˈreɪmi/, RAY-mee; dari bahasa Melayu yakni rami) atau dengan nama latin Boehmeria nivea adalah spesies tumbuhan berbunga dalam keluarga jelatang (Urticaceae) yang berasal dari Asia Timur. Rami nerupakan tanaman herba menahun yang tumbuh hingga setinggi 1,0–2,5 meter,[1] daun...

 

Ancient Egyptian goddess of childbirth Part of a series onAncient Egyptian religion Beliefs Afterlife Cosmology Duat Ma'at Mythology Numerology Philosophy Soul Practices Funerals Offerings: Offering formula Temples Priestess of Hathor Pyramids Deities (list)Ogdoad Amun Amunet Hauhet Heh Kauket Kek Naunet Nu Ennead Atum Geb Isis Nephthys Nut Osiris Set Shu Tefnut A Aati Aker Akhty Amenhotep, son of Hapu Amesemi Ammit Am-heh Amu-Aa Anat Andjety Anhur Anput Anubis Anuket Apedemak Apep Apis Apt A...

 

Santa Cruz Provincia de Santa CruzProvinsiProvinsi Santa CruzPemandangan Gunung Fitz Roy BenderaLambang kebesaranLokasi Santa Cruz di ArgentinaKoordinat: 48°37′S 70°01′W / 48.62°S 70.01°W / -48.62; -70.01Koordinat: 48°37′S 70°01′W / 48.62°S 70.01°W / -48.62; -70.01NegaraArgentinaDepartment7Municipality27Ibu kotaRío GallegosPemerintahan • GubernurClaudio Vidal (SER) • Wakil GubernurFabián Leguizamón (PJ)...

Artikel ini membutuhkan rujukan tambahan agar kualitasnya dapat dipastikan. Mohon bantu kami mengembangkan artikel ini dengan cara menambahkan rujukan ke sumber tepercaya. Pernyataan tak bersumber bisa saja dipertentangkan dan dihapus.Cari sumber: Tumbuhan lumut – berita · surat kabar · buku · cendekiawan · JSTOR (Januari 2021) Untuk halaman disambiguasi, lihat Lumut. Tumbuhan lumut Bryophytes TaksonomiSuperdomainBiotaSuperkerajaanEukaryotaKerajaanPlan...

 

Portovenere, Cinque Terre, dan Pulau-Pulaunya (Palmaria, Tino dan Tinetto)Situs Warisan Dunia UNESCOKriteriaBudaya: ii, iv, vNomor identifikasi826Pengukuhan1997 (21st)Koordinat44°7′10″N 9°43′00″E / 44.11944°N 9.71667°E / 44.11944; 9.71667Koordinat: 44°7′10″N 9°43′00″E / 44.11944°N 9.71667°E / 44.11944; 9.71667Letak di Italia Cinque Terre (pengucapan bahasa Italia: [ˈtʃiŋkwe ˈtɛrre]; bahasa Liguria: Çin...

 

Stadio Algarve Informazioni generaliStato Portogallo UbicazioneFaro Inizio lavori2002 Inaugurazione2003 Costo34,6 mil. euro ProprietarioFaro ProgettoHOK S+V+E Informazioni tecnichePosti a sedere30305 CoperturaTribuna centrale e distinti Mat. del terrenoErba Dim. del terreno107 × 72 m Uso e beneficiariCalcio Farense (2003-) Louletano (2003-) Gibilterra (2013-19)[1] Gibilterra Under-21 (2017-)[1] Mappa di localizzazione Modifica dati su Wikidata · ...

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: PowerBook 160 – news · newspapers · books · scholar · JSTOR (April 2023) (Learn how and when to remove this template message) Laptop by Apple PowerBook 160Product familyPowerBook 100 seriesRelease dateOctober 19, 1992 (1992-10-19)Introductory pri...

 

King of Cappadocia Ariobarzanes ICoin of Ariobarzanes, minted at Mazaca in 83/82 BCKing of CappadociaReign95–63/62 BCPredecessorAriarathes VIII (Ariarathid dynasty)SuccessorAriobarzanes IISpouseAthenais Philostorgos IIssueAriobarzanes II Ariobarzanes I (Ancient Greek: Ἀριοβαρζάνης), surnamed Philoromaios (Ancient Greek: Φιλορωμαίος, romanized: Philorōmaíos, Friend to the Romans), was the first Ariobarzanid king of Cappadocia from 95 BC to 63/62 BC. Ariobarzane...

 

Pour les articles homonymes, voir Netta (homonymie). Netta BarzilaiNetta Barzilai en 2018.BiographieNaissance 22 janvier 1993 (31 ans)Hod Hasharon, Israël Nom de naissance נטע ברזיליPseudonyme נטעNationalité israélienneDomicile Tel AvivActivités Musicienne, chanteuse, compositrice, disc jockey, auteure-compositrice-interprète, auteure-compositricePériode d'activité depuis 2012Autres informationsInstrument Guitare, piano, looperLabel Tedy Productions (d)Genre artistiqu...

Запрос «Пугачёва» перенаправляется сюда; см. также другие значения. Алла Пугачёва На фестивале «Славянский базар в Витебске», 2016 год Основная информация Полное имя Алла Борисовна Пугачёва Дата рождения 15 апреля 1949(1949-04-15) (75 лет) Место рождения Москва, СССР[1]...

 

Indonesian savoury cracker RempeyekPeanut rempeyekAlternative namesPeyekTypeCrackerPlace of originIndonesia[1]Region or stateJava and Nationwide in Indonesia, Malaysia[2]Main ingredientsRice flour, peanuts, dried anchovies or shrimp, coconut milkVariationsPeyek bayam  Media: Rempeyek Rempeyek or peyek is a deep-fried savoury Indonesian-Javanese cracker[1][3] made from flour (usually rice flour) with other ingredients, bound or coated by crispy flour ba...

 

2020年夏季奥林匹克运动会波兰代表團波兰国旗IOC編碼POLNOC波蘭奧林匹克委員會網站olimpijski.pl(英文)(波兰文)2020年夏季奥林匹克运动会(東京)2021年7月23日至8月8日(受2019冠状病毒病疫情影响推迟,但仍保留原定名称)運動員206參賽項目24个大项旗手开幕式:帕维尔·科热尼奥夫斯基(游泳)和马娅·沃什乔夫斯卡(自行车)[1]闭幕式:卡罗利娜·纳亚(皮划艇)&#...

2016 Indian filmFamily KattaMarathiफॅमिली कट्टा Directed byChandrakant KulkarniScreenplay byPrashant DalviStory byPrashant DalviProduced byVandana GupteStarringDilip Prabhavalkar Vandana GupteAlok RajwadeGauri NalawadeKiran KarmarkarPrateeksha LonkarSachin DeshpandeSulekha TalwalkarSanjay KhapreSai TamhankarAadesh ShrivastavaCinematographyMahesh LimayeEdited byJayant JatharMusic byMangesh DhakadeProductioncompanySister Concern EntertainmentRelease date 7 October...

 

Dominican baseball player (born 1960) This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Cecilio Guante – news · newspapers · books · scholar · JSTOR (June 2010) (Learn how and when to remove this ...

 

1987 Chicago television hijacking incident Max Headroom signal hijackingThe unidentified hijacker dressed to resemble Max Headroom in the pirate broadcastDateNovember 22, 1987; 36 years ago (1987-11-22)LocationChicago, Illinois, U.S.TargetWGN-TVWTTWParticipantsAt least 3 (unidentified) On the night of November 22, 1987, the television signals of two stations in Chicago, Illinois, were hijacked, briefly sending a pirate broadcast of an unidentified person wearing a Max Headro...

Species of marine reptile distributed throughout the world Loggerhead turtle redirects here. For other uses, see Loggerhead turtle (disambiguation). Caretta redirects here. For the community in West Virginia, see Caretta, West Virginia. Loggerhead sea turtleTemporal range: 40–0 Ma PreꞒ Ꞓ O S D C P T J K Pg N Eocene - Recent[1] Conservation status Vulnerable  (IUCN 3.1)[2] CITES Appendix I (CITES)[3] Scientific classification Domain: Eukaryota Kingd...

 

American politician Don RehfeldtRehfeldt circa 1950Personal informationBorn(1927-01-07)January 7, 1927Chicago, IllinoisDiedOctober 16, 1980(1980-10-16) (aged 53)Wisconsin Rapids, WisconsinNationalityAmericanListed height6 ft 7 in (2.01 m)Listed weight210 lb (95 kg)Career informationHigh schoolAmundsen (Chicago, Illinois)CollegeWisconsin (1944–1945, 1946–1950)NBA draft1950: 1st round, 2nd overall pickSelected by the Baltimore BulletsPlaying career1950–1952Po...

 

Visigoth siege and looting of Rome For other uses, see Sack of Rome. Sack of Rome (410)Part of the fall of the Western Roman EmpireThe Sack of Rome in 410 by the Barbarians by Joseph-Noël Sylvestre, 1890Date24 August 410 ADLocationRomeResult Visigothic victoryBelligerents Visigoths Western Roman EmpireHuns[a]Commanders and leaders Alaric IAthaulf HonoriusStrength Possibly 40,000 soldiers[6]Unknown number of civilian followers UnknownCasualties and losses Unknown Unknown vteFa...

State school in B Legwale Street, Moletsane, Kwa-Xuma, SowetoMoletsane High SchoolLocation1644 B Legwale Street, Moletsane, Kwa-Xuma, SowetoCoordinates26°15′16″S 27°51′02″E / 26.2545°S 27.8506°E / -26.2545; 27.8506InformationTypeState schoolEstablished1972PrincipalElliot Mashinini (2011)Enrolment1124[1]Colour(s)   blue and white Moletsane High School is a government secondary school in Soweto, South Africa. Founded in 1972 it became a sec...

 

2002 single by Ace of BaseUnspeakableSingle by Ace of Basefrom the album Da Capo B-sideDon't StopReleased2 December 2002GenrePopLength3:30LabelMegaSongwriter(s)Adam Anders Jonas Berggren M. Lindsten Nicklas Von Der BurgAce of Base singles chronology The Juvenile (2002) Unspeakable (2002) Wheel of Fortune 2009 (2008) Music videoUnspeakable on YouTube Unspeakable is a single from Ace of Base's 2002 album Da Capo. Chart performance The single peaked at number 3 in Israel, 14 in Finland, 45 in Sw...