Tuesday, February 5, 2013

SQL: Toddlers Query (Select Statement)


As a beginner, basic is always the core foundation of being the best among the rest.

I’ve listed down some of the basic query that you might want to know in T-SQL Scripting.

SELECT and FROM CLAUSE

SELECT Statement is the most basic and widely known of the four query statement.” But logically it is the FROM clause which is the first one to process the query.” (Quering Microsf SQL Server 2012 – by: Itzik Ben – Gan; Dejan Sarka and Ron Talmage) The SELECT statement allows you to view records from a Table.

                SELECT columns FROM TableName WHERE predicate;

Example:

                Sample you have a Database name “RutherRoque” with table1, table2 and table3. And under table1 we have column1, column2, column3 …. Column n..

Let’s name table1 as “Friends” and column1 “FirstName”, column2 “LastName”, column n…

FirstName
LastName
Country
City
Mel
Jacob
Philippines
Quezon
CJ
Samuel
Philippines
Valenzuela
Jasmin
Tyler
Philippines
Quezon
Fred
Dylan
Philippines
Novaliches
Joseph
Jonathan
Philippines
Pasig
Jennifer
Caleb
USA
Corona

 
                RutherRoque = Database Name
                Friends = Table Name (Table1)

Start SSMS and connect to your SQL Server Instance then type the following Select statements below:

                SELECT * FROM Friends; (The sample SELECT statement will view all the column records under Friends Table.)

FirstName
LastName
Country
City
Mel
Jacob
Philippines
Quezon
CJ
Samuel
Philippines
Valenzuela
Jasmin
Tyler
Philippines
Quezon
Fred
Dylan
Philippines
Novaliches
Joseph
Jonathan
Philippines
Pasig
Jennifer
Caleb
USA
Corona

    

SELECT FirstName FROM Friends;

(This will only view records from FirstName Column)

FirstName
Mel
CJ
Jasmin
Fred
Joseph
Jennifer


                SELECT FirstName, LastName, Country FROM Friends;

(This will view records from column FirstName, LastName and Country.)

FirstName
LastName
Country
Mel
Jacob
Philippines
CJ
Samuel
Philippines
Jasmin
Tyler
Philippines
Fred
Dylan
Philippines
Joseph
Jonathan
Philippines
Jennifer
Caleb
USA

 

                SELECT FirstName, LastName, City FROM Friends WHERE Country = ‘Philippines’;

(This will view records from FirstName, LastName, City where country is filtered by Philippines)

FirstName
LastName
Country
City
Mel
Jacob
Philippines
Quezon
CJ
Samuel
Philippines
Valenzuela
Jasmin
Tyler
Philippines
Quezon
Fred
Dylan
Philippines
Novaliches
Joseph
Jonathan
Philippines
Pasig

 
Note: (*) asterisk – means to view all records in a table.

Reference:
Quering Microsf SQL Server 2012 – by: Itzik Ben – Gan; Dejan Sarka and Ron Talmage

No comments:

Post a Comment