Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
A given table may have a lot of columns and you will often be interested in only some of them fortunately, selecting particular columns is easy and here is how it's done. Here I have SID opening my browser and I'm going to select the world database, and if I just select like this, SELECT * FROM Country ORDER BY Code; and I'll press the Go button. You see we get all 239 rows.
And we also get all of the columns, if I scroll off to the side here, you see there's even more. The asterisk is in the place where you would list the columns you wanted returned by the query the asterisk is simply the wildcard that means all of the columns. You can select particular columns by listing them in the Select statement in the place where the asterisk is. So if I come over here I can say Name, Code, Region, Population, and I press Go.
And I just get those columns, Name, Code, Region, and Population in the order that I specified them in the SELECT statement. If you would like to return different names in your column headers, you can do so with the AS clause after the column name like this. I could say Name AS Country. I could say Code AS ISO, because that's an ISO code. I could say population AS Pop, like that and if I press Go, you see now we have country, ISO, region, pop in our headers.
Now, the column headers are actually the names returned by the database interface, so they're commonly used in your code. They're also used in SQL to specify intermediate results. So the AS clause can be important in preventing namespace collision. You'll see more examples of this later in the course. It's also worth noting that the AS clause is often omitted. If I take out the word AS and just list the other name right next to the column name, it has exactly the same result.
So the AS keyword is optional, I very much prefer to use the AS keyword, because it makes the code more readable. It makes it more obvious what's going on and also if I were to happen to list two columns and simply forget the comma, but I have this AS clause here, it comes up as a syntax error and I get an error. But if I don't have the AS clause there, then what I'll get is the name column with the word Code at the top of it.
So, using the AS clause all the time, it's much less ambiguous. And it's much more clear what you mean and it's actually even less prone to error. So, I suggest that you always use the AS keyword although you need to be aware that you'll see a lot of code out there where people omit the AS keyword. I think it's lazy to do so and I wish it was required personally. So it's easy to select particular columns from a table in SQL, this is a feature you'll use a lot, and you'll see a lot in this course.
Get unlimited access to all courses for just $25/month.Become a member