SQL
From Wikibooks, the open-content textbooks collection
- See also: MySQL for a thorough look at one SQL variant.
Contents |
[edit] Introduction
[edit] Relational Databases
The main drive behind a relational database is to increase accuracy by increasing the efficiency with which data is stored. For example, the names of each of the millions of people who immigrated to the United States through Ellis Island at the turn of the 20th century were recorded by hand on large sheets of paper; people from the city of London had their country of origin entered as England, or Great Britain, or United Kingdom, or U.K., or UK, or Engl., etc. Multiple ways of recording the same information leads to future confusion when there is a need to simply know how many people came from the country now known as the United Kingdom.
The modern solution to this problem is the database. A single entry is made for each country, for example, in a reference list that might be called the Country table. When someone needs to indicate the United Kingdom, he only has one choice available to him from the list: a single entry called "United Kingdom". In this example, "United Kingdom" is the unique representation of a country, and any further information about this country can use the same term from the same list to refer to the same country. For example, a list of telephone country codes and a list of European castles both need to refer to countries; by using the same Country table to provide this identical information to both of the new lists, we've established new relationships among different lists that only have one item in common: country. A relational database, therefore, is simply a collection of lists that share some common pieces of information.
If you are not familiar with the concepts of databases, you can begin with Database Programming. For more technical information on different software applications that allow users to create databases, see the Wikipedia article Relational database management system (RDBMS)s.
[edit] Structured Query Language (SQL)
SQL, which is an initialism for Structured Query Language, is a language to request data from a database, to add, update, or remove data within a database, or to manipulate the metadata of the database.
SQL is generally pronounced as the three letters in the name, e.g. ess-cue-ell, or in some people's usage, as the word sequel.
SQL is a declarative language in which the expected result or operation is given without the specific details about how to accomplish the task. The steps required to execute SQL commands are handled transparently by the SQL database. Sometimes SQL is characterized as non-procedural because procedural languages generally require the details of the operations to be specified, such as opening and closing tables, loading and searching indexes, or flushing buffers and writing data to filesystems. Therefore, SQL is considered to be designed at a higher conceptual level of operation than procedural languages because the lower level logical and physical operations aren't specified and are determined by the SQL engine or server process that executes it.
Instructions are given in the form of commands, consisting of a specific SQL command and additional parameters and operands that apply to that command. The simplest example of how to retrieve all of the rows and columns of a table named Customers is:
SELECT * FROM Customers |
The asterisk (*) that follows the SELECT command is a wildcard character that refers to all of the columns of the table. SQL assumes that the whole set of records is to be retrieved unless you provide conditional logic to restrict the result to a subset, which is added using a WHERE clause. Following are a few typical SQL examples for a table named Customers with three columns: CustomerID, LastName, and FirstName.
SELECT LastName, FirstName FROM Customers WHERE CustomerID=99 Returns the last name and first name of the customers that have a CustomerID value of 99. Typically this will return a single row, if it exists, because values such as CustomerID would be defined as a primary key that uniquely identifies one customer and cannot have other rows identified with the same value |
SELECT LastName, FirstName FROM Customers ORDER BY LastName, FirstName Returns an alphabetized list of the last and first names of all customers |
INSERT INTO Customers (CustomerID, LastName, FirstName) Values (1, "Doe", "John") Creates a row with the CustomerID of 1 for John Doe. |
UPDATE Customers SET FirstName="Johnny" WHERE CustomerID=1 Changes John Doe's first name to Johnny |
DELETE Customers WHERE CustomerID=1 Removes the row where the CustomerID is the value 1 |
In general, SQL isn't case sensitive and ignores excess whitespace characters, except for the contents of an alphanumeric string. Upper case is frequently used for SQL commands as a matter of style, but this is not a universal convention.
Some databases support stored procedures in which SQL is embedded within another procedural language to manipulate data or tables on the server for more complex operations than allowed by SQL alone, and without necessarily returning data from the server. These procedural languages are usually proprietary to the vendor of the SQL server. For example, Oracle uses its own language PL/SQL while Microsoft SQL Server uses T-SQL. These procedural languages are similar in design and function, but use different syntax that are not interoperable.
SQL can also be embedded within other languages using SQL modules, libraries, or pre-compilers that offer functions to open a path of communication to the SQL server to send commands and retrieve results. Since the execution of an SQL command is a useful service that is performed externally to the host language by the SQL server, the overall processing is divided into two tiers: the client tier and the server tier. The modules and libraries used to provide the connection between the client and server are usually referred to as middleware, particularly when connections are allowed with one interface from the client to various servers from different vendors. ODBC, JDBC, OLEDB are common middleware libraries, among a large number of others specific to a wide range of client hosting operating systems and programming models. The use of SQL has become so prevalent that it would be unusual to find an application language that doesn't support it in some manner.
SQL commands and their modifiers are based upon official SQL standards and certain extensions to that each database provider implements. Commonly commands are grouped into the following categories:
- Data Definition Language ( DDL )
- CREATE - Used to create a new table, a view of a table, or other object in database.
- ALTER - Used to modify an existing database object, such as a table.
- DROP - Used to delete an entire table, a view of a table or other object in the database.
- Data Control Language ( DCL )
- GRANT - Used to give a privilege to someone.
- REVOKE - Used to take back privileges granted to someone.
- Data Manipulation Language ( DML )
- INSERT - Used to create a record.
- UPDATE - Used to change certain records.
- DELETE - Used to delete certain records.
- Data Query Language ( DQL )
- SELECT - Used to retrieve certain records from one or more tables.
[edit] Getting a database to work with
You will need a database system to work with. Popular database systems are listed as RDBMSes in Wikipedia. Among them are:
- PostgreSQL and MySQL (Wikibook), two free and Open-Source database systems for Linux, Mac OS X, Windows
- SQLite, a small-scale public domain embedded client/server that may also be used. The primary benefit is the zero configuration required to run it, and each database is a single file
- Oracle, IBM DB2 and Microsoft SQL Server are three popular commercial systems.
Once installed there are many ways to enter SQL commands. Common ways include a command-line-interface tool such as psql or a text-box inside a graphical-user-interface tool such as pgAdminIII.
SQL commands are often stored together in text files or embedded in source code so a text editor is recommended.
[edit] Data Definition
The data definition statements are used to CREATE, to ALTER and to DROP the tables that contain data.
[edit] Tables, rows and columns
The easiest and most fun way I find to think about database structure is to compare it to a spreadsheet.
Think of the entire spreadsheet as a representation of the database. A sheet in a spreadsheet is the same as a table in a database. Just as each sheet in a spreadsheet has columns and rows, so does a table.
Columns in database tables are the type of each bit of data contained in a row.
Think of a row of data like a sentence. A sentence has different words of different types (nouns, adjectives, etc) likewise a column can be a different type. Different column types include (but are not limited to) integer, varchar (that is a variable number of characters - so VARCHAR(20) would be able to contain up to 20 ASCII values), date or blob (binary large object).
[edit] Creating Tables
Example code for a table that describes the produce section of the grocery store:
CREATE TABLE fruit (
fruit_name TEXT,
price_per_pound NUMERIC,
quantity_available NUMERIC
);
This would produce an empty table that has field names of fruit_name, price_per_pound and quantity_available. Their type is also specified and any data entered must be of that type.
[edit] Foreign Keys
In most database systems, you can specify that values in one column match values in a column in another table. For example, you have a table that tracks all the dog owners in the neighborhood:
| owner | dog name | dog breed |
|---|---|---|
| Joe Smith | Rex | mastiff |
| Rosa Gomez | Gato | chihuahua |
| Smitty Jones | Spot | mastiff |
And let's say you have another table that describes the attributes of different dog breeds:
| dog breed | average size | poop description |
|---|---|---|
| mastiff | enormous | horrible; will kill most grasses and flowers. |
| chihuahuah | tiny | surprisingly pungent |
Ok, so you want to make sure that when you add new neighbors to the list, you only add valid dog breeds off your dog breed table. You can use the following sql code to enforce that:
CREATE TABLE dog_types (
dog_breed TEXT,
average_size TEXT,
poop_description TEXT
);
CREATE TABLE dog_owners (
owners TEXT,
dog_name TEXT,
dog_breed TEXT REFERENCES dog_types
);
This is a foreign key in SQL jargon. There are much more interesting applications than this.
[edit] Exercise
Write a set of tables that a teacher can use to create an online multiple-choice testing program. One table will hold questions and the answer_id of the correct answer. Another table will hold a list of answers. A third table will hold the available answers for each question.
For example, imagine two questions exist in the question table:
1. what is 6 * 30? 2. who was the first US president?
And imagine the following four answers exist in the answer table:
1. 45 2. George Washington 3. Thomas Jefferson 4. 180
Now create a third table that lists answers one and four as possible answers for question 1 and answers 2 and 3 for question 2.
Got it?
[edit] Exercise solution
This program illustrates one use of a compound foreign key constraint. I needed a way to track answers to multiple-choice questions, and to limit possible answers to each question. For example, I want to make sure that if I ask the question "what is your favorite color?" then the answer is a color, and not something silly like "yes."
This table holds each question:
CREATE TABLE questions (
q_id SERIAL PRIMARY KEY,
q_text TEXT
);
Here are some questions. Since I used the serial data type, I'm not going to assign the q_id column. Postgresql will assign the q_id automatically.
INSERT INTO questions (q_text) VALUES ('What is your favorite color?'); /* q_id 1 */
INSERT INTO questions (q_text) VALUES ('Is it raining outside?'); /* q_id 2 */
After inserting, let's see what the database looks like now:
SELECT * FROM questions;
This results in:
| q_id | q_text |
|---|---|
| 1 | What is your favorite color? |
| 2 | Is it raining outside? |
Now, create a table which lists every possible answer, each with a unique id:
CREATE TABLE all_answers ( a_id SERIAL PRIMARY KEY, a_text TEXT );
These are some answers:
INSERT INTO all_answers (a_text) VALUES ('red'); /* a_id 1 */
INSERT INTO all_answers (a_text) VALUES ('yes'); /* a_id 2 */
INSERT INTO all_answers (a_text) VALUES ('green'); /* a_id 3 */
INSERT INTO all_answers (a_text) VALUES ('no'); /* a_id 4 */
Here's what all_answers looks like after adding data:
SELECT * FROM all_answers;
Result:
| a_id | a_text |
|---|---|
| 1 | red |
| 2 | yes |
| 3 | green |
| 4 | no |
This table links each question to meaningful possible answers. I am using question ID (q_id) and answer ID (a_id) numbers in order to save space.
CREATE TABLE possible_answers (
q_id INTEGER REFERENCES questions (q_id),
a_id INTEGER REFERENCES all_answers (a_id),
primary key (q_id, a_id)
);
Now, I'll link certain questions with certain answers:
INSERT INTO possible_answers (q_id, a_id) VALUES (1, 1);
This statement linked 'What is your favorite color?' with 'red'.
INSERT INTO possible_answers (q_id, a_id) VALUES (1, 3); INSERT INTO possible_answers (q_id, a_id) VALUES (2, 2); INSERT INTO possible_answers (q_id, a_id) VALUES (2, 4);
The last statement linked 'Is it raining outside?' with 'no'.
And, just to continue the trend...
SELECT * FROM possible_answers;
| q_id | a_id |
|---|---|
| 1 | 1 |
| 1 | 3 |
| 2 | 2 |
| 2 | 4 |
Finally, this is the table that will record the actual answer given for a question and make sure that the answer is appropriate for the question:
CREATE TABLE real_answers ( q_id INTEGER REFERENCES questions (q_id), a_id INTEGER REFERENCES all_answers (a_id), FOREIGN KEY (q_id, a_id) REFERENCES possible_answers (q_id, a_id) );
Now, watch what happens when I try to insert an answer that doesn't match the question into the database. I'm going to try to answer the question:
"What is your favorite color?"
with the answer
"yes"
Hopefully the database will prevent me.
SELECT q_text FROM questions WHERE q_id = 1;
Result:
| q_text |
|---|
| What is your favorite color? |
SELECT a_text FROM all_answers WHERE a_id = 2;
Result:
| a_text |
|---|
| yes |
INSERT INTO real_answers (q_id, a_id) VALUES (1, 2);
Database answer:
ERROR: $3 referential integrity violation - key referenced from real_answers not found in possible_answers
Hurray! We are prevented from entering the data! Now, let's try storing an acceptable answer.
INSERT INTO real_answers (q_id, a_id) VALUES (1,1);
Database answer:
INSERT 17196 1
That means it worked!
[edit] Data Manipulating
[edit] Adding Data
The insert statement adds new records.
Extending the fruit store metaphor:
INSERT INTO fruit ( fruit_name, price_per_pound, quantity_available ) VALUES ('apples', 0.90, 400);
INSERT INTO fruit ( fruit_name, price_per_pound, quantity_available ) VALUES ('bananas', 0.59, 800);
SELECT * FROM fruit;
| fruit_name | price_per_pound | quantity_available |
|---|---|---|
| bananas | 0.59 | 800 |
| apples | 0.90 | 400 |
[edit] Removing Data
The DELETE statement removes existing records.
DELETE FROM fruit;
Deletes every row in table fruit.
DELETE FROM fruit WHERE fruit_name = 'pears';
Deletes every fruit named pears in table fruit.
[edit] Updating Data
The UPDATE statement changes existing records.
UPDATE fruit SET QUANTITY = 200 WHERE fruit_name = 'apples';
This query changes every fruit named apples, to give it a quantity of 200.
[edit] Data Querying
[edit] Retrieving Data
All data retrieval is via a SELECT statement. A SELECT statement will return a new table, and the statement describes the rows and columns of the table. The statement basically answers three questions: what will the new table's columns be, what will its rows be, and where will the data come from.
The basic structure is as follows:
SELECT FirstColumnName (, SecondColumnName...)
FROM FirstTableName (, SecondTableName...)
WHERE FirstCondition (AND SecondCondition...)
ORDER BY colname (, colname,...);
The first line, SELECT FirstColumnName, SecondColumnName, ... tells us what the columns of the table will be. The next line, FROM FirstTableName, SecondTableName, ... tells us where the data will be pulled from. The remainder of the query — usually WHERE FirstCondition AND SecondCondition ... — specifies a list of conditions which will be true for every output row.
For example if a table named pets has a field, PetID, and a field, PetName,
SELECT * FROM pets;
would print out the entire table.
SELECT PetName FROM pets;
would print out only the names, and
SELECT PetName FROM pets WHERE PetID=1;
would print out only the name of the pet in the table whose ID number was 1.
[edit] Joins
The power of relational databases is that they allow us to "JOIN" different tables together and view associated information.
[edit] Inner Join
If we have two tables Pet_Types and Pet_Owners, and they look like this:
Pet_Types (Pet_Type_ID [primary key], Breed, Characteristic)
Pet_Owners (Owner_ID [primary key], Owner_Name, Pet_Type_ID)
Let us say that we are looking for humans who own yappy dogs:
What we do is an inner join on Pet_Types and Pet_Owners ON the column which is the same.
SELECT Owner_name FROM Pet_Types INNER JOIN Pet_Owners ON Pet_Types.Pet_Type_ID = Pet_Owners.Pet_Type_ID WHERE Pet_Types.Characteristic= 'yappy';
How this query is processed: first, since it specified two tables, a new table would be generated that includes every combination of one row from the first table and one row from the second. If there are 8 rows in the first and 5 in the second, then this joined table would include 8x5=40 rows. Most of these rows are just noise. The only ones which make sense are the ones for which the breed in the first and the breed in the second match, so the ON Pet_Types.Pet_Type_ID = Pet_Owners.Pet_Type_ID tells the engine to throw out every row for which the Pet_Type_IDs don't match. Within this much smaller and much more coherent table, we want only those rows for which Pet_Types.Characteristics="yappy". Within those rows (if any), we ask to see the Owner column.
[edit] Outer Join
If we have two tables Pet_Types and Pet_Owners, and they look like this:
Pet_Types (Pet_Type_ID [primary key], Breed, Characteristic)
Pet_Owners (Owner_ID [primary key], Owner_Name, Pet_Type_ID)
Let us say that we are looking for all humans, and any dogs that they own, still listing a human that does not own a dog.
What we can do is an outer join on Pet_Types and Pet_Owners ON the column which is the same.
SELECT Owner_name, Breed FROM Pet_Types RIGHT OUTER JOIN Pet_Owners ON Pet_Types.Pet_Type_ID = Pet_Owners.Pet_Type_ID;
This query is processed just like the Inner Join but the result set will contain all records from the Pet_Owners table (the right side of the join) even if there is no matching Pet_Type_ID in the Pet_Types table. The Breed name for these records will be null.
Alternatively we can look for all pet types, also adding human owners where they exist.
SELECT Owner_name, Breed FROM Pet_Types LEFT OUTER JOIN Pet_Owners ON Pet_Types.Pet_Type_ID = Pet_Owners.Pet_Type_ID;
This time the result set will contain all records from the Pet_Types table (the left side of the join) even if there is no matching Pet_Type_ID in the Pet_Owners table. The Owner name for these records will be null.
If we want to look at all records, we can use a full outer join, to see all Pet_Types and all Pet_Owners. For example, show all Yappy dogs, with owners where they exist:
SELECT Owner_name, Breed FROM Pet_Types FULL OUTER JOIN Pet_Owners ON Pet_Types.Pet_Type_ID = Pet_Owners.Pet_Type_ID WHERE Pet_Types.Characteristic = 'yappy';
This combines the two previous Outer join types.
[edit] Unions
The union operator is used to combine the information from 2 different tables into one result set.
For example, let's say that one table lists pet owners in LA and another lists pet owners in Chicago, and we would like them in one table. The UNION statement lies between two SELECT statements, and does what we desire:
SELECT * FROM LA_pets UNION SELECT * FROM Chicago_pets
The converse to this is the EXCLUDE: say that we want only pets outside of LA:
SELECT * FROM California_pets EXCLUDE SELECT * FROM LA_pets
[edit] See also
- Python Programming/Database Programming — using SQL statements from within a Python programming environment

