4. Your First Query
Ok, the time has come! You've hopefully learned some background or refreshed your memory about what databases and SQL queries are, you've learned about the data we're using in this course, and it's time to write some queries for yourself!
A Simple Query
Let's first consider this simple query:
select 'Hello world!' as column_name
This is perhaps the simplest valid SQL query that can be written. Let's break down its component parts:
select
tells the database that we want to execute aselect
statement, the result of which will be a table of some kind.'Hello world!'
wrapped in single quotes ('
) represents a literal string value, telling the database that we want everything between the single quotes to be treated as one continuous block of text, including the space between "Hello" and "world".as column_name
is a column alias telling the database that in the resulting table, the column name for our value,Hello world!
should becolumn_name
.
The result of this query will be a table with one column, column_name
, and one row with the value Hello world!
in that column.
The SQL Console
Below is an SQL console. You can type SQL queries into it and click "Submit", and you'll see the results of your query. The console is pre-populated with our simple select
statement. The table below the console shows the result of our query.
Exercise 1: Modify the column alias
In the SQL console above, modify the query so that the column in our results is named my_column
instead of column_name
.
Exercise 2: Modify the value
In the SQL console above, modify the query so that the value in our results is Some new value
instead of Hello world!
.
Selecting multiple columns
So far, we've selected only one column. To select multiple columns, separate them with commas (,
), like this:
select
'Hello world!' as first_column,
'A second value' as second_column
Exercise 3: Add a column
In the SQL console above, modify the query so that we are selecting three values: A first value
, A second value
, and A third value
with the columns named first_col
, second_col
, and third_col
, respectively.
Notice that in some of these examples, I've put each of the columns in my select statement on a new line, and I've indented those lines. None of this is required; SQL is not sensitive to whitespace (extra spaces, tabs, line breaks). From the database's point of view, these two queries are identical:
select 'Something' as my_column
select
'Something' as
my_column
Verify it for yourself by copy/pasting these queries into the SQL console or adding arbitrary whitespace to the queries you've written for the exercises above.
That said, for readability, it is common practice to place each column in your select
statement on its own line and to use indentation and standard spacing to keep your queries easy to read. This doesn't matter much for simple queries like these, but will become very important as your queries grow.