CS 334

Course Notes:


Chapter 9:

SQL is a standard computer language for accessing and manipulating databases.
------------------------------------------------------------------------

What is SQL?

* SQL stands for Structured Query Language
* SQL allows you to access a database
* SQL is an ANSI standard computer language
* SQL can execute queries against a database
* SQL can retrieve data from a database
* SQL can insert new records in a database
* SQL can delete records from a database
* SQL can update records in a database
* SQL is easy to learn

------------------------------------------------------------------------

SQL is a Standard - BUT....

SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems. SQL statements are used to retrieve and update data in a database. SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc.

Unfortunately, there are many different versions of the SQL language, but to be in compliance with the ANSI standard, they must support the same major keywords in a similar manner (such as SELECT, UPDATE, DELETE, INSERT, WHERE, and others).

Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!
------------------------------------------------------------------------
SQL Create Database and Table

Create a Database

To create a database:

CREATE DATABASE database_name

Create a Table

To create a table in a database:

CREATE TABLE table_name

( column_name1 data_type, column_name2 data_type, )

Example

This example demonstrates how you can create a table named "Person", with four columns. The column names will be "LastName", "FirstName", "Address", and "Age":

CREATE TABLE Person 

(

LastName varchar,

FirstName varchar,

Address varchar,

Age int

)

 

This example demonstrates how you can specify a maximum length for some columns:

CREATE TABLE Person 

(

LastName varchar(30),

FirstName varchar,

Address varchar,

Age int(3) 

)

The data type specifies what type of data the column can hold. The table below contains the most common data types in SQL:

Data Type Description

integer(size)

int(size)

smallint(size)

tinyint(size) Hold integers only. The maximum number of digits are specified in parenthesis.

decimal(size,d)

numeric(size,d) Hold numbers with fractions. The maximum number of digits are specified in "size". The maximum number of digits to the right of the decimal is specified in "d".

char(size) Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis.

varchar(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis.

date(yyyymmdd) Holds a date

------------------------------------------------------------------------

SQL Database Tables

 A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.

 Below is an example of a table called "Persons":

LastName   FirstName   Address   City

Hansen   Ola   Timoteivn 10   Sandnes

Svendson   Tove   Borgvn 23   Sandnes

Pettersen   Kari   Storgt 20   Stavanger

 The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).

 SQL Queries

 With SQL, we can query a database and have a result set returned.

 SELECT field FROM table

A query like this:

SELECT LastName FROM Persons 

Gives a result set like this:

LastName

Hansen

Svendson

Pettersen

 Note: Some database systems require a semicolon at the end of the SQL statement. We don't use the semicolon in our tutorials.

SQL Data Manipulation Language (DML)

 SQL (Structured Query Language) is a syntax for executing queries. But the SQL language also includes a syntax to update, insert, and delete records.

 These query and update commands together form the Data Manipulation Language (DML) part of SQL:

 *   SELECT - extracts data from a database table

*   UPDATE - updates data in a database table

*   DELETE - deletes data from a database table

*   INSERT INTO - inserts new data into a database table

 SQL Data Definition Language (DDL)

 

The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted. We can also define indexes (keys), specify links between tables, and impose constraints between database tables.

 The most important DDL statements in SQL are: 

 *   CREATE TABLE - creates a new database table

*   ALTER TABLE - alters (changes) a database table

*   DROP TABLE - deletes a database table

*   CREATE INDEX - creates an index (search key)

*   DROP INDEX - deletes an index

 The SELECT Statement 

The SELECT statement is used to select data from a table. The tabular result is stored in a result table (called the result-set).

 Syntax

SELECT column_name(s) FROM table_name

Select Some Columns

 

To select the columns named "LastName" and "FirstName", use a SELECT statement like this:

SELECT LastName, FirstName FROM Persons

 "Persons" table

LastName   FirstName   Address   City

Hansen   Ola   Timoteivn 10   Sandnes

Svendson   Tove   Borgvn 23   Sandnes

Pettersen   Kari   Storgt 20   Stavanger

 

Result

LastName   FirstName

Hansen   Ola

Svendson   Tove

Pettersen   Kari

------------------------------------------------------------------------

 

Select All Columns

 

To select all columns from the "Persons" table, use a * symbol instead of column names, like this: 

SELECT * FROM Persons

 

Result

LastName   FirstName   Address   City

Hansen   Ola   Timoteivn 10   Sandnes

Svendson   Tove   Borgvn 23   Sandnes

Pettersen   Kari   Storgt 20   Stavanger

------------------------------------------------------------------------

 

The Result Set

 

The result from a SQL query is stored in a result-set. Most database software systems allow navigation of the result set with programming functions, like: Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.

 

------------------------------------------------------------------------

 

Semicolon after SQL Statements? 

Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.

 Some SQL tutorials ends each SQL statement with a semicolon. Is this necessary? We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each SQL statement, but some database programs force you to use it.

------------------------------------------------------------------------

 The SELECT DISTINCT Statement

 The DISTINCT keyword is used to return only distinct (different) values.

 The SELECT statement returns information from table columns. But what if we only want to select distinct elements?

 With SQL, all we need to do is to add a DISTINCT keyword to the SELECT statement:

 

Syntax

SELECT DISTINCT column_name(s)

FROM table_name

 

------------------------------------------------------------------------

 

Using the DISTINCT keyword

 

To select ALL values from the column named "Company" we use a SELECT statement like this:

SELECT Company FROM Orders

 

"Orders" table

Company   OrderNumber

Sega   3412

W3Schools   2312

Trio   4678

W3Schools   6798

 

Result

Company

Sega

W3Schools

Trio

W3Schools

 

Note that "W3Schools" is listed twice in the result-set.

 

To select only DIFFERENT values from the column named "Company" we use a SELECT DISTINCT statement like this:

SELECT DISTINCT Company FROM Orders

 

Result:

Company

Sega

W3Schools

Trio

 

Now "W3Schools" is listed only once in the result-set.

The WHERE Clause 

 To conditionally select data from a table, a WHERE clause can be added to the SELECT statement.

 Syntax

SELECT column FROM table

WHERE column operator value

 

With the WHERE clause, the following operators can be used:

Operator   Description

=   Equal

<>   Not equal

>   Greater than

<   Less than

>=   Greater than or equal

<=   Less than or equal

BETWEEN   Between an inclusive range

LIKE  

Search for a pattern

 

Note: In some versions of SQL the <> operator may be written as !=

------------------------------------------------------------------------

 

Using the WHERE Clause

 

To select only the persons living in the city "Sandnes", we add a WHERE clause to the SELECT statement: 

SELECT * FROM Persons

WHERE City='Sandnes'

 "Persons" table

LastName   FirstName   Address   City   Year

Hansen   Ola   Timoteivn 10   Sandnes   1951

Svendson   Tove   Borgvn 23   Sandnes   1978

Svendson   Stale   Kaivn 18   Sandnes   1980

Pettersen   Kari   Storgt 20   Stavanger   1960

 

Result:

LastName   FirstName   Address   City   Year

Hansen   Ola   Timoteivn 10   Sandnes   1951

Svendson   Tove   Borgvn 23   Sandnes   1978

Svendson   Stale   Kaivn 18   Sandnes   1980

-----------------------------------------------------------------------

Using Quotes

 Note that we have used single quotes around the conditional values in the examples.

 SQL uses single quotes around text values (most database systems will also accept double quotes). Numeric values should not be enclosed in quotes.

 

For text values:

This is correct:

SELECT * FROM Persons WHERE FirstName='Tove'

 

This is wrong:

SELECT * FROM Persons WHERE FirstName=Tove

 

For numeric values:

This is correct:

SELECT * FROM Persons WHERE Year>1965

 This is wrong:

SELECT * FROM Persons WHERE Year>'1965'

------------------------------------------------------------------------

 

The LIKE Condition  

The LIKE condition is used to specify a search for a pattern in a column.

 Syntax

SELECT column FROM table

WHERE column LIKE pattern

 

A "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.

 Using LIKE

 The following SQL statement will return persons with first names that start with an 'O':

SELECT * FROM Persons

WHERE FirstName LIKE 'O%' 

The following SQL statement will return persons with first names that end with an 'a':

SELECT * FROM Persons

WHERE FirstName LIKE '%a' 

The following SQL statement will return persons with first names that contain the pattern 'la':

SELECT * FROM Persons

WHERE FirstName LIKE '%la%'

 

The INSERT INTO Statement 

The INSERT INTO statement is used to insert new rows into a table.

 Syntax

INSERT INTO table_name

VALUES (value1, value2,....) 

You can also specify the columns for which you want to insert data:

INSERT INTO table_name (column1, column2,...)

VALUES (value1, value2,....)

 

 Insert a New Row

 This "Persons" table:

LastName   FirstName   Address   City

Pettersen   Kari   Storgt 20   Stavanger

 And this SQL statement:

INSERT INTO Persons 

VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes')

 Will give this result:

LastName   FirstName   Address   City

Pettersen   Kari   Storgt 20   Stavanger

Hetland   Camilla   Hagabakka 24   Sandnes

------------------------------------------------------------------------

 Insert Data in Specified Columns

 This "Persons" table:

LastName   FirstName   Address   City

Pettersen   Kari   Storgt 20   Stavanger

Hetland   Camilla   Hagabakka 24   Sandnes

 And This SQL statement:

INSERT INTO Persons (LastName, Address)

VALUES ('Rasmussen', 'Storgt 67')

 

Will give this result:

LastName   FirstName   Address   City

Pettersen   Kari   Storgt 20   Stavanger

Hetland   Camilla   Hagabakka 24   Sandnes

Rasmussen       Storgt 67    

 The Update Statement

 The UPDATE statement is used to modify the data in a table.

 Syntax

UPDATE table_name

SET column_name = new_value

WHERE column_name = some_value

 

------------------------------------------------------------------------

 

Person:

LastName   FirstName   Address   City

Nilsen   Fred   Kirkegt 56   Stavanger

Rasmussen       Storgt 67    

------------------------------------------------------------------------

 

Update one Column in a Row

 

We want to add a first name to the person with a last name of "Rasmussen":

UPDATE Person SET FirstName = 'Nina'

WHERE LastName = 'Rasmussen'

 

Result:

LastName   FirstName   Address   City

Nilsen   Fred   Kirkegt 56   Stavanger

Rasmussen   Nina   Storgt 67    

------------------------------------------------------------------------

 

Update several Columns in a Row

 

We want to change the address and add the name of the city:

UPDATE Person

SET Address = 'Stien 12', City = ' Stavanger'

WHERE LastName = 'Rasmussen'

 

Result:

LastName   FirstName   Address   City

Nilsen   Fred   Kirkegt 56   Stavanger

Rasmussen   Nina   Stien 12   Stavanger

 

The Delete Statement

 

The DELETE statement is used to delete rows in a table.

 

Syntax

DELETE FROM table_name

WHERE column_name = some_value

 

------------------------------------------------------------------------

 

Person:

LastName   FirstName   Address   City

Nilsen   Fred   Kirkegt 56   Stavanger

Rasmussen   Nina   Stien 12   Stavanger

------------------------------------------------------------------------

 

Delete a Row

 

"Nina Rasmussen" is going to be deleted:

DELETE FROM Person WHERE LastName = 'Rasmussen'

 

Result

LastName   FirstName   Address   City

Nilsen   Fred   Kirkegt 56   Stavanger

------------------------------------------------------------------------

 

Delete All Rows

 

It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact:

DELETE FROM table_name

 

or

 

DELETE * FROM table_name

 

SQL Order By

 

------------------------------------------------------------------------

 

The ORDER BY keywords are used to sort-order the result.

------------------------------------------------------------------------

 

Sort the Rows

 

The ORDER BY clause is used to sort the rows.

 

Orders:

Company   OrderNumber

Sega   3412

ABC Shop   5678

W3Schools   2312

W3Schools   6798

 

Example

 

To display the companies in alphabetical order:

SELECT Company, OrderNumber FROM Orders

ORDER BY Company

 

Result:

Company   OrderNumber

ABC Shop    5678

Sega   3412

W3Schools   6798

W3Schools   2312

 

Example

 

To display the companies in alphabetical order AND the ordernumbers in numerical order:

SELECT Company, OrderNumber FROM Orders

ORDER BY Company, OrderNumber

 

Result:

Company   OrderNumber

ABC Shop   5678

Sega   3412

W3Schools   2312

W3Schools   6798

 

Example

 

To display the companies in reverse alphabetical order:

SELECT Company, OrderNumber FROM Orders

ORDER BY Company DESC

 

Result:

Company   OrderNumber

W3Schools   6798

W3Schools   2312

Sega   3412

ABC Shop   5678

 

Example

 

To display the companies in reverse alphabetical order AND the ordernumbers in numerical order:

SELECT Company, OrderNumber FROM Orders

ORDER BY Company DESC, OrderNumber ASC

 

Result:

Company   OrderNumber

W3Schools   2312

W3Schools   6798

Sega   3412

ABC Shop   5678

 

SQL And & Or

 

------------------------------------------------------------------------

 

AND & OR

 

AND and OR join two or more conditions in a WHERE clause.

 

The AND operator displays a row if ALL conditions listed are true. The OR operator displays a row if ANY of the conditions listed are true.

------------------------------------------------------------------------

 

Original Table (used in the examples)

LastName   FirstName   Address   City

Hansen   Ola   Timoteivn 10   Sandnes

Svendson   Tove   Borgvn 23   Sandnes

Svendson   Stephen   Kaivn 18   Sandnes

------------------------------------------------------------------------

 

Example

 

Use AND to display each person with the first name equal to "Tove", and the last name equal to "Svendson":

SELECT * FROM Persons

WHERE FirstName='Tove'

AND LastName='Svendson'

 

Result:

LastName   FirstName   Address   City

Svendson   Tove   Borgvn 23   Sandnes

 

Example

 

Use OR to display each person with the first name equal to "Tove", or the last name equal to "Svendson":

SELECT * FROM Persons

WHERE firstname='Tove'

OR lastname='Svendson'

 

Result:

LastName   FirstName   Address   City

Svendson   Tove   Borgvn 23   Sandnes

Svendson   Stephen   Kaivn 18   Sandnes

 

Example

 

You can also combine AND and OR (use parentheses to form complex expressions):

SELECT * FROM Persons WHERE

(FirstName='Tove' OR FirstName='Stephen')

AND LastName='Svendson'

 

Result:

LastName   FirstName   Address   City

Svendson   Tove   Borgvn 23   Sandnes

Svendson   Stephen   Kaivn 18   Sandnes

 

SQL Between...And

 

------------------------------------------------------------------------

 

BETWEEN ... AND

 

The BETWEEN ... AND operator selects a range of data between two values. These values can be numbers, text, or dates.

SELECT column_name FROM table_name

WHERE column_name

BETWEEN value1 AND value2

 

------------------------------------------------------------------------

 

Original Table (used in the examples)

LastName   FirstName   Address   City

Hansen   Ola   Timoteivn 10   Sandnes

Nordmann   Anna   Neset 18   Sandnes

Pettersen   Kari   Storgt 20   Stavanger

Svendson   Tove   Borgvn 23   Sandnes

------------------------------------------------------------------------

 

Example 1

 

To display the persons alphabetically between (and including) "Hansen" and exclusive "Pettersen", use the following SQL:

SELECT * FROM Persons WHERE LastName

BETWEEN 'Hansen' AND 'Pettersen'

 

Result:

LastName   FirstName   Address   City

Hansen   Ola   Timoteivn 10   Sandnes

Nordmann   Anna   Neset 18   Sandnes

 

IMPORTANT! The BETWEEN...AND operator is treated differently in different databases. With some databases a person with the LastName of "Hansen" or "Pettersen" will not be listed (BETWEEN..AND only selects fields that are between and excluding the test values). With some databases a person with the last name of "Hansen" or "Pettersen" will be listed (BETWEEN..AND selects fields that are between and including the test values). With other databases a person with the last name of "Hansen" will be listed, but "Pettersen" will not be listed (BETWEEN..AND selects fields between the test values, including the first test value and excluding the last test value). Therefore: Check how your database treats the BETWEEN....AND operator!

------------------------------------------------------------------------

 

Example 2

 

To display the persons outside the range used in the previous example, use the NOT operator:

SELECT * FROM Persons WHERE LastName

NOT BETWEEN 'Hansen' AND 'Pettersen'

 

Result:

LastName   FirstName   Address   City

Pettersen   Kari   Storgt 20   Stavanger

Svendson   Tove   Borgvn 23   Sandnes

 

SQL Aliases

 

------------------------------------------------------------------------

 

With SQL, aliases can be used for column names and table names.

------------------------------------------------------------------------

 

Column Name Alias

 

The syntax is:

SELECT column AS column_alias FROM table

------------------------------------------------------------------------

 

Table Name Alias

 

The syntax is:

SELECT column FROM table AS table_alias

------------------------------------------------------------------------

 

Example: Using a Column Alias

 

This table (Persons):

LastName   FirstName   Address   City

Hansen   Ola   Timoteivn 10   Sandnes

Svendson   Tove   Borgvn 23   Sandnes

Pettersen   Kari   Storgt 20   Stavanger

 

And this SQL:

SELECT LastName AS Family, FirstName AS Name

FROM Persons

 

Returns this result:

Family   Name

Hansen   Ola

Svendson   Tove

Pettersen   Kari

------------------------------------------------------------------------

 

Example: Using a Table Alias

 

This table (Persons):

LastName   FirstName   Address   City

Hansen   Ola   Timoteivn 10   Sandnes

Svendson   Tove   Borgvn 23   Sandnes

Pettersen   Kari   Storgt 20   Stavanger

 

And this SQL:

SELECT LastName, FirstName

FROM Persons AS Employees

 

Returns this result:

 

Table Employees:

LastName   FirstName

Hansen   Ola

Svendson   Tove

Pettersen   Kari

 

SQL Join

 

------------------------------------------------------------------------

 

Joins and Keys

 

Sometimes we have to select data from two tables to make our result complete. We have to perform a join.

 

Tables in a database can be related to each other with keys. A primary key is a column with a unique value for each row. The purpose is to bind data together, across tables, without repeating all of the data in every table.

 

In the "Employees" table below, the "Employee_ID" column is the primary key, meaning that no two rows can have the same Employee_ID. The Employee_ID distinguishes two persons even if they have the same name.

 

When you look at the example tables below, notice that: 

 

*   The "Employee_ID" column is the primary key of the "Employees" table

*   The "Prod_ID" column is the primary key of the "Orders" table

*   The "Employee_ID" column in the "Orders" table is used to refer to the persons in the "Employees" table without using their names

 

------------------------------------------------------------------------

 

Employees:

Employee_ID   Name

01   Hansen, Ola

02   Svendson, Tove

03   Svendson, Stephen

04   Pettersen, Kari

 

Orders:

Prod_ID   Product   Employee_ID

234   Printer   01

657   Table   03

865   Chair   03

------------------------------------------------------------------------

 

Referring to Two Tables

 

We can select data from two tables by referring to two tables, like this:

 

Example

 

Who has ordered a product, and what did they order?

SELECT Employees.Name, Orders.Product

FROM Employees, Orders

WHERE Employees.Employee_ID=Orders.Employee_ID

 

Result

Name   Product

Hansen, Ola   Printer

Svendson, Stephen   Table

Svendson, Stephen   Chair

 

Example

 

Who ordered a printer?

SELECT Employees.Name

FROM Employees, Orders

WHERE Employees.Employee_ID=Orders.Employee_ID

AND Orders.Product='Printer'

 

Result

Name

Hansen, Ola

------------------------------------------------------------------------

 

Using Joins

 

OR we can select data from two tables with the JOIN keyword, like this:

 

Example INNER JOIN

 

Syntax

SELECT field1, field2, field3

FROM first_table

INNER JOIN second_table

ON first_table.keyfield = second_table.foreign_keyfield

 

Who has ordered a product, and what did they order?

SELECT Employees.Name, Orders.Product

FROM Employees

INNER JOIN Orders

ON Employees.Employee_ID=Orders.Employee_ID

 

The INNER JOIN returns all rows from both tables where there is a match. If there are rows in Employees that do not have matches in Orders, those rows will not be listed.

 

Result

Name   Product

Hansen, Ola   Printer

Svendson, Stephen   Table

Svendson, Stephen   Chair

 

Example LEFT JOIN

 

Syntax

SELECT field1, field2, field3

FROM first_table

LEFT JOIN second_table

ON first_table.keyfield = second_table.foreign_keyfield

 

List all employees, and their orders - if any.

SELECT Employees.Name, Orders.Product

FROM Employees

LEFT JOIN Orders

ON Employees.Employee_ID=Orders.Employee_ID

 

The LEFT JOIN returns all the rows from the first table (Employees), even if there are no matches in the second table (Orders). If there are rows in Employees that do not have matches in Orders, those rows also will be listed.

 

Result

Name   Product

Hansen, Ola   Printer

Svendson, Tove    

Svendson, Stephen   Table

Svendson, Stephen   Chair

Pettersen, Kari    

 

Example RIGHT JOIN

 

Syntax

SELECT field1, field2, field3

FROM first_table

RIGHT JOIN second_table

ON first_table.keyfield = second_table.foreign_keyfield

 

List all orders, and who has ordered - if any.

SELECT Employees.Name, Orders.Product

FROM Employees

RIGHT JOIN Orders

ON Employees.Employee_ID=Orders.Employee_ID

 

The RIGHT JOIN returns all the rows from the second table (Orders), even if there are no matches in the first table (Employees). If there had been any rows in Orders that did not have matches in Employees, those rows also would have been listed.

 

Result

Name   Product

Hansen, Ola   Printer

Svendson, Stephen   Table

Svendson, Stephen   Chair

 

Example

 

Who ordered a printer?

SELECT Employees.Name

FROM Employees

INNER JOIN Orders

ON Employees.Employee_ID=Orders.Employee_ID

WHERE Orders.Product = 'Printer'

 

Result

Name

Hansen, Ola