SQL source code

SQL is written in plain text and the keywords have much the same meaning as in natural language. By convention, SQL keywords (such as SELECT, FROM, JOIN, and so on) are often written in capitals but this is not required; names of objects such as tables and columns are often case-sensitive, depending on the RDBMS. A semicolon terminating SQL statements is not required in all flavors of SQL but is in the ANSI SQL standard, will work in all SQL varieties and its use is preferred by many SQL programmers even where it is not required.

SQL ignores excess whitespace, allowing the use of indentation; while indentation is not required in SQL, it is often used to make code more readable. While there is no "official" standard for indentation, it is good to be consistent with your own indentation rules.

An example of SQL source code: by the end of this topic, you should be able to understand and also write queries such as these. Note the use of indentation to make the query clearer.

You can probably guess what this query does; it gets the instruments and measurement units for all the instruments whose model begins with "Magnotron2016". Before we dive into learning how to write queries like this in SQL, a few things to note. Firstly, the use of commas immediately before items in a list is fairly common; the list contents are often changed and associating commas, which are the list separator, with the items they precede will mean fewer syntax errors when removing or adding items. Also note the use of aliases for the table names; it's much easier to write the qualifiers S and R than the full table names. The qualifiers are not always needed as, contextually, if a column name can only refer to one item, most RDBMSs will work it out without needing the table specified, but for readable and extensible code it is good practice to always include qualifiers. Finally, note that the query ends with a semicolon!

In this module, we will large draw examples from the database designed in the designing databases topic.

 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement