A SELECT statement retrieves zero or more rows from one or more database tables or database views. In most applications, SELECT is the most commonly used data manipulation language (DML) command. As SQL is a declarative programming language, SELECT queries specify a result set, but do not specify how to calculate it. The database translates the query into a "query plan" which may vary between executions, database versions and database software. This functionality is called the "query optimizer" as it is responsible for finding the best possible execution plan for the query, within applicable constraints.
The SELECT statement has many optional clauses:
SELECT list is the list of columns or SQL expressions to be returned by the query. This is approximately the relational algebraprojection operation.
AS optionally provides an alias for each column or expression in the SELECT list. This is the relational algebra rename operation.
FROM specifies from which table to get the data.[3]
WHERE specifies which rows to retrieve. This is approximately the relational algebra selection operation.
HAVING selects among the groups defined by the GROUP BY clause.
ORDER BY specifies how to order the returned rows.
Overview
SELECT is the most common operation in SQL, called "the query". SELECT retrieves data from one or more tables, or expressions. Standard SELECT statements have no persistent effects on the database. Some non-standard implementations of SELECT can have persistent effects, such as the SELECT INTO syntax provided in some databases.[4]
Queries allow the user to describe desired data, leaving the database management system (DBMS) to carry out planning, optimizing, and performing the physical operations necessary to produce that result as it chooses.
A query includes a list of columns to include in the final result, normally immediately following the SELECT keyword. An asterisk ("*") can be used to specify that the query should return all columns of all the queried tables. SELECT is the most complex statement in SQL, with optional keywords and clauses that include:
The FROM clause, which indicates the tables to retrieve data from. The FROM clause can include optional JOIN subclauses to specify the rules for joining tables.
The WHERE clause includes a comparison predicate, which restricts the rows returned by the query. The WHERE clause eliminates all rows from the result set where the comparison predicate does not evaluate to True.
The GROUP BY clause projects rows having common values into a smaller set of rows. GROUP BY is often used in conjunction with SQL aggregation functions or to eliminate duplicate rows from a result set. The WHERE clause is applied before the GROUP BY clause.
The HAVING clause includes a predicate used to filter rows resulting from the GROUP BY clause. Because it acts on the results of the GROUP BY clause, aggregation functions can be used in the HAVING clause predicate.
The ORDER BY clause identifies which columns to use to sort the resulting data, and in which direction to sort them (ascending or descending). Without an ORDER BY clause, the order of rows returned by an SQL query is undefined.
The DISTINCT keyword[5] eliminates duplicate data.[6]
The following example of a SELECT query returns a list of expensive books. The query retrieves all rows from the Book table in which the price column contains a value greater than 100.00. The result is sorted in ascending order by title. The asterisk (*) in the select list indicates that all columns of the Book table should be included in the result set.
SELECT*FROMBookWHEREprice>100.00ORDERBYtitle;
The example below demonstrates a query of multiple tables, grouping, and aggregation, by returning a list of books and the number of authors associated with each book.
Title Authors
---------------------- -------
SQL Examples and Guide 4
The Joy of SQL 1
An Introduction to SQL 2
Pitfalls of SQL 1
Under the precondition that isbn is the only common column name of the two tables and that a column named title only exists in the Book table, one could re-write the query above in the following form:
However, many[quantify] vendors either do not support this approach, or require certain column-naming conventions for natural joins to work effectively.
SQL includes operators and functions for calculating values on stored values. SQL allows the use of expressions in the select list to project data, as in the following example, which returns a list of books that cost more than 100.00 with an additional sales_tax column containing a sales tax figure calculated at 6% of the price.
Queries can be nested so that the results of one query can be used in another query via a relational operator or aggregation function. A nested query is also known as a subquery. While joins and other table operations provide computationally superior (i.e. faster) alternatives in many cases (all depending on implementation), the use of subqueries introduces a hierarchy in execution that can be useful or necessary. In the following example, the aggregation function AVG receives as input the result of a subquery:
A subquery can use values from the outer query, in which case it is known as a correlated subquery.
Since 1999 the SQL standard allows WITH clauses, i.e. named subqueries often called common table expressions (named and designed after the IBM DB2 version 2 implementation; Oracle calls these subquery factoring). CTEs can also be recursive by referring to themselves; the resulting mechanism allows tree or graph traversals (when represented as relations), and more generally fixpoint computations.
Derived table
A derived table is a subquery in a FROM clause. Essentially, the derived table is a subquery that can be selected from or joined to. Derived table functionality allows the user to reference the subquery as a table. The derived table also is referred to as an inline view or a select in from list.
In the following example, the SQL statement involves a join from the initial Books table to the derived table "Sales". This derived table captures associated book sales information using the ISBN to join to the Books table. As a result, the derived table provides the result set with additional columns (the number of items sold and the company that sold the books):
Given a table T, the querySELECT*FROMT will result in all the elements of all the rows of the table being shown.
With the same table, the query SELECTC1FROMT will result in the elements from the column C1 of all the rows of the table being shown. This is similar to a projection in relational algebra, except that in the general case, the result may contain duplicate rows. This is also known as a Vertical Partition in some database terms, restricting query output to view only specified fields or columns.
With the same table, the query SELECT*FROMTWHEREC1=1 will result in all the elements of all the rows where the value of column C1 is '1' being shown – in relational algebra terms, a selection will be performed, because of the WHERE clause. This is also known as a Horizontal Partition, restricting rows output by a query according to specified conditions.
With more than one table, the result set will be every combination of rows. So if two tables are T1 and T2, SELECT*FROMT1,T2 will result in every combination of T1 rows with every T2 rows. E.g., if T1 has 3 rows and T2 has 5 rows, then 15 rows will result.
Although not in standard, most DBMS allows using a select clause without a table by pretending that an imaginary table with one row is used. This is mainly used to perform calculations where a table is not needed.
The SELECT clause specifies a list of properties (columns) by name, or the wildcard character (“*”) to mean “all properties”.
Limiting result rows
Often it is convenient to indicate a maximum number of rows that are returned. This can be used for testing or to prevent consuming excessive resources if the query returns more information than expected. The approach to do this often varies per vendor.
In ISOSQL:2003, result sets may be limited by using
According to PostgreSQL v.9 documentation, an SQL window function "performs a calculation across a set of table rows that are somehow related to the current row", in a way similar to aggregate functions.[7]
The name recalls signal processing window functions. A window function call always contains an OVER clause.
ROW_NUMBER() window function
ROW_NUMBER() OVER may be used for a simple table on the returned rows, e.g. to return no more than ten rows:
ROW_NUMBER can be non-deterministic: if sort_key is not unique, each time you run the query it is possible to get different row numbers assigned to any rows where sort_key is the same. When sort_key is unique, each row will always get a unique row number.
RANK() window function
The RANK() OVER window function acts like ROW_NUMBER, but may return more or less than n rows in case of tie conditions, e.g. to return the top-10 youngest persons:
The above code could return more than ten rows, e.g. if there are two people of the same age, it could return eleven rows.
FETCH FIRST clause
Since ISO SQL:2008 results limits can be specified as in the following example using the FETCH FIRST clause.
SELECT*FROMTFETCHFIRST10ROWSONLY
This clause currently is supported by CA DATACOM/DB 11, IBM DB2, SAP SQL Anywhere, PostgreSQL, EffiProz, H2, HSQLDB version 2.0, Oracle 12c and Mimer SQL.
Microsoft SQL Server 2008 and higher supports FETCH FIRST, but it is considered part of the ORDER BY clause. The ORDER BY, OFFSET, and FETCH FIRST clauses are all required for this usage.
Some DBMSs offer non-standard syntax either instead of or in addition to SQL standard syntax. Below, variants of the simple limit query for different DBMSes are listed:
SETROWCOUNT10SELECT*FROMT
MS SQL Server (This also works on Microsoft SQL Server 6.5 while the Select top 10 * from T does not)
IBM Db2 (new rows are filtered after comparing with key column of table T)
Rows Pagination
Rows Pagination[9] is an approach used to limit and display only a part of the total data of a query in the database. Instead of showing hundreds or thousands of rows at the same time, the server is requested only one page (a limited set of rows, per example only 10 rows), and the user starts navigating by requesting the next page, and then the next one, and so on. It is very useful, specially in web systems, where there is no dedicated connection between the client and the server, so the client does not have to wait to read and display all the rows of the server.
Data in Pagination approach
{rows} = Number of rows in a page
{page_number} = Number of the current page
{begin_base_0} = Number of the row - 1 where the page starts = (page_number-1) * rows
Simplest method (but very inefficient)
Select all rows from the database
Read all rows but send to display only when the row_number of the rows read is between {begin_base_0 + 1} and {begin_base_0 + rows}
Select*from{table}orderby{unique_key}
Other simple method (a little more efficient than read all rows)
Select all the rows from the beginning of the table to the last row to display ({begin_base_0 + rows})
Read the {begin_base_0 + rows} rows but send to display only when the row_number of the rows read is greater than {begin_base_0}
Method with filter (it is more sophisticated but necessary for very big dataset)
Select only then {rows} rows with filter:
First Page: select only the first {rows} rows, depending on the type of database
Next Page: select only the first {rows} rows, depending on the type of database, where the {unique_key} is greater than {last_val} (the value of the {unique_key} of the last row in the current page)
Previous Page: sort the data in the reverse order, select only the first {rows} rows, where the {unique_key} is less than {first_val} (the value of the {unique_key} of the first row in the current page), and sort the result in the correct order
Read and send to display all the rows read from the database
the FROM clause is evaluated, a cross join or Cartesian product is produced for the first two tables in the FROM clause resulting in a virtual table as Vtable1
the ON clause is evaluated for vtable1; only records which meet the join condition g.Userid = u.Userid are inserted into Vtable2
If an outer join is specified, records which were dropped from vTable2 are added into VTable 3, for instance if the above query were:
the SELECT list is evaluated and returned as Vtable 7
the DISTINCT clause is evaluated; duplicate rows are removed and returned as Vtable 8
the ORDER BY clause is evaluated, ordering the rows and returning VCursor9. This is a cursor and not a table because ANSI defines a cursor as an ordered set of rows (not relational).
Window function support by RDBMS vendors
The implementation of window function features by vendors of relational databases and SQL engines differs wildly. Most databases support at least some flavour of window functions. However, when we take a closer look it becomes clear that most vendors only implement a subset of the standard. Let's take the powerful RANGE clause as an example. Only Oracle, DB2, Spark/Hive, and Google Big Query fully implement this feature. More recently, vendors have added new extensions to the standard, e.g. array aggregation functions. These are particularly useful in the context of running SQL against a distributed file system (Hadoop, Spark, Google BigQuery) where we have weaker data co-locality guarantees than on a distributed relational database (MPP). Rather than evenly distributing the data across all nodes, SQL engines running queries against a distributed filesystem can achieve data co-locality guarantees by nesting data and thus avoiding potentially expensive joins involving heavy shuffling across the network. User-defined aggregate functions that can be used in window functions are another extremely powerful feature.
^Omitting FROM clause is not standard, but allowed by most major DBMSes.
^"Transact-SQL Reference". SQL Server Language Reference. SQL Server 2005 Books Online. Microsoft. 2007-09-15. Retrieved 2007-06-17.
^SAS 9.4 SQL Procedure User's Guide. SAS Institute (published 2013). 10 July 2013. p. 248. ISBN9781612905686. Retrieved 2015-10-21. Although the UNIQUE argument is identical to DISTINCT, it is not an ANSI standard.
^Leon, Alexis; Leon, Mathews (1999). "Eliminating duplicates - SELECT using DISTINCT". SQL: A Complete Reference. New Delhi: Tata McGraw-Hill Education (published 2008). p. 143. ISBN9780074637081. Retrieved 2015-10-21. [...] the keyword DISTINCT [...] eliminates the duplicates from the result set.
Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Oktober 2022. Buku ilmu antik adalah karya sejarah asli, misalnya buku atau makalah teknis, tentang sains, matematika, dan kadang-kadang teknik. Buku-buku ini adalah rujukan utama yang penting untuk kajian sejarah sains dan teknologi, yang dapat memberikan wawasan b...
Sings LegendsAlbum kompilasi karya NOAHDirilis19 Mei 2016 (2016-05-19)Direkam2008 (2008) – 2016 (2016)Studio Musica Studio's, Jakarta Masterplan Recording Chamber, Bandung GenreRock alternatifpop rockrock elektronikpopDurasi38:56LabelMusica Studio'sProduserNoahKronologi NOAH Second Chance(2014)Second Chance2014 Sings Legends(2016) Keterkaitan Keterikatan(2019)Keterkaitan Keterikatan2019 Singel dalam album Sings Legends Sajadah PanjangDirilis: 13 Mei 2016 Anda...
Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Ali Suavi – berita · surat kabar · buku · cendekiawan · JSTOR Ali Suavi (1838-1878) ialah seorang pemberontak dan penulis. Ia menulis di surat kabar Muhbir pada tahun 1866, melarikan diri ke Eropa pada t...
Building complex in Toronto, Ontario The CrosswaysThe twin 29-storey apartment towers seen from the northGeneral informationStatusCompletedLocation2340 Dundas Street WestToronto, OntarioOwnerCreccal Investments Ltd.Design and constructionArchitect(s)Webb Zerafa Menkès Housden PartnershipDeveloperConsolidated Building Corporation The Crossways is a mixed-use residential/commercial complex in the west end of Toronto, Ontario, Canada, located at the intersection of Bloor Street West and Dundas ...
Questa voce o sezione sull'argomento calciatori è priva o carente di note e riferimenti bibliografici puntuali. Sebbene vi siano una bibliografia e/o dei collegamenti esterni, manca la contestualizzazione delle fonti con note a piè di pagina o altri riferimenti precisi che indichino puntualmente la provenienza delle informazioni. Puoi migliorare questa voce citando le fonti più precisamente. Segui i suggerimenti del progetto di riferimento. Pat Bonner Bonner (a destra) in azione in n...
English footballer Jack Powell Powell in November 2015Personal informationFull name Jack Patrick Powell[1]Date of birth (1994-01-29) 29 January 1994 (age 30)[2]Place of birth Canning Town, EnglandHeight 1.85 m (6 ft 1 in)[2]Position(s) MidfielderTeam informationCurrent team Crewe AlexandraNumber 23Youth career0000–2013 West Ham UnitedSenior career*Years Team Apps (Gls)2013–2016 Millwall 6 (0)2013–2014 → Concord Rangers (loan) 7 (1)2015–201...
Emblema del femminismo. «Per fortuna la scuola, il lavoro e il progresso hanno un po' aperto gli occhi alle donne. In molti paesi le donne hanno ottenuto gli stessi diritti degli uomini; molte persone, soprattutto donne, ma anche uomini, adesso capiscono quanto questa suddivisione fosse sbagliata e le donne moderne vogliono avere il diritto all'indipendenza totale!» (Anna Frank, Diario di Anna Frank[1].) La storia del femminismo è la narrazione cronologica degli eventi riconducibil...
Державний комітет телебачення і радіомовлення України (Держкомтелерадіо) Приміщення комітетуЗагальна інформаціяКраїна УкраїнаДата створення 2003Керівне відомство Кабінет Міністрів УкраїниРічний бюджет 1 964 898 500 ₴[1]Голова Олег НаливайкоПідвідомчі ор...
Ця стаття потребує додаткових посилань на джерела для поліпшення її перевірності. Будь ласка, допоможіть удосконалити цю статтю, додавши посилання на надійні (авторитетні) джерела. Зверніться на сторінку обговорення за поясненнями та допоможіть виправити недоліки. Мат...
American politician (born 1963) This article is about the Attorney General of Minnesota. For other people named Keith Ellison, see Keith Ellison (disambiguation). Keith Ellison30th Attorney General of MinnesotaIncumbentAssumed office January 7, 2019GovernorTim WalzPreceded byLori SwansonMember of the U.S. House of Representativesfrom Minnesota's 5th districtIn officeJanuary 3, 2007 – January 3, 2019Preceded byMartin Olav SaboSucceeded byIlhan OmarDeputy Chair of the...
2001 extended version of Apocalypse Now directed by Francis Ford Coppola Apocalypse Now ReduxTheatrical release posterDirected byFrancis Ford CoppolaWritten by John Milius Francis Ford Coppola Narration byMichael Herr Produced by Francis Ford Coppola Kim Aubry Starring Marlon Brando Robert Duvall Martin Sheen Frederic Forrest Albert Hall Sam Bottoms Laurence Fishburne Christian Marquand Aurore Clément Harrison Ford Dennis Hopper CinematographyVittorio StoraroEdited by Richard Marks Walter Mu...
American racing driver (1875–1945) John JenkinsBornJohn William Jenkins(1875-11-11)November 11, 1875Springfield, Ohio, U.S.DiedNovember 26, 1945(1945-11-26) (aged 70)Brownsville, Texas, U.S.Champ Car career9 races run over 5 yearsFirst race1909 Indianapolis Race #6 (Indianapolis)Last race1913 Columbus 200 (Columbus)First win1911 Hamilton County Trophy (Cincinnati) Wins Podiums Poles 1 3 0 John William Jenkins (November 11, 1875 – November 26, 1945) was an American racing driver. Acco...
Federal electoral district in British Columbia, CanadaNewton—North Delta British Columbia electoral districtNewton—North Delta in relation to other federal electoral districts in VancouverCoordinates:49°07′52″N 122°53′10″W / 49.131°N 122.886°W / 49.131; -122.886Defunct federal electoral districtLegislatureHouse of CommonsDistrict created2003District abolished2013First contested2004Last contested2011District webpageprofile, mapDemographicsPopulation (201...
Palestinian Arab nationalist (1907–1948) Abd al-Qadir al-Husayniعبد القادر الحسينيPortraitBorn1907 (1907)Jerusalem, Ottoman EmpireDied8 April 1948(1948-04-08) (aged 40–41)Al-Qastal, Mandatory PalestineAllegiance Palestinian Arab irregularsService/branch Army of the Holy WarYears of service1936–1948Battles/warsArab revolt in Palestine1941 Iraqi coup d'étatCivil war in Palestine Battle of al-Qastal † RelationsMusa al-Husayni (father)Faisal Hussei...
Pour les articles homonymes, voir Marie Mancini (homonymie). Maria ManciniBiographieNaissance 1355PiseDécès 22 janvier 1431PiseActivité Religieuse chrétienneAutres informationsOrdre religieux Ordre des PrêcheursÉtape de canonisation BienheureuseFête 30 janviermodifier - modifier le code - modifier Wikidata La Bienheureuse Marie Catherine Mancini, née en 1355 à Pise et morte dans la même ville le 22 janvier 1431, est une religieuse dominicaine italienne. Le Pape Pie IX confirme son ...
US Navy submarine For other ships with the same name, see USS Growler. Regulus I missile aboard USS Growler at Pier 86 in New York, its museum ship home. History United States NameGrowler NamesakeGrowler Ordered31 July 1954 BuilderPortsmouth Naval Shipyard Laid down15 February 1955 Launched5 April 1958 Sponsored byMrs. Robert K. Byerts, widow of Commander Thomas B. Oakley, Jr. Commissioned30 August 1958 Decommissioned25 May 1964 Stricken1 August 1980 HomeportPearl Harbor, HI StatusMuseum...
مدرسة ثانوية کيخسروي دبیرستان کیخسروی مدرسة ثانوية كيخسروي معلومات الموقع الجغرافي المدينة يزد البلد إيران تعديل مصدري - تعديل مدرسة ثانوية کيخسروي هي مدرسة تاريخية تعود إلى القاجاريون ودولة بهلوية، وتقع في يزد.[1] مراجع ^ Encyclopaedia of the Iranian Architectural History. Cultural Heritage,...
2022 Irish filmRóise & FrankPosterDirected by Rachael Moriarty Peter Murphy Written by Rachael Moriarty Peter Murphy Produced by Suzanne Colwell Cúán Mac Conghail Starring Bríd Ní Neachtain Cillian O'Gairbhi CinematographyPeter RobertsonEdited by Colin Campbell Mary Crumlish Music byColm Mac Con IomaireProductioncompanyMacalla TeorantaDistributed byBreak Out PicturesRelease dates 27 February 2022 (2022-02-27) (Dublin) 16 September 2022 (2022-09-16)&...