Site icon Analytics4All

SQL: SELECT Statement

Advertisements

 

SELECT is doubtlessly the most important command in SQL. A database is completely useless unless you can query the data it is holding. SELECT is how we query.


If you want to follow along:

You will need MS SQL Server installed. Here is a link to instructions: InstallSQL

Microsoft provides a great sample database known as Adventure Works. I am working with the 2012 release. You can download it here: AdventureWorksDownload


Once you have Adventureworks downloaded, you will need attach it to SQL Server.

Copy and paste the download file to somewhere you can find it. I recommend:

C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA

** the portion in red changes based on what version of SQL Server you downloaded. 

Open SQL Server Management Studio. Windows Key + R – Type SSMS

Login to your server

Go to Object Explorer – Right Click Database > Attach…

Click Add…

Select Adventureworks2012_Data.mdf

In the bottom window, highlight the log file and click Remove. Then Click Okay

Go back to Object Explorer. Expand Databases > AdventureWorks2012 > Tables

Just picking a table at random, I selected HumanResources.Employee. Let us see what is in the table. Click the New Query button up top, and a new query window will open.

Make sure you are working with the right database. Select AdventureWorks2012 from the drop down:

Cut and Paste the following into the new query window.


select *
from HumanResources.Employee
go

select JobTitle, BirthDate, Gender, HireDate
from HumanResources.Employee
go

select JobTitle as Job, BirthDate as DOB, Gender, HireDate as [Start Date]
from HumanResources.Employee
go

select HireDate as [Start Date], JobTitle as Job, BirthDate as DOB, Gender
from HumanResources.Employee
order by HireDate
go
select HireDate as [Start Date], JobTitle as Job, BirthDate as DOB, Gender
from HumanResources.Employee
where gender like ‘F’
order by HireDate
go


 

One cool thing about SQL code is that you can select only the  code you want to execute

Highlight the first group of code and click the ! Execute button

Syntax

Notice the results show every field in the table. It displays in a spreadsheet like table

Now Select the next code group  and click ! Execute

Syntax

Results show the 4 columns selected above

Next block of code – click ! Execute

Note the column names have changed

Next block of code – click ! Execute

syntax

Notice Start Date(HireDate) is now the first column and the records (rows) are sorted in order from oldest Start Date to newest

FInal block of code – click ! Execute

Syntax

Note now only Female employees are in the results


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more SQL content: SQL

Exit mobile version