Select Query
With an intent of data manipulation, you really only have 4 types of SQL statements you can make: SELECT, INSERT, UPDATE, or DELETE. We will first discuss the only way to get information from a database using the SQL command SELECT. SELECT is probably the most common query that you will use. You probably are more concerned with displaying data to the user as opposed to getting data from them. Luckily in SQL, the SELECT statement has the easiest syntax to master. First up, we need some information to retrieve. Think of this following table as a table in your database that you just created. Now we are ready to perform master SQL ninja skills.
id | username | password | birthday |
---|---|---|---|
1 | bobdole32 | secretP | 1984-06-01 |
2 | rustyMeerkat | digholes | 1995-09-15 |
3 | theFlanders | kermit | 1955-09-15 |
SQL SELECT STATEMENT
So this is our default table. Nothing really too special about it. It is just a tiny little users table with a bad way to store passwords (you should look into hashing passwords if you plan to create a real users table). Now let's get some data from our table.
Example
SELECT username FROM table_name
Result
bobdole32 rustyMeerkat theFlanders
We already know that SELECT simply tells SQL we want to get information from the database. Then, username is just the name of the column that we want returned. So, if we would have put the column name as "id" we would have returned the 1, 2, and 3. You can add extra column names by putting a comma after the column before the new column name. Next, we have to tell SQL where to SELECT data with the FROM keyword, which just gives SQL a table name. That is one simple query, but let's get more specific.
WHERE Keyword
SQL has a built-in keyword WHERE that you can give a condition. Pseudo code here: WHERE column_name = "value". The WHERE keyword is another term you will use very often in your queries, because you probably don't want to work with every record in the table all the time. WHERE allows you to work with a selected set of records. Let's steal "theFlanders" password:
Example
SELECT password FROM table_name WHERE username = 'theFlanders'
Result
kermit
WHERE is fairly straightforward when you are searching for single exact matches. What if I had 2 or more conditions? We'll get into the more advanced stuff like that after we introduce all of the SQL Statements. All you would really need to do is add an AND or an OR after the WHERE statement. You can add as many as you want. Go ahead and go crazy.