SQL for Beginners - Retrieving Your Data

In the last lesson we established a minimal foundation of SQL knowledge Now it's time to cover how you get data from your database using SQL.

SELECTing Data

In SQL, you don't GRAB data, you don't TAKE data, you certainly don't INHALE data (that could get you in trouble with the Feds). Sometimes you FETCH data, but that's an advanced use. Instead, you SELECT data.

Let's continue our patient chart example from the first lesson. Let's say we have a "Patients" table. For each patient, we're storing their first and last names, their heart rate (pulse), and the last date they were examined.

We might name our columns like so:

  • FirstName
  • LastName
  • Pulse
  • LastVisit

If we wanted to retrieve every chart and every bit of data for each chart, the SELECT statement would look like this:

SELECT * FROM Patients

Basically the asterisk (*) is a shortcut that means "all columns". So, for every record in our table, we'll be grabbing the FirstName, LastName, Pulse, and LastVisit columns. While using the asterisk (some call it a "splat") is faster to type, it is considered best practice to name each of the columns you want to return. So, let's rewrite our statement:

SELECT FirstName, LastName, Pulse, LastVisit FROM Patients

It's longer, but more explicit and maybe a tad more efficient. A key point to remember is that you must always tell the server what columns you want it to return - whether explicitly as we've been doing or implicitly via the asterisk shortcut.

The above SELECT statement might return data like this:

FirstName LastName Pulse LastVisit
John Smith 68 12/23/2012
Mary Blige 72 01/15/2013
Carlton Johnson 102 10/03/2012
Happy Tucker 78 05/28/2013

FYI: Lest our international readers get confused by the dates, I'm using US date formatting which is month/day/year

Notice I'm using the same order of columns that I defined in the table originally. It doesn't have to be this way. I could say:

SELECT LastName, LastVisit, Pulse, FirstName FROM Patients

The columns will be returned like so:

LastName LastVisit Pulse FirstName
Smith 12/23/2012 68 John
Blige 01/15/2013 72 Mary
Johnson 10/03/2012 102 Carlton
Tucker 05/28/2013 78 Happy

<< Foundations

  

Sorting Your Data >>