SQL: Using SELECT and FROM Clause

These are some of the common statements in SQL.   We store data for a reason and it might be important for us to use later.  It can be important to our business or us personally.

Querying is all about asking questions

We can pretend that another human knows everything and has it stored in the form of data.  I believe that SQL can be postulated in English.  If we understand the mapping of English and SQL, it will make learning SQL much easier.

What are some example questions you can ask?

  • Who are all my contacts?
  • How many contacts do I have?
  • Which of my contacts are the oldest?

How to use SELECT?

  • SELECT is a list of items you want in a set
  • SELECT determines the shape of the result set
  • SELECT contains a set of variables that can be the end of the query
  • SELECT will contain a list of columns from a table (more common)
  • if you are querying columns from a table you will need a FROM clause after a SELECT list
  • after every column comes a comma, except the last column in the list

Syntax:

SELECT <COLUMN_NAME>, <COLUMN_NAME> FROM <TABLE_NAME>;

Example query in our contacts database:

SELECT person_first_name, person_last_name FROM person;

What if I want all the columns?

Yes, it’s possible with the Wildcard character by using *.

Wildcard * 

  • is useful but very dangerous and inefficient!!
  • inefficient because the database will need to look up every column
  • dangerous because the order of the columns might change and break the code depending on the order of the column
  • it will break applications

 

Using FROM clause

Using FROM is easy because…

Syntax:

FROM <TABLENAME>

Note:  You should qualify the columns in the select list with the Table’s name.  This will avoid column name collision later if you add other tables to the query (which might have a column with the same name).

<TABLENAME.COLUMNNAME>

  • You can alias your table name in the FROM clause, so your table name will be shorter and hence you don’t need to type out the whole name

Example:

What are the first names of all the people in my contact list?

SELECT p.person_first_name FROM person p;

 

Stay tuned next time for…

  • How to use WHERE clause?

Thanks for reading!

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s