SQL - Syntax
SQL follows a general syntax, there are not many quotations or other symbols to throw into your statements. Generally we follow a Do what To what syntax, meaning first we decide what we want to do, then we decide what we want to do it to, and finally we end the whole thing with a semicolon (;).
A statement begins with a clause. Clauses are commands in the SQL world and the backbone of any script. The first clause of a statement gives a general idea of what type of action a script is taking. A few basic clauses are SELECT, INSERT, or CREATE. We will look at each of these clauses a little more in depth on the next few pages but it may be obvious to you already what each of those clauses does. SQL statements end with a semicolon as most with most programming languages. A basic statement might look like this:
SQL Code:
SELECT * FROM table_name;
Above we have a SELECT clause asking for all columns and values (*) from our database table. As shown above, a good habit is to capitalize your clauses. Later on when we have larger statements and subqueries it will make life much easier to go back and debug your code.
Formating your statements in a similar fashion will also aid your debugging efforts. The common formatting technique is to begin each line with a clause or to break up and list columns or tables as needed. More on this in a moment.
SQL Code:
SELECT *
FROM table_name;
The advantage of this isn't apparent with this example. Each are fairly easy to read. However the example below shows an example where this format shines.
SQL Code:
SELECT column_one, column_two
FROM table_name
WHERE (
column_one,
column_two,
column_three,
)
= (SELECT column_one,
column_two
FROM table_two
WHERE table_one.id = 'table_two.id');
As you can see, when subqueries are thrown into the mix things become a little more complicated. A one line statement will not fit across your screen. Both statements are neither right nor wrong, each are easier to follow. Parentheses generally depict order of operations but it is not an exact science. Quotations are not found until the predicate of the statement.
Tips
- When referring to a table, table column, or table data we must match the case (upper or lower) of each character.
|