Tsql

Page 1

FROM and SELECT clause T-SQL

In this tutorial we will give you a few examples about the FROM and SELECT clauses. This tutorial is meant for beginners who have just began learning about T-SQL. We will not cover the complete syntax of FROM and SELECT clause in this tutorial. Let's begin with the FROM clause. The FROM clause specifies one or more tables containing the data that the query retrieves from. The FROM clause has a few roles. One role it plays is an indicator of the table you want to query.Also in from clause you use operators like joins which are used to join two or more tables and table hints which are used to override the default behavior of the query optimizer. If you are interested in reading about table hints you can read it from the Microsoft website. In this tutorial we will just give an example showing how you can use table hints in the FROM clause. http://msdn.microsoft.com/en-us/library/ms187373.aspx In the FROM clause, you can specify where you want your results to come from or the table you want to use. SELECT * FROM dbo.DimCustomer

As you can see from the above code the “dbo” is the schema name. Tip!: It is considered a good practice to use schema names in the FROM clause . It is considered a bad practice to use “*” in your statement. In the FROM clause, you can give a name for your table to increase readability. This name is called alias or table alias. SELECT * FROM dbo.DimCustomer AS “C”

In the FROM clause, you can also use table hints. Hints override the default behavior of the query optimizer for the time the query is running. SELECT * FROM dbo.DimCustomer WITH (FORCESCAN)

In the FROM clause you declare table operations like joins. SELECT * FROM dbo.DimCurrency DC INNER JOIN dbo.FactInternetSales FI ON DC.CurrencyKey =FI.CurrencyKey


The SELECT statement is used to retrieve rows form a table or selecting one or more columns from a table.

Example : Select all columns form the customer table in AdventureWorksDW2012: SELECT * FROM dbo.DimCustomer

Tip!: It is considered a bad practice to use “*” in your statement.To avoid using of “*” you can use one of the following, a good practice would be to go “Object explorer and select the table then select the columns like in the following picture.


Table structure T-SQL

Another useful way would be to use “System tables” to see all the columns for a specific table. To do that use the following code. SELECT name FROM sys.columns WHERE object_id =37575172


Learn more at http://www.pcfixtutorials.com


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.