Logo
programming4us
programming4us
programming4us
programming4us
Home
programming4us
XP
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server
programming4us
Windows Phone
 
Windows Server

SQL Server 2012 : Transact-SQL - Data Manipulation Language (part 1)

- How To Install Windows Server 2012 On VirtualBox
- How To Bypass Torrent Connection Blocking By Your ISP
- How To Install Actual Facebook App On Kindle Fire
11/30/2014 8:28:56 PM

Most of what you’ll do with T-SQL centers around the Data Manipulation Language (DML). DML consists of the four statements SELECT, INSERT, UPDATE, and DELETE. These are the four statements that you use to get data into a database, update and delete that data, and get it back out again.

SELECT

The SELECT DML statement allows users to retrieve data from the database. A simplified version of the syntax follows:

SELECT <select_list> FROM <table_source> [WHERE <search_condition>]

where the parameters are defined as follows:

  • <select_list> specifies the columns that you want to return in the query.
  • <table_source> is the table that you want to retrieve data from.
  • <search_condition> is used to filter or scope the results that you are seeking.

The WHERE clause is optional. If you omit this clause, you will return all the rows from the given table. You can think of the WHERE clause like a Boolean expression. That is, the expression will be evaluated across every row in the table.

Basic SELECT Queries

Let’s look at an example. If you wanted to return all the pets’ names and weights, you would issue the following SELECT query:

SELECT pet_name, pet_weight FROM Pets

This statement would return the following result set:


pet_name     pet_weight

Zeus             185

Lady             155

Deno              50

Rex               44

Rover             15

If you wanted to narrow the result set, you could add a WHERE clause like the following:

SELECT pet_name, pet_weight FROM Pets WHERE pet_weight > 100

This WHERE expression would cause the result set to return only pets whose weight was greater than the value 100.

In the example, you explicitly asked SQL Server to return specific columns from the table. You could have used an asterisk (*) instead, and this would have returned all the columns in the table. To return all the columns in the Pets table, you would issue the following statement:

SELECT * FROM Pets

Sometimes tables have millions or billions of rows, and you don’t really want to enumerate all of them at once. There are expressions like TOP that you can use to limit the result set. TOP specifies that only a specific number of results or percentage of results will be returned from the query. For example, SELECT TOP 3 * FROM Pets will return the first three pets stored within the table, as shown here:


Pet_id   pet_name   pet_weight   MicroChipID

1           Zeus          185        398BF49

2           Lady          155        191ABBC

3           Deno           50       790AG441

This limiting capability is also useful when used in conjunction with other clauses defined within the query. The ORDER BY clause is used to instruct SQL Server to order the result set in a particular way. You specify the columns to sort by and the direction of the sort as parameters of the ORDER BY clause. For example, if you wanted to know the top three lightest pets, you would issue the following query:

SELECT TOP 3 * FROM Pets ORDER BY pet_weight ASC

This would yield the following result:


Pet_id   pet_name   pet_weight   MicroChipID

5           Rover         15        A8719841

4           Rex           44        CDD81322

3           Deno          50        790AG441

The ASC parameter instructs SQL Server to order the results in ascending order, or lowest to highest. If you wanted to go the other way and order from highest to lowest, you could have specified DESC, which means descending.

A key value for relational databases is the fact that sometimes different tables hold data that is related to each other. This data can be combined and returned in a single result set. In this example, you have a Pets table and an Owners table. Pets have owners, so if you wanted to figure out which owners have pets with a weight greater than 100, you could accomplish this by joining the tables within the query. When you join together tables, you have the option of specifying what to do with the rows that are matched and those that are not matched. What happens depends on what kind of JOIN you include in your query. For example, if you wanted to know all the pets who have owners, you could execute this statement:

SELECT pet_name,owner_name FROM Pets
 INNER JOIN Owners
 ON Pets.pet_id=Owners.pet_id

This statement will yield the following results:


pet_name     owner_name

Lady            Bryan

Deno            Rob

Zeus            Rob

If you look at the data in both the Pets and Owners tables, you can see that two additional pets, Rex and Rover, were not displayed. This is because the Owners table does not have a matching pet_id for these two pets.

If you wanted to list all the pets regardless of whether they had an owner, you could issue a LEFT OUTER JOIN, which will always include the data from the table defined on the left side of the JOIN statement. The following is an example of listing all the pets and their owners, if they have any:

SELECT pet_name,owner_name FROM Pets
 LEFT OUTER JOIN Owners
 ON Pets.pet_id=Owners.pet_id

This statement will yield the following result:


pet_name   owner_name

Zeus           Rob

Lady           Bryan

Deno           Rob

Rex            NULL

Rover          NULL

Notice that NULL values result when owners do not exist. Rex has no owner name on record. The system doesn’t make up a name where none exists. When no value exists, the system will return NULL.

