SQL
by Chris Fehily
Copyright 2015 by Questing Vole Press. All rights reserved.
Editor: Kevin Debenjak
Proofreader: Pat Kissell
Compositor: Hiromi Yamada
Cover: Questing Vole Press
By the Same Author
SQL Tricks
SQL Short Course
For a complete list of titles, go to questingvolepress.com.
Contents
Introduction
SQL (pronounced es-kyoo-el ) is the standard programming language for creating, updating, and retrieving information thats stored in databases. With SQL, you can turn your ordinary questions (Where do our customers live?) into statements that your database system can understand ( SELECT DISTINCT city, state FROM customers; ). You might already know how to extract this type of information by using a graphical query or reporting tool, but perhaps youve noticed that this tool becomes limiting or cumbersome as your questions grow in complexity thats where SQL comes in.
You also can use SQL to add, change, and delete data and database objects. All modern relational database management systems (DBMSs) support SQL, although support varies by product (more about that later in this introduction).
Database vs. DBMS
A database is not the same as the database software that youre running; its incorrect to say, Oracle is a database. Database software is called a database management system ( DBMS ). A database , which is just one component of a DBMS, is the data itself that is, its a container (one or more files) that stores structured information. Besides controlling the organization, integrity, and retrieval of data in databases, DBMSs handle tasks such as physical storage, security, backup, replication, and error recovery.
DBMS also is abbreviated RDBMS , in which the R stands for relational . An RDBMS organizes data according to the relational model (see ) rather than, say, a hierarchical or network model. This book covers only relational systems, so when I use DBMS , the initial R is implied.
About SQL
SQL is:
- A programming language
- Easy to learn
- Declarative
- Interactive or embedded
- Standardized
- Used to change data and database objects
- Not an acronym
A programming language. SQL is a formal language in which you write programs to create, modify, and query databases. Your database system executes your SQL program, performs the tasks youve specified, and displays the results (or an error message). Programming languages differ from natural (spoken) languages in that programming languages are designed for a specific purpose, have a small vocabulary, and are inflexible and utterly unambiguous. So if you dont get the results you expect, its because your program contains an error or bug and not because the computer misinterpreted your instructions. (Debugging ones programs is a cardinal programming task.)
SQL, like any formal language, is defined by rules of syntax , which determine the words and symbols you can use and how they can be combined, and semantics , which determine the actual meaning of a syntactically correct statement. Note that you can write a legal SQL statement that expresses the wrong meaning (good syntax, bad semantics). introduces SQL syntax and semantics.
Easy to learn. Easy compared with other programming languages, that is. If youve never written a program before, youll find the transition from natural to formal language frustrating. Still, SQLs statements read like sentences to make things easy on humans. A novice programmer probably would understand the SQL statement SELECT au_fname, au_lname FROM authors ORDER BY au_lname; to mean List the authors first and last names, sorted by last name, whereas the same person would find the equivalent C or Perl program impenetrable.
Declarative. If youve never programmed, you can skip this point without loss of continuity. If youve programmed in a language such as C or Javascript, youve used a procedural language , in which you specify the explicit steps to follow to produce a result. SQL is a declarative language , in which you describe what you want and not how to do it; your database systems optimizer will determine the how. As such, standard SQL lacks traditional control-flow constructs such as if-then-else, while, for, and goto statements.
To demonstrate this difference, Ive written programs that perform an equivalent task in Microsoft Access Visual Basic (VB; a procedural language) and SQL. shows how to do the same task with a single SQL statement (as opposed to about 20 lines of VB code). With SQL, you specify only what needs to be accomplished; the DBMS determines and performs internally the actual step-by-step operations needed to get the result.
Listing i.1 This Microsoft Access Visual Basic routine extracts the first and last names from a database table containing author information and places the results in an array.
Sub GetAuthorNames()
Dim db As Database
Dim rs As Recordset
Dim i As Integer
Dim au_names() As String
Set db = CurrentDb()
Set rs = db.OpenRecordset("authors")
rs.MoveLast
ReDim au_names(rs.RecordCount - 1, 1)
With rs
.MoveFirst
i = 0
Do Until .EOF
au_names(i, 0) = ![au_fname]
au_names(i, 1) = ![au_lname]
i = i + 1
.MoveNext
Loop
End With
rs.Close
db.Close
End Sub
Listing i.2 This single SQL statement performs the same query as the Visual Basic routine in . Accesss internal optimizer determines the best way to extract the data.
SELECT au_fname, au_lname
FROM authors;
Moreover, is a trivial SQL query. After you add common operations such as sorts, filters, and joins, you might need more than 100 lines of procedural code to accomplish what a single SQL SELECT statement can do.
Interactive or embedded. In interactive SQL, you issue SQL commands directly to your DBMS, which displays the results as soon as theyre produced. DBMS servers come with both graphical and command-line tools that accept typed SQL statements or text files that contain SQL programs (scripts).
If youre developing database applications, you can embed SQL statements in programs written in a host language , which commonly is a general-purpose language (C++, Java, or COBOL, for example) or a scripting language (Perl, PHP, or Python). A PHP CGI script can use an SQL statement to query a MySQL database, for example; MySQL will pass the query result back to a PHP variable for further analysis or webpage display. Drawing from the preceding examples, Ive embedded an SQL statement in an Access Visual Basic program in .
Listing i.3 Here, Visual Basic serves as the host language for embedded SQL.
Sub GetAuthorNames2()
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb()
Set rs = db.OpenRecordset(" SELECT au_fname, au_lname FROM authors; ")
' --Do something with rs here.
rs.Close
db.Close
End Sub
This book covers only interactive SQL. In general, any SQL statement that can be used interactively also can be used in a host language, though perhaps with slight syntactic differences, depending on your DBMS, host language, and operating environment.
Standardized. SQL isnt owned by any particular firm. Its an open standard defined by an international standards working group, under the joint leadership of the International Organization for Standardization (ISO) and the International Engineering Consortium (IEC). The American National Standards Institute (ANSI) participates in the working groups and has ratified the standard ( in Chapter 3.