{"id":93376,"date":"2022-02-22T18:08:53","date_gmt":"2022-02-22T18:08:53","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=93376"},"modified":"2022-02-22T18:08:53","modified_gmt":"2022-02-22T18:08:53","slug":"the-basic-t-sql-select-statement","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/the-basic-t-sql-select-statement\/","title":{"rendered":"The basic T-SQL SELECT statement"},"content":{"rendered":"<p>The <code>SELECT<\/code> statement is the most used statement in the T-SQL language. It is executed to retrieve columns of data from one or more tables. The SELECT statement can constrain the data returned by using the <code>WHERE<\/code> or <code>HAVING<\/code> clause, and sort or group results using the <code>ORDER<\/code> <code>BY<\/code> and <code>GROUP<\/code> <code>BY<\/code> clauses, respectively. A <code>SELECT<\/code> statement can also be made up of many different <code>SELECT<\/code> statements, commonly called subqueries.<\/p>\n<p>There are many different aspects of the <code>SELECT<\/code> statement, making it a very complex T-SQL statement. This article is the first in a series of articles that will cover the various nuances of the <code>SELECT<\/code> statement. In this article, I will discuss only the basics of the <code>SELECT<\/code> statement.<\/p>\n<h2>The SELECT statement<\/h2>\n<p>The <code>SELECT<\/code> statement has many different pieces, making it multifaceted. The main clauses supported by the <code>SELECT<\/code> statement as found in the <a href=\"https:\/\/docs.microsoft.com\/en-us\/sql\/t-sql\/queries\/select-transact-sql?view=sql-server-ver15\">Microsoft Documentation<\/a> are shown in Figure 1.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-93377\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/02\/table-description-automatically-generated-with-lo.png\" alt=\"An image showing the many options of the SELECT statement\" width=\"639\" height=\"163\" \/><\/p>\n<p><strong>Figure 1: Main clauses of the SELECT statement<\/strong><\/p>\n<p>The <code>SELECT<\/code> statement supports many different options. To discuss each of these various options would require a very long article. For the purpose of this article, I will only be focusing on a few clauses, which I am presenting as the basic <code>SELECT<\/code> statement syntax shown in Figure 2.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-93378\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/02\/word-image-12.png\" alt=\"An image showing the three parts: SELECT list, FROM table_source, WHERE search_condition\" width=\"632\" height=\"42\" \/><\/p>\n<p><strong>Figure 2: Basic SELECT statement<\/strong><\/p>\n<p>The basic <code>SELECT<\/code> statement has three parts: the select list, the <code>FROM<\/code> clause, and the <code>WHERE<\/code> clause.<\/p>\n<h2>The SELECT list<\/h2>\n<p>The <code>select_list<\/code> component identifies the data that will be returned when the <code>SELECT<\/code> statement is executed. This is the only part that is required in every <code>SELECT<\/code> statement. All other attributes of a <code>SELECT<\/code> statement are options.<\/p>\n<p>The <code>select_list<\/code> identifies one or more items of data that will be returned when the <code>SELECT<\/code> statement is executed. When multiple items are identified in the list, each item is separated by a comma. The arguments of a select list can take on many different forms, like a column name, a calculation, a function call, or a literal constant, to name a few.<\/p>\n<p>The format of the <code>select_list<\/code> as found in the <a href=\"https:\/\/docs.microsoft.com\/en-us\/sql\/t-sql\/queries\/select-clause-transact-sql?view=sql-server-ver15\">SELECT clause<\/a> documentation is shown in Figure 3.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-93379\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/02\/graphical-user-interface-text-application-email-5.png\" alt=\"An image showing many options for the SELECT list\" width=\"528\" height=\"240\" \/><\/p>\n<p><strong>Figure 3: <em>Select_list<\/em> specifications<\/strong><\/p>\n<p>Listing 1 has an example of a <code>SELECT<\/code> statement that contains only a selection list. There are two different columns of data in the list that will be returned.<\/p>\n<p><strong>Listing 1: Returning a calculated field and literal value<\/strong><\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">USE tempdb;\r\nGO \r\nSELECT 1024*1024, \t\r\n       'The Basic Select Statement';<\/pre>\n<p>Report 1 shows the two column values returned when Listing 1 is executed.<\/p>\n<p><strong>Report 1: Columns returned when Listing 1 is executed <\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"241\" height=\"28\" class=\"wp-image-93380\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/02\/word-image-13.png\" \/><\/p>\n<p>The first column returned is the result of a calculation that multiplies 1024 by1024. The second column displayed is just the literal string <em>The Basic Select Statement<\/em>. The columns returned were not given column names, hence why the column names say (No column name).<\/p>\n<p>Not having a column name for some columns in the result set is not really a problem, unless you need to reference the returned data by name. To assign names to these two columns, a column alias can be used.<\/p>\n<h2>Assigning column aliases<\/h2>\n<p>A column alias is useful when you want to assign a specific name to a column of data returned from a <code>SELECT<\/code> statement. If you refer to the <code>select_list<\/code> specifications found in Figure 3 there are two ways to define a column alias. One way is to use the <code>AS<\/code> keyword, followed by the name of the column alias. The <code>AS<\/code> keyword is optional. The other way is to use the equal operator (<code>=<\/code>), where the alias name is defined on the left side of the <code>=<\/code> sign. The <code>SELECT<\/code> statement in Listing 2 returns the same data as Listing 1, but each item identified in the selection list has now been given a column alias name.<\/p>\n<p><strong>Listing 2: Defining column aliases<\/strong><\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">USE tempdb;\r\nGO \r\nSELECT 1024*1024 AS NumOfBytesInMB, \t\r\n       'The Basic Select Statement' BasicSelectStatement;<\/pre>\n<p>When Listing 2 is executed each column returned will have a column alias name assigned, as shown in Report 2.<\/p>\n<p><strong>Report 2: Results from execution of Listing 2<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-93381\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/02\/word-image-14.png\" alt=\"An image showing table results: NumOfBytesInMB, BasicSelectStatement, 1048576, The Basic Select Statement\" width=\"237\" height=\"34\" \/><\/p>\n<p>In Listing 2, both column alias names do not contain any spaces in the name. If you want to include spaces in an alias name, then the name needs to be enclosed in quotes. Quotes can either be a set of brackets or single or double quotation marks. Lisitng 3 shows how to use the different quoting options.<\/p>\n<p><strong>Listing 3: Creating alias names with spaces<\/strong><\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">USE tempdb;\r\nGO \r\nSET QUOTED_IDENTIFIER ON\r\nSELECT 1024*1024 AS [Num of bytes in a MB], \t\r\n       \"Using Double Quotes\" = 'The Basic Select Statement',\r\n\t'ABC' AS 'String ABC';<\/pre>\n<p>The output in Report 3 is produced when Listing 3 is executed.<\/p>\n<p><strong>Report 3: Aliases with spaces in name<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"324\" height=\"36\" class=\"wp-image-93382\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/02\/word-image-15.png\" \/><\/p>\n<h2>The FROM clause<\/h2>\n<p>The <code>FROM<\/code> clause in SQL Server is used to identify a table or tables in which to retrieve data. In this basic <code>SELECT<\/code> clause article, I will only discuss retrieving data from a single SQL Server table. Future articles will talk about retrieving data from multiple tables.<\/p>\n<p>A table within SQL Server is stored in a database. A given SQL Server instance might have many databases, and there might be many tables within a database. Tables within a database are grouped and organized by a schema. The hierarchy of databases, schemas, and tables means there might be multiple tables within a SQL Server instance that have the same name. Because a given table name could reside in various schemas, databases, or even instances, the table name used must be uniquely identified in the <code>FROM<\/code> clause. To uniquely identify a table in the <code>FROM<\/code> clause, it can be named using a one, two, three, or four-part name, where each part is separated by a period (<code>.<\/code>).<\/p>\n<p>A one-part table name is a table name that doesn\u2019t contain a period, like <em>Orders<\/em> or <em>Customers. <\/em>When a one-part name is used in the <code>FROM<\/code> clause, the database engine needs to determine which schema owns the table. To identify the schema that owns a one-part table name SQL Server uses a two-step process. The first step is to see if the table resides in the default schema associated with the user submitting the <code>SELECT<\/code> statement. If the table is in the default schema for the user, then that table is used, and the database engine doesn\u2019t need to process the second step. If the table is not found in the user\u2019s default schema, then the second step of identifying the table is performed. The second step looks into the <em>dbo<\/em> schema to try and find the table. When a database contains only a single schema named <em>dbo, <\/em>using one-part names makes sense. However, when there are multiple schemas in a database, it is best to use multiple part table names to clarify what table is used. It simplifies the amount of work SQL Server needs to perform to identify the table.<\/p>\n<p>A two-part name is made up of both the table name and schema that contains the table with a period (<code>.<\/code>) in between, like <em>Sales.Orders, <\/em>or <em>Sales.Customer. <\/em> When writing <code>SELECT<\/code> statements that only query data from tables in a single database with multiple schemas, the best practice is to use two-part table names.<\/p>\n<p>In most cases, when a <code>SELECT<\/code> statement uses tables in a single database, one and two-part table names are used. Three-part table names are needed when code is run in the context of one database and needs to retrieve data from another database, or you are joining data from multiple tables that live in different databases. The third part of the name precedes the two-part table name and identifies the database in which the table lives, like <em>AdventureWorks2019.Sales.Orders. <\/em><\/p>\n<p>The last way to uniquely identify a table in the <code>FROM<\/code> clause is to include the instance name as the fourth part. The instance name is placed in front of the fully qualified three-part table name. Four-part names are used to query across instances using a linked server. Discussion of Linked servers is an entirely separate topic, which I will leave for a future article.<\/p>\n<p>The <code>SELECT<\/code> statement example in Listing 4 runs in the context of the <em>AdventureWorks2019 <\/em>database using a two-part table name to return all the data in the <em>Territory <\/em>table, owned by the <em>Sales <\/em>schema.<\/p>\n<p><strong>Listing 4: Using two-part table name<\/strong><\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">USE AdventureWorks2019;\r\nGO\r\nSELECT * FROM Sales.SalesTerritory;<\/pre>\n<p>The statement in Listing 5 uses a three-part table name to return all the data from the <em>Territory <\/em>table in the <em>Sales <\/em>schema within the <em>AdventureWorks2019<\/em> database, but it runs in the context of the <em>tempdb <\/em>database.<\/p>\n<p><strong>Listing 5: Using three-part table name<\/strong><\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">USE tempdb\r\nGO\r\nSELECT * FROM AdventureWorks2019.Sales.SalesTerritory;<\/pre>\n<p>The rows displayed in Report 4 are produced when either the code in Listing 4 or Listing 5 is executed.<\/p>\n<p><strong>Report 4: Output when Listing 4 or 5 is run<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-93383\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/02\/word-image-16.png\" alt=\"An image showing tabular results of querying all the columns of the Sales.SalesTerritory table\" width=\"1013\" height=\"184\" \/><\/p>\n<p>In Listing 4 and Listing 5, the <code>*<\/code> wildcard character was used for the <em>select_list <\/em>option. The <code>*<\/code> tells SQL Server that all columns from the <em>AdventureWorks2019.Sales.SalesTerritory <\/em>table are to be returned based on their ordinal positions within the table. Using the <code>*<\/code> wildcard character in the selection list is a simple way to specify and select all the columns in a table. I wouldn\u2019t recommend using wildcard characters for production code because if columns are added or dropped from the table being queried, the number of columns returned will be based on the table definition at the time of the query. Best practice is not to use wild card characters and instead specifically identify column names for the data that needs to be returned. Note that there are some situations where wildcards do make sense, and I\u2019ll cover those in later articles. The <code>SELECT<\/code> statement in Listing 6 returns the same results as Listings 4 and 5 but specifics the actual quoted column names instead of the <code>*<\/code> wildcard character.<\/p>\n<p><strong>Listing 6: Specify column names<\/strong><\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">USE AdventureWorks2019;\r\nGO\r\nSELECT [TerritoryID],\r\n       [Name], \r\n\t  [CountryRegionCode], \r\n\t  [Group], \r\n\t  [SalesYTD], \r\n\t  [SalesLastYear], \r\n\t  [CostYTD], \r\n\t  [CostLastYear], \r\n\t  [rowguid], \r\n\t  [ModifiedDate]\r\nFROM Sales.SalesTerritory;<\/pre>\n<h2>The WHERE clause<\/h2>\n<p>The <code>SELECT<\/code> statement examples I have shown so far returned all the rows in the <em>AdventurewWorks2019.Sales.SalesTerritory <\/em>table. There might be times when you don\u2019t want to return all the rows in a table but instead only want to return a subset of rows. When this is the case, the <code>WHERE<\/code> clause can be used to restrict the rows returned.<\/p>\n<p>When using the <code>WHERE<\/code> clause, search criteria needs to be specified. The search criteria identifies one or more expressions, known as predicates, that each row must meet in order to be selected. The logical operators <code>AND<\/code>, <code>OR<\/code>, and <code>NOT<\/code> can be used to string together multiple expressions for fine-tuning the exact rows that should be returned.<\/p>\n<p>Listing 7 has a <code>SELECT<\/code> statement that contains a single expression in the <code>WHERE<\/code> clause. In this case, only the <em>Sales.SalesTerritory <\/em>records that have their <em>SalesLastYear <\/em>value greater than 3,000,000 will be returned.<\/p>\n<p><strong>Listing 7: Simple search condition in WHERE statement<\/strong><\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">USE AdventureWorks2019;\r\nGO\r\nSELECT * FROM Sales.SalesTerritory\r\nWHERE SalesLastYear &gt; 3000000;<\/pre>\n<p>When the code in Listing 6 is executed the rows in Report 5 are returned.<\/p>\n<p><strong>Report 5: Rows returned when Listing 7 is executed<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-93384\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/02\/word-image-17.png\" alt=\"An image showing tabular results. Only 6 rows returned because of the WHERE clause\" width=\"1480\" height=\"176\" \/><\/p>\n<p>Sometimes more complex search conditions are needed to produce a specific subset of rows. The <code>SELECT<\/code> statement in Listing 8 uses two different conditions in the <code>WHERE<\/code> clause to narrow down the rows returned. The two different conditions use the logical <code>AND<\/code> operator to create a complex compound search condition.<\/p>\n<p><strong>Listing 8: Using two expressions with the AND operator<\/strong><\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">USE AdventureWorks2019;\r\nGO\r\nSELECT * FROM Sales.SalesTerritory\r\nWHERE SalesLastYear &gt; 3000000\r\n  AND CountryRegionCode = 'CA';<\/pre>\n<p>Report 6 shows the output created when Listing 8 is run.<\/p>\n<p><strong>Report 6: Results when Listing 8 is executed<\/strong><\/p>\n<p><em><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-93385\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/02\/word-image-18.png\" alt=\"An image showing tabular results. Only 1 row returned because of multiple predicate where clause\" width=\"1426\" height=\"46\" \/><\/em><\/p>\n<h1>The basic T-SQL SELECT statement<\/h1>\n<p>The <code>SELECT<\/code> statement is the most used statement in the T-SQL language. Understanding the basics of the <code>SELECT<\/code> clause in the foundation of all other formats of the <code>SELECT<\/code> statement. Identifying columns in the selection list, tables in the <code>FROM<\/code>, and constraints in the <code>WHERE<\/code> clause will allow you to return any subset of rows from a database table. I will discuss other more complex aspects of querying SQL Server data using the <code>SELECT<\/code> statement in future articles.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The SQL language is used across many relational database platforms. Greg Larsen explains the basics of the SELECT statement for SQL Server.&hellip;<\/p>\n","protected":false},"author":78478,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[53,143525,143531],"tags":[5134],"coauthors":[11330],"class_list":["post-93376","post","type-post","status-publish","format-standard","hentry","category-featured","category-learn","category-t-sql-programming-sql-server","tag-sql-prompt"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/93376","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/78478"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=93376"}],"version-history":[{"count":4,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/93376\/revisions"}],"predecessor-version":[{"id":93387,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/93376\/revisions\/93387"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=93376"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=93376"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=93376"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=93376"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}