Chapter 3. Data Retrieval Using Transact-SQL Statements

The primary purpose of creating databases and tables in SQL Server is to store data and make that data available to users and application queries. Like any other Relational Database Management System (RDBMS), retrieval of data from a SQL Server database is a relatively straightforward task. In this chapter, you will learn how to get data from the databases using the Transact-SQL (T-SQL) SELECT statement. After reading through the chapter, you will be able to understand the following:

  • Transact-SQL SELECT, FROM, and WHERE clauses
  • Use a Transact-SQL function in a query
  • Multiple table queries using UNION, EXCEPT, INTERSECT, and JOINs
  • Use subqueries and CTEs to perform advanced queries
  • Organizing, grouping, and pivoting data
  • Use of the Transact-SQL analytic window functions

    Note

    This chapter contains a large number of example T-SQL queries, all of which require the AdventureWorks2012 database, which is available for download from http://msftdbprodsamples.codeplex.com/downloads/get/478214.

    After attaching the AdventureWorks2012 database to your SQL Server instance, enter and execute the following Transact-SQL in SSMS 2014 to set its compatibility level to SQL Server 2014:

    USE [master];
    GO
    
    ALTER DATABASE [AdventureWorks2012] SET COMPATIBILITY_LEVEL = 120;
    GO

Understanding Transact-SQL SELECT, FROM, and WHERE clauses

In this section, you will learn how to use the Transact-SQL SELECT, FROM, and WHERE clauses to retrieve the data you need from the SQL Server databases.

The SELECT statement

The SELECT statement is the most frequently used Transact-SQL statement. We use the SELECT statement for the following purposes:

  • To query specific data from the selected database tables
  • To assign a value to local variables
  • To call a function

We often see SELECT statements within programming objects (such as views, stored procedures, functions, batches, and common table expressions (CTEs)). We also use SELECT statements to run ad hoc queries, most often through an SSMS 2014 query window. The SELECT statement has several clauses, most of which are optional. The following is the general syntax of the SELECT statement:

SELECT [TOP(n)|TOP(n) PERCENT] [ALL|DISTINCT] select_list
[INTO[[database.]owner.]table_name]
FROM[[[database.]owner.]table_name|view_name|UDF]
[WHERE search_conditions]
[GROUP BY aggregate_free_expression]
[HAVING search_conditions]
[ORDER BY table_or_view_and_column]
[COMPUTE row_aggregate(column_name)]
[BY column_name]]
[FOR for_options]
[OPTION (query_hint)][;]

The select_list parameter is the list of expressions (such as numeric computation, constants, functions, aliases, and subqueries) or columns in the SELECT clause that you want to return in the query result set. We can use asterisk (*) as a wildcard character in the select_list parameter of the SELECT statement to return all columns from the selected tables. For example, the following query returns all columns from the Sales.Currency table in the AdventureWorks2012 database:

SELECT  *
FROM    [Sales].[Currency];

However, you should avoid using the asterisk (*) wildcard character in select_list; instead, provide a full list of columns needed for the query, because SQL Server resolves the column list each time the SELECT statement is executed. Moreover, if we use SELECT * in the T-SQL code, the SELECT statement might generate an error due to changes in the schemas of the underlying tables. To display the values in CurrencyCode and Name from the Sales.Currency table, run the following code:

SELECT  [CurrencyCode] ,
        [Name]
FROM    [Sales].[Currency];

The FROM clause

The purpose of the FROM clause in the SELECT statement is to identify the data sources for a query. For example, in the previous example, we used the FROM clause in the SELECT statement to specify the Sales.Currency table as a data source for the query.

The WHERE clause

The WHERE clause is used to specify the query criteria, so that only the required subset of data is returned in the result set. For example, suppose that you want to write a query to return all the currency codes that begin with the A character. To accomplish this, we include the WHERE clause in the preceding query as follows:

SELECT  [CurrencyCode] ,
        [Name]
FROM    [Sales].[Currency]
WHERE   [CurrencyCode] LIKE 'A%';

The WHERE clause always comes after the FROM clause and can include conditions that use the following:

  • Comparison operators (= (equal to), <> (not equal to), != (not equal to), > (greater than), !> (not greater than), < (less than), !< (not less than), >= (greater than or equal to), and <= (less than or equal to))
  • Subqueries and JOINs
  • The LIKE operator for wildcard searches
  • The BETWEEN operator for searching ranges of data
  • The IN and NOT IN operators to match any one value from a list of values
  • The EXISTS and NOT EXISTS keywords to check whether a value or record exists in the result set
  • The IS and IS NOT operators to search for NULLs
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.106.237