Note INNER JOIN is the default join if you do not specify the join type.

There are other types of joins: RIGHT OUTER joins are similar to LEFT OUTER joins except they include the result set for the table to the right of the JOIN statement. A FULL OUTER join lists all results for both tables to the left and right of the JOIN statement.

Paging Support

When you want to view a product catalog on a web page, you usually see the results returned from 1–25 for example. The actual query, though, might have returned hundreds or thousands of results. A lot of developers spent time writing complex code in the middle-tier web page layer or the database layer to parse the full query for the specified range. Starting in SQL Server 2012, native paging support is available that allows you to ask for specific ranges of rows to be returned. To illustrate, let’s add a few more rows of data to our Pets table:

INSERT INTO Pets
VALUES(6,'Roscoe',55,'F5CAA29'),
(7,'Missy',67,'B7C2A59'),
(8,'George',12,'AA63BC5'),
(9,'Spot',34,'CC8A674')
GO

If you wanted to know the three heaviest pets, you could leverage the TOP T-SQL statement as follows:

SELECT TOP 3 pet_name,pet_weight FROM Pets ORDER BY pet_weight DESC

This would get the answer, but it would be difficult to find out the next three heaviest pets. This is where the OFFSET and FETCH statements work well. Consider the following statement, which uses OFFSET (0) to specify stating at the beginning and FETCH NEXT 3 ROWS to request only the three heaviest pets:

SELECT pet_name,pet_weight FROM Pets
    ORDER BY pet_weight DESC    
        OFFSET (0) ROWS    FETCH NEXT 3 ROWS ONLY

Running this statement yields the same result as our TOP 3 statement:


pet_name   pet_weight

Zeus           185

Lady           155

Missy          67

If you wanted to know the next three, you would set the offset to start at the third result and fetch the next three. Notice the use of OFFSET (3) in the following example:

SELECT pet_name,pet_weight FROM Pets
    ORDER BY pet_weight DESC    
        OFFSET (3) ROWS    FETCH NEXT 3 ROWS ONLY;

This would yield the following result:


pet_name   pet_weight

Roscoe       55

Deno         50

Rex          44

SELECT is arguably the most frequently used DML statement. Many different expressions and clauses are possible to use with SELECT. Mastering the use of this statement will be important in your daily use of SQL Server or any other database platform.

Other -----------------
- SQL Server 2012 : Transact-SQL - The VetClinic Sample Database Revisited, Data Types
- Microsoft Sharepoint 2013 : Claims Authentication and Oauth - Server-to-Server Authentication
- Microsoft Sharepoint 2013 : Application Authentication (part 3) - App Authentication - App Catalog App Authentication
- Microsoft Sharepoint 2013 : Application Authentication (part 2) - App Authentication - SharePoint Store App Authentication
- Microsoft Sharepoint 2013 : Application Authentication (part 1) - Cloud App Model, OAuth
- Microsoft Sharepoint 2013 : User Authentication (part 4) - Using Claims-Based Identity - Federated User Authentication Process
- Microsoft Sharepoint 2013 : User Authentication (part 3) - Using Claims-Based Identity - Understanding the User Authentication Process and Authentication Providers
- Microsoft Sharepoint 2013 : User Authentication (part 2) - Using Claims-Based Identity
- Microsoft Sharepoint 2013 : User Authentication (part 1) - Claims-Based Identity
- Microsoft Sharepoint 2013 : What’s New with Claims and Authorization?
 
 
Top 10
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Trailers Game
- The Banner Saga 2 [PS4/XOne/PC] PC Launch Trailer
- Welkin Road [PC] Early Access Trailer
- 7th Dragon III Code: VFD [3DS] Character Creation Trailer
- Human: Fall Flat [PS4/XOne/PC] Coming Soon Trailer
- Battlefleet Gothic: Armada [PC] Eldar Trailer
- Neon Chrome [PS4/XOne/PC] PC Release Date Trailer
- Rocketbirds 2: Evolution [Vita/PS4] Launch Trailer
- Battleborn [PS4/XOne/PC] 12 Min Gameplay Trailer
- 7 Days to Die [PS4/XOne/PC] Console Trailer
- Total War: Warhammer [PC] The Empire vs Chaos Warriors Gameplay Trailer
- Umbrella Corps [PS4/PC] Mercenary Customization Trailer
- Niten [PC] Debut Trailer
- Stellaris [PC] Aiming for the Stars - Dev. Diary Trailer #1
- LawBreakers [PC] Dev Diary #4: Concept Art Evolutions
programming4us programming4us
Popular tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 windows Phone 7 windows Phone 8
programming4us programming4us
 
programming4us
Natural Miscarriage
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server
programming4us
Game Trailer