SQL - Queries
Queries are the backbone of SQL. Query is a loose term that refers to a widely available set of SQL commands called clauses. Each clause (command) performs some sort of function against the database. For instance, the create clause creates tables and databases and the select clause selects rows that have been inserted into your tables. We will dive deeper in detail as this tutorial continues but for now let's take a look at some query structure.
Query construction begins with one of the following clauses:
- Add
- Drop
- Create
- Insert
- Select
- Update
- Replace
- Delete
Queries are loosely typed into your SQL prompt. Spacing and line breaks are not very important as we will discuss further in our SQL Syntax lesson. We now know that a query begins with a clause, what comes next depends on the clause we select and we will be covering all the clauses as the tutorial progresses. For now, let's take a look at some syntax.
SQL - Query Syntax
The syntax of a query is loose, meaning you are free to place line breaks where you please without injuring the code. Few instances require parentheses, including the insert statement listed below. Parentheses will also be covered during our Functions lesson. Be sure to end all query statements with a semicolon (;).
SQL Code:
SELECT * FROM table_name;
The above code selects every row and every column from a hypothetical table (table_one) and prints it to our prompt. Here's a look at a few more queries that should become second nature to you as the tutorial coninues.
SQL Code:
INSERT INTO table_name (column_one,column_two)
VALUES(value_one,value_two);
SQL Code:
UPDATE table_name SET column_one = value_one, column_two = value_two;
Queries are how you communicate to your database program. Nearly everything typed at a SQL command prompt is a query.
SQL - What are Subqueries: Advanced Queries
Subqueries can be performed inside of existing queries. This expands the capabilities of SQL in a number of ways providing a 3rd dimension to the language you might say. Again, we will discuss subqueries in more detail in a later lesson. Feel free to familiarize yourself with what a subquery may look like using the example below.
SQL Code:
SELECT * FROM table_one WHERE unique_column =
(SELECT unique_column FROM table_two WHERE id_column = 1)
Above is a look at where you might cross subqueries. The logic behind the entire query is fairly confusing at this point, try and stay with us and focus on the syntax of the query and subquery.
|