Lesson 3

SQL Basic syntax

Case Sensitivity in SQL Statements and Objects

One of the key things that sets SQL apart from other programming languages is its general case insensitivity. For keywords like SELECT, FROM, WHERE etc, capitalization does not matter:

SeLeCt * FrOm Books WhErE Publish_Date > '2020-01-01';

This query searching books would run identically to:

select * from books where publish_date > '2020-01-01';

So SQL allows flexibility in formatting statement keywords. Capitalization conventions like CamelCase or lowercase are usually just for readability.

String comparison

When comparing string values in SQL using the WHERE clause or JOIN conditions, the default behavior is often case-insensitive. For example, 'john' and 'John' would be considered equal. However, this behavior can vary depending on the database system and collation settings.

Statement Termination with Semicolons

In SQL, each statement must be terminated with a semicolon ; symbol.

Without a semicolon, databases will fail to parse the full statement:

SELECT * FROM books WHERE price > 10 ORDER BY publish_date DESC
SELECT * FROM authors

This would error. The semicolon indicates the end:

SELECT * FROM books WHERE price > 10 ORDER BY publish_date DESC;
SELECT * FROM authors;

Now both statements will execute properly.

Indentation and Line Breaks

SQL statements can grow quite long with multiple clauses and nesting. Proper indentation and line breaks are key for readability.

For example:

SELECT CONCAT(c.first_name, ' ', c.last_name) AS customer_name, b.title, r.rating
FROM customers c
LEFT JOIN reviews r
    ON r.customer_id = c.customer_id
LEFT JOIN books b
   ON b.book_id = r.book_id
WHERE r.rating IS NOT NULL
ORDER BY c.first_name, c.last_name;

The indented JOIN clauses are much clearer to parse than cramming onto one line. Consistent indentation also helps when modifying complex queries.

Commenting Code

Comments documenting sections of SQL code or explaining logic should always be included:

SELECT c.first_name, o.order_date, o.total_amount
FROM customers c
INNER JOIN orders o
    ON c.customer_id = o.customer_id
WHERE o.order_date BETWEEN '2023-01-01' AND '2023-04-30'
ORDER BY c.first_name;

Comments like above help future developers understand the purpose of code segments without having to decipher complex logic themselves.

No Data

©2024 SQLZap - Learn SQL Interactively

Twitter