+ All Categories
Home > Documents > Introduction_to_SQL_e_v11.doc.doc.doc

Introduction_to_SQL_e_v11.doc.doc.doc

Date post: 13-Sep-2014
Category:
View: 1,069 times
Download: 0 times
Share this document with a friend
Description:
 
Popular Tags:
90
ASCA & ALCS Curriculum Databases V1.1 26/1/2006 Contents Introduction to Structured Query Language...............3 What is SQL?..........................................3 History for SQL (not within the curricula)............3 Data Definition Language and Data Manipulation Language5 An Illustrative Example – A Library System............7 Commonly Used Data Types in SQL.......................9 SQL Statements.......................................11 Creating Database Objects...............................11 Create a database.................................11 Create a table in a database......................11 Creating Table with Integrity Rule.........................13 Create table with primary key.....................13 Create table with foreign key.....................14 Modifying Table Structure...............................15 Add column........................................ 15 Drop column....................................... 15 Change columns’ data type.........................16 Change column(s) to NOT NULL......................17 Add a primary key to an existing table............18 Deleting Database Objects...............................19 Delete a table....................................19 Delete a database.................................19 Adding Data to Tables..................................20 Insert new row....................................20 Insert new record with only specified column field(s).......................................... 21 Retrieving Data from Database Table(s).....................22 Retrieve all fields from a table..................22 Retrieve value(s) from particular column(s) of a table............................................. 23 Retrieve value(s) from particular column(s) of a table without duplication.........................23 Retrieve data with specified selection criteria. . .25 Creating and Deleting Data View..........................26 Create a data view................................26 Delete a data view................................27 Update the value in a column......................28 Update values in a number of columns..............29 Delete record(s) from the table...................30 1
Transcript
Page 1: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Contents

Introduction to Structured Query Language............................................................3What is SQL?............................................................................................................3History for SQL (not within the curricula)............................................................3Data Definition Language and Data Manipulation Language.............................5An Illustrative Example – A Library System........................................................7Commonly Used Data Types in SQL......................................................................9SQL Statements......................................................................................................11

Creating Database Objects..................................................................................11Create a database...........................................................................................11Create a table in a database..........................................................................11

Creating Table with Integrity Rule.....................................................................13Create table with primary key......................................................................13Create table with foreign key........................................................................14

Modifying Table Structure..................................................................................15Add column.....................................................................................................15Drop column...................................................................................................15Change columns’ data type...........................................................................16Change column(s) to NOT NULL.................................................................17Add a primary key to an existing table........................................................18

Deleting Database Objects..................................................................................19Delete a table...................................................................................................19Delete a database............................................................................................19

Adding Data to Tables.........................................................................................20Insert new row................................................................................................20Insert new record with only specified column field(s)................................21

Retrieving Data from Database Table(s)............................................................22Retrieve all fields from a table......................................................................22Retrieve value(s) from particular column(s) of a table...............................23Retrieve value(s) from particular column(s) of a table without duplication..........................................................................................................................23Retrieve data with specified selection criteria.............................................25

Creating and Deleting Data View.......................................................................26Create a data view..........................................................................................26Delete a data view...........................................................................................27Update the value in a column........................................................................28Update values in a number of columns........................................................29Delete record(s) from the table.....................................................................30

Result Presentation.............................................................................................31The ORDER BY clause..................................................................................31The GROUP BY … HAVING clause...........................................................33

Operators Used with WHERE............................................................................35The LIKE operator........................................................................................35The IN operator..............................................................................................37The BETWEEN Operator.............................................................................38The AND Operator........................................................................................39The OR operator............................................................................................39Add alias to a column.....................................................................................41

1

Page 2: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Joining Tables.....................................................................................................42Equijoin...........................................................................................................42The NATURAL JOIN operator....................................................................44The INNER JOIN operator...........................................................................45The LEFT (OUTER) JOIN operator...........................................................46The RIGHT (OUTER) JOIN operator........................................................47The FULL (OUTER) JOIN operator...........................................................48

Combining Query Results...................................................................................49The UNION operator.....................................................................................49The INTERSECT operator...........................................................................50The EXCEPT/MINUS operator....................................................................51Using nested SELECT statement..................................................................52

Arithmetic Operators/Functions.........................................................................54String Functions..................................................................................................54Aggregate Functions...........................................................................................56

The AVG function..........................................................................................56The COUNT function....................................................................................57The MAX function.........................................................................................58The MIN function...........................................................................................59The SUM Function.........................................................................................60Create/Drop Table Index...............................................................................61

Exporting Data from MS Access........................................................................63Export Data from an MS Access Database to Another Access Database. 63Export Data from an MS Access Database in other file formats...............65

2

Page 3: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Introduction to Structured Query Language

What is SQL?

Structural Query Language (SQL) is a standard language for manipulating and querying database objects (e.g., table structures and contents) in the relational database management system. For simplicity, we refer relational database management system to as database from now on. SQL allows you to access a database. SQL can be used to define database table structure and to store, select and manage data from the database including data insertion, update and deletion. SQL is widely used in databases like MySQL, DB2, Oracle, PostgreSQL, Sybase, Microsoft SQL Server, MS Access, etc.

History for SQL (not within the curricula)

In early 1970s, a seminal paper related to the relational database model authored by E.F. Codd received in a considerable notice from the database community. The relational database model provided a perfectly theoretical framework for the development of a well-formed querying language that the model could support. By 1974, IBM had defined a language called the ‘Structured English Query Language’ or SEQUEL. The name was later shortened as Structured Query Language (SQL).

In 1986, a standard for Structured Query Language (SQL) was defined by the American National Standards Institute (ANSI), and this became an international standard recognized by the International Standards Organization (ISO) in 1987. In 1989, a revised standard known commonly as SQL89 or SQL1, was published. The ANSI committee released the SQL92 standard in 1992 (also called SQL2). This standard addressed several weaknesses in SQL89 and set forth conceptual SQL features which at that time exceeded the capabilities of any existing RDBMS implementation. The SQL92 standard was approximately six times the length of its predecessor. Because of this disparity, the authors defined three levels of SQL92 compliance: Entry-level conformance, Intermediate-level conformance, and Full conformance. Some information about the difference among various levels of SQL92 compliance can be found here.

In 1999, the ANSI/ISO released the SQL99 standard (also called SQL3). This standard addresses some of the more advanced areas of modern SQL systems, such as object-relational database concepts, call level interfaces, and integrity management. SQL99 replaces the SQL92 levels of compliance with its own degrees of conformance: Core SQL99 and Enhanced SQL99. A short article that highlights some important changes in SQL99 can be found here.

Although various databases may implement their SQL slightly differently, they support the same major functions (such as SELECT, UPDATE, DELETE, INSERT, WHERE, etc.) in a similar way in order to fulfill the ANSI standard. This SQL statements introduced in this note are largely based on the Entry-level conformance of SQL92.

3

Page 4: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Teaching remarks Apparently, the SQL statements that the A/AS level curricula cover are so basic

that even the entry-level of SQL92 supports them. Most of the SQL statements included in this note have been tested on Microsoft

Access 2003. It supports SQL92 but this requires some reconfiguration. The default database format is Access 2000 which is not compatible with SQL92. To change the default database format, start Access 2003. Click Tools, then Options. Click the Advanced tab and change the Default File Format to “MS Access2002-2003” (see Figure 1). To change the SQL syntax to SQL92, click Tools and then Options. Click the Tables/Queries tab and check both boxes (This database and Default for new databases) under SQL Server Compatible Syntax (ANSI 92) (see Figure 2).

It appears that the SQL92 supported by Access 2003 conforms to the entry-level only. For example, it does not support for some join features such as NATURAL JOIN and FULL OUTER JOIN. Other non-support features include EXCEPT and INTERSECT, etc.

A subset of the SQL92 standard that is both usable and commonly supported can be found at http://www.firstsql.com/tutor.htm.

Figure 1. Setting Access 2003’s default database format to “Access 2002 – 2003” to support SQL92.

4

Page 5: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Figure 2. Setting Access 2003’s default SQL syntax to conform to SQL92.

Data Definition Language and Data Manipulation Language

SQL supports functions such as building and manipulating database objects, populating database tables with data, updating existing data in tables, deleting data, performing database queries, controlling database access and overall database administration. Such functions can be classified into a number of categories and the most well known two categories are Data Definition Language (DLL) and Data Manipulation Language (DML).

DDL allows user to create and restructure database objects, such as creating and deleting database tables. Besides, DDL can be used to define table indexes as well as foreign keys between tables. Some of the commonly used DDL commands are:

CREATE TABLE ALTER TABLE DROP TABLE CREATE INDEX ALTER INDEX DROP INDEX CREATE VIEW DROP VIEW

DML allows users to manipulate data within the objects of a database. Some of the commonly used DML commands are:

5

Page 6: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

SELECT INSERT INTO UPDATE DELETE

In a nutshell, DDL allows database users to define database objects whereas DML allows database users to retrieve, insert, delete and update data in a database.

6

Page 7: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

An Illustrative Example – A Library System

In order to help readers understand the SQL statements that we are going to introduce, those statements will be illustrated in a hypothetical library database as far as possible. The tables used in the simple library database are the Student, Book and LoanRecord tables and their details are given below. Readers are reminded that the tables and fields kept in the proposed database are far less than what a real library system requires. We keep the example database simple and yet adequate for the illustration purposes.

The Student table is used to store basic student information like student ID, name, the class that the student belongs, and phone number. The data fields of the Student table are as follows:

Table 1. Data in the Student table.

Table 2 describes the characteristics of the data fields in the Student table.

Field Name DescriptionStdID Unique Student number

Text string – 7 digits Not null (i.e., the field is mandatory and a value is to be

inserted)Name Student Name

Text string – 30 characters Not null

Class The class student study Text string – 2 characters Not null

PhoneNo Phone Number Text string – 8 digits

OverduePay Overdue Payment A number with two decimal places (<= 999.99)

Table 2. Characteristics of the data fields in the Student table.

StdID Name Class OverduePay PhoneNo0002011 Chan Ming Wai 2C 12.5 212387820002012 Wong Wai Ming 2B 30.5 212344560002013 Cheung Ka Fai 2C 0 232123210002014 Chang Wai Yee 4A 20.5 232131230002015 Lee Oi Lam 5C 3 252141230002016 Sze Yuk Ki 7B 1.5 26434534

7

Page 8: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Teaching remark Some people may opt to define numeric data like StdID and PhoneNo as integers

instead of text string. The reason why we prefer to represent the fields as text strings is that as the “numbers” are not used for computation.

Two different data types can be used to define text strings (see next section) and it is important for teachers to clarify to their student of the key difference between the data types.

The Book table contains the key information about the books in the library. Details of the Book table are shown in Table 3.

BookID Title Type00000001 Apple Tree00000002 Bible00000003 Star Wing

Table 3. Data in the Book table.

Table 4 describes the characteristics of the data fields in the Book table.

Field Name DescriptionBookID Unique book ID

Text string – 8 digits Not null

Title Book Title Text string – 100 characters Not null

Type Book category Text string – 3 digits

Table 4. Characteristics of the data fields in the Book table.

The LoanRecord table contains information of the library items on loan (or once on loan). Details of the Book table are as follows:

LoanRecID StdID BookID DateOfBorrow Status1 0002012 00000001 20051001 12 0002011 00000002 20020112 23 0002012 00000003 20031211 24 0002013 00000002 20031001 25 0002011 00000002 20051018 1

Table 5. Data in the LoanRecord table.

8

Page 9: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Table 6 describes the characteristics of the data fields in the LoanRecord table.

Field Name DescriptionLoanRecID Unique loan record ID

Text string – 8 digits Not null

StdID Student number Text string – 7 digits Not null

BookID Book ID Text string – 8 digits Not null

DateOfBorrow Date of the book being borrowed Date data type Not null

Status Loan status (1 – on loan; 2 – returned; 3 – on hold) Text string – 1 digit Not null

Table 6. Characteristics of the data fields in the LoanRecord table.

Commonly Used Data Types in SQL

The data type of a data item restricts the values that the data item can take and the operations which one can perform on that data item. Table 7 gives some of the commonly used data types in SQL.

Data Type DescriptionINTEGER or INTSMALLINTTINYINT

Hold integers only. The three types differ in the minimum and maximum value that they can represent.

DECIMAL(size, decimal)NUMERIC(size, decimal)

Hold numbers with fractions. The maximum number of digits is specified by size. The maximum number of decimal places is specified by decimal.

CHAR(size) Hold a fixed length text string. The maximum size of fixed length string is specified by size. Unused space is packed with space characters.

VARCHAR(size) Hold a variable length string. The maximum size of fixed length string is specified by size. Unused space is not packed with any characters.

DATE Date format may be different in various databases but they all contain calendar date with year, month and day.

Table 7. Some basic data types used in SQL.

Note that the Boolean data type, which accepts TRUE or FALSE as its value, is not defined in SQL92, but in SQL99. However databases support the data type even though they are not conforming to SQL99.

9

Page 10: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Teaching remarks A character string stored in a CHAR column is left-justified and padded with

trailing blanks to the length of the column. All the strings stored in a CHAR column have the same length. These trailing blanks are preserved in query results.

A character string stored in a VARCHAR column has exactly the same length as the source string or the expression that generated the string (including trailing blanks). Character strings stored in a VARCHAR column can vary in length.

A character string stored in a VARCHAR column incurs a 2-byte overhead. Do not use this data type for columns less than 6 bytes long or for columns that store strings of the same length. Use the CHAR data type instead.

10

Page 11: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

SQL Statements

Creating Database Objects

Create a database

The CREATE DATABASE statement can be used to create a database with a specified name.

Syntax

CREATE DATABASE database_name

Example

A database named “library_system” is created with the following statement.

CREATE DATABASE library_system

Teaching remark Some databases like Microsoft Access may require users to create a database by

using their own user interface instead of within a SQL environment.

Create a table in a database

The CREATE TABLE statement can be used to create a table with a specified name.

Syntax

CREATE TABLE TableName(Column1 DataType1,Column2 DataType2,.......)

Full Syntax

Example 1Create a table called “Teacher” with two columns named “Name” and “Age” respectively.

CREATE TABLE Teacher(Name varchar(30),Age int)

Sample Query - Q1_1_CreateTableTeacher Want to Try?

Result

11

Page 12: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

An empty Teacher table with two fields – Name and Age – is created.

Teaching remark The Teacher table is not required in the library system example. It is created to

demonstrate another SQL statement which removes database tables.

Example 2

Create a table called “Book” that contains fields named “BookID”, “Title” and “Type” such that a value for “BookID” must be entered for each row and its value is unique within the table.

CREATE TABLE Book(BookID char(8) NOT NULL UNIQUE,Title varchar(100),Type int)

Sample Query Q1_2_CreateTableBook Want to Try?

Result

An empty Book table with three fields – BookID, Title and Type – is created. The BookID field is mandatory (indicated by “NOT NULL”) and unique (indicated by “UNIQUE”) within the Book table.

12

Page 13: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Creating Table with Integrity Rule

Create table with primary key

For each table, it is necessary to have a field or a combination of selected fields such that their values can be used to identify each table row uniquely. Such an identifier is known as a candidate key. The concept of candidate key is essential to good database design. The most commonly used candidate key of a table is typically selected to be the primary key of the table.

The PRIMARY KEY keyword is used to specify the fields in a table that compose the table’s primary key.

Syntax

CREATE TABLE TableName(Column1 DataType, NOT NULLColumn2 DataType, NOT NULL.......PRIMARY KEY (Column1, Column2, …))

Full Syntax

Teaching remark Technically, all fields in a primary key should be defined to be UNIQUE and

NOT NULL. Although some databases like Microsoft Access 2003 may take all primary key fields as UNIQUE and NOT NULL even though they are not specified, it is a good practice to specify them explicitly.

Example

To create a table called “Student” with the primary key “StdID”, we can use the following statement:

CREATE TABLE Student(StdID char(7) NOT NULL UNIQUE,Name varchar(30),Class char(10),Age smallint,OverduePay decimal(5,2),

PRIMARY KEY (StdID))

Sample Query Q2_1_createStudent_PriKey Want to Try?

Teaching remark The length of the Class field is set to 10 characters long intentionally. We will

alter it to 2 characters long using another SQL statement later.

13

Page 14: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Create table with foreign key

A foreign key (which may be composite) to another table ensures that the value of the foreign key field(s) can be found in the primary key of the foreign table. The following example shows how to create a table in a database with foreign key.

Syntax

CREATE TABLE TableName1(Column1 DataType1,Column2 DataType2,.......FOREIGN KEY (ColumnX, ColumnY) REFERENCES TableName2)

Full Syntax

Example

In this example, we would like to create a table “LoanRecord” with a primary key “LoanRecID” and two foreign keys “StdID” and “BookID” that references tables “Student” and “Book” respectively by using the following statement.

CREATE TABLE LoanRecord(LoanRecID char(8) NOT NULL,StdID char(7) NOT NULL,BookID char(8) NOT NULL,Dateofborrow date,Status char(1),PRIMARY KEY (LoanRecID),FOREIGN KEY (StdID) REFERENCES Student,FOREIGN KEY (BOOKID) REFERENCES Book)

Sample Query Q2_2_CreateLoanRecord Want to Try ?

The SQL script given above for creating LoanRecord table cannot run successfully because a primary key has not been defined for the Book table created earlier. It is important to rectify the problem by altering the structure of the Book table before running the above SQL script again.

Important remark A special view on one or more tables in the database in form of a kind of “virtual”

table can be created with the use of the CREATE VIEW statement. The data stored in the virtual table is extracted by the SELECT statement. Both the CREATE VIEW and SELECT statements will be covered later.

14

Page 15: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Modifying Table StructureIf required, a table structure can be altered with the use of various forms of the ALTER TABLE statement.

Add column

To add column(s) in a table, use ADD within the ALTER TABLE statement.

Syntax

ALTER TABLE TableName ADD ColumnName DataType

Full Syntax

Example

To add a column named “PhoneNo” in the “Student” table, we can use the following statement.

ALTER TABLE Student ADD PhoneNo char(8)

Sample Query Q3_1_AlterStudenttable Want to Try?

Result

Drop column

To drop column(s) in a table, use DROP within the ALTER TABLE statement.

Syntax

ALTER TABLE TableName DROP ColumnName

Full Syntax

Example

To drop a column ‘Age’ in the “Student” table, we can use the following statement.

ALTER TABLE Student DROP Age

Sample Query Q3_2_Alterstudent_Drop Want to Try?

Result

15

Page 16: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Change columns’ data type

Apart from adding or dropping an existing column(s) in a table, we can also edit the structure or change the data type as well as characteristics for the existing column(s) by using ALTER TABLE … ALTER COLUMN statement.

Syntax

ALTER TABLE TableName ALTER COLUMN Column1 NewDataType

Full Syntax

Teaching remark If a new data type is set for an existing column, the values that already exist in the

column must be compatible with the new data type. Otherwise, the query will not be running successfully.

Example

To change the data type ‘Class’ to char(2) in the “Student” table, we can use the following statement:

ALTER TABLE Student ALTER COLUMN Class char(2)

Sample Query Q3_3_Changedatatype Want to Try?

Result

16

Page 17: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Change column(s) to NOT NULL

Syntax

ALTER TABLE TableName ALTER COLUMN Column1 DataType NOT NULL

Full Syntax

Example

To change the data type ‘Name’ to NOT NULL in the “Student” table, we can use the following statement:

ALTER TABLE Student ALTER COLUMN Name varchar(30) NOT NULL

Sample Query Q3_4_changefieldNotNull Want to Try?

Result

Teaching remark In the above MS Access 2003 interface, the item “Required” means a mandatory

entry. In other words, the value for the field cannot be NULL, i.e., NOT NULL.

17

Page 18: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Add a primary key to an existing table

Apart from creating the primary key when creating table, we can also create a primary key to an existing table by changing the table’s column property.

Syntax

ALTER TABLE TableName ADD PRIMARY KEY (ColumnName)

Full Syntax

Example

ALTER TABLE Book ADD PRIMARY KEY (BookID)

Sample Query Q3_5_AddPriKey Want to Try?

Result

Teaching remark As the Book table has a primary key now, the SQL script for creating the

LoanRecord table that references the Book table can now be running successfully.

18

Page 19: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Deleting Database Objects

If required, a database table or even the whole database can be deleted.

Delete a table

To delete a table, use the DROP TABLE statement.

Syntax

DROP TABLE TableName

Full Syntax

Example

DROP TABLE teacher

Sample Query Q3_6_Droptable Want to Try?

Delete a database

We can delete the entire database with the use of the DROP DATABASE statement.

Syntax

DROP DATABASE DatabaseName

Example

DROP DATABASE my_database

Teaching remarks The DROP DATABASE statement should be used very rarely. You will not be able to run the DROP DATABASE statement within the graphical

user environment of MS ACCESS 2003.

19

Page 20: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Adding Data to Tables

To insert data into a table, we can use INSERT INTO statement. We can insert a new row or insert a specified field into a table.

Insert new row

Syntax

INSERT INTO TableName VALUES(Value1,Value2,.......)

Full syntax

Value1 is the value of the first field of the TableName table when the table is created. Similarly Value2 is the value of the second field of the table.

Example

The following query inserts data into the Student table.

INSERT INTO Student VALUES ('0002011', 'Chan Edward', '1C', 12.5, '21238782');INSERT INTO Student VALUES ('0002012', 'Wong Wai Ming', '2B', 30.5, '21234456');INSERT INTO Student VALUES ('0002013', 'Cheung Ka Fai', '1C', 0, '23212321');INSERT INTO Student VALUES ('0002014', 'Chang Wai Yee', '4A', 20.5, '23123123');INSERT INTO Student VALUES ('0002015', 'Lee Oi Lam', '5C', 3, '25214123');INSERT INTO Student VALUES ('0002016', 'Sze Yuk Ki', '7B', 1.5, '26434534');

Sample Query Q4_1_InsertData – Q4_6_InsertData Want to Try?

Result

20

Page 21: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Insert new record with only specified column field(s)

The following statement shows how to insert a new record with specified column field(s).

Syntax

INSERT INTO TableName (Column1, Column2..) VALUES(Value1,Value2,.......)

Full syntax

Example

We insert the Book ID and titles of three books into the Book table. The book category information (stored in the Type field) is empty for the three books.

INSERT INTO Book (BookID, Title) VALUES ('00000001', 'Apple Tree');INSERT INTO Book (BookID, Title) VALUES ('00000002', 'Bible');INSERT INTO Book (BookID, Title) VALUES ('00000003', 'Star Wing');

Sample Query Q4_7_InsertSpecialField - Q4_9_InsertSpecialField Want to Try?

Result

21

Page 22: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Retrieving Data from Database Table(s)

To select specific data from one or more tables, we can use the SELECT statement. The SELECT statement can be used in conjunction with other SQL statement to build sophisticated database queries.

Retrieve all fields from a table

In SQL statement, the symbol “*” is used to represent the “all of them”. The statement can be used to retrieve data from multiple tables but we defer the discussion to a later stage. We can use the following statement to select all fields from a database table.

Syntax

SELECT * FROM TableName

Full Syntax

Example

The following SQL statement retrieves (and displays) all records in the Student table.

SELECT * FROM Student

Sample Query Q5_1_select Want toTry?

Result

22

Page 23: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Retrieve value(s) from particular column(s) of a table

To select data from particular column of a table, we can use the SELECT statement too.

Syntax

SELECT Column1, Column2…FROM TableName

Full Syntax

Example

To select the ‘Name’ and ‘Class’ columns from the Student table, we can use the statement as below.

SELECT Name, Class FROM Student

Sample Query Q5_2_SelectSpecificField Want to Try?

Result

Teaching remark If the values of the selected columns from different rows of the table are the same,

multiple occurrences of the same values will result. To avoid the duplication, the SELECT DISTINCT statement is required.

Retrieve value(s) from particular column(s) of a table without duplication

The SELECT DISTINCT statement is used to select the value(s) of those specified column field(s) with no duplication. The syntax of this statement is as follows.

Syntax

SELECT DISTINCT column1, coloumn2 …FROM TableName

Full Syntax

23

Page 24: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Example

In this example, we would like to identify all students who have used the library service at least once. If we use the SELECT statement without the DISTINCT keyword, multiple occurrences of the same students may appear if those students use the library services more than once. To avoid the duplication, we retrieve all distinct value(s) of the ‘StdID’ field from the LoanRecord table (see Table 5 for its content) with the use of the SELECT DISTINCT statement.

SELECT DISTINCT StdID FROM LoanRecord

Sample Query Q5_3_SelectDistinct Want to Try?

Result

24

Page 25: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Retrieve data with specified selection criteria

A WHERE clause can be appended to the basic SELECT statement to specify the condition(s) that the retrieved data need to fulfill. Rows that do not meet the specified condition(s) will not be retrieved. When more than one condition is specified, AND/OR may be used to join the conditions.

Syntax

SELECT Column1, Column2… FROM TableNameWHERE Condition(s)

Full Syntax

Common operators used in the WHERE clause are tabulated below.

Operator Description= Equal to<> Not Equal to> Greater/ Larger than< Less/ Smaller than>= Greater or equal to <= Less or equal toBETWEEN Within the rangeLIKE Match the pattern

Example

In this example, we would like to retrieve records of those students in the class “1C”.

SELECT * FROM Student WHERE class = '1C'

Sample Query Q6_1_SelectwithCriteria

Teaching remark Except for numeric values, the operand(s) of the operator must be enclosed by a

pair of single quotation marks ‘’.

Result

25

Page 26: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Creating and Deleting Data View

Create a data view

With the use of the CREATE VIEW statement, users may create a special view on one or more tables (or views) in the database in form of a new “virtual” table. The data view is created with the use of an associated SELECT statement. Most SQL statements that apply to a database table can also be applied to a data view.

Syntax

CREATE VIEW ViewName (Column1, Column2…)AS Select-Statement;

Full Syntax

Example

In this example, we would like to create a data view to store the Book ID of those library books that are currently on loan and their corresponding borrowers (Student ID and Name).

CREATE VIEW BookOnLoan_n_Borrower_View (StdID, Name, BookID)AS SELECT Student.StdID, Name, BookID FROM Student, LoanRecord WHERE Student.StdID = LoanRecord.StdID AND status='1';

Sample Query Q29_Create_View Want to Try?

Result

A data view known as BookOnLoan_n_Borrower_View is created.

The data view has the following content.

26

Page 27: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Delete a data view

A data view can be deleted with the use of the DROP VIEW statement.

Syntax

DROP VIEW ViewName;

Full syntax

Example

The BookOnLoan_n_Borrower_View data view created earlier can be removed with the following SQL statement.

DROP VIEW BookOnLoan_n_Borrower_View;

Sample Query Q29_Drop_View Want to Try?

Result

The BookOnLoan_n_Borrower_View data view is removed.

27

Page 28: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Updating Data in a Table

Apart from retrieving data from a table, we can also modify selected data in a table by using the UPDATE statement and delete selected row(s) from a table.

Update the value in a column

To modify values in a selected column of one or more rows, we can use the UPDATE … SET statement.

Syntax

UPDATE TableNameSET Column = NewValueWHERE Condition(s) The WHERE clause is optional.

Full syntax

If the WHERE clause is not used, the value in the specified column of each row will be changed to the new value.

Example

Suppose we had wrongly put ‘1C’ as the value of the ‘Class’ field for students in Class 2C (and no records for students from Class 1C have been entered), the problem can be rectified by the following SQL statement.

UPDATE Student SET class = '2C'WHERE class='1C';

Sample Query Q7_1_updatetable Want to Try?

Result

Teaching remark Except for numeric values, the operand(s) of the operator must be enclosed by a

pair of single quotation marks ‘’.

28

Page 29: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Update values in a number of columns

To modify values in a number of columns, we can use the following statement.

Syntax

UPDATE TableNameSET Column1 = NewValue1, Column2 = NewValue2WHERE Condition(s) The WHERE clause is optional.

Full syntax

If the WHERE clause is not used, the values in the specified column(s) of each row will be changed to the new values.

Example

Suppose we have wrongly entered the name and phone number of a student with student ID equal to ‘0002011’ in the Student table earlier on, we can use the UPDATE statement to fix the problem. The name and phone number of the student should be “Chan Ming Wai” and ‘21111182’ respectively.

UPDATE Student SET Name = 'Chan Ming Wai', PhoneNo = '21111182'WHERE StdID='0002011';

Sample Query Q7_2_Updateseveralcolumn Want to Try?

Result

29

Page 30: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Delete record(s) from the table

To delete record(s) from a table, the DELETE Statement can be used.

Syntax

DELETE FROM TableNameWHERE Condition(s) The WHERE clause is optional.

Full syntax

Example 1

In this example, we would like to delete all records with the book ID “00000003” from a table “Book”.

DELETE *FROM BookWHERE BookID='00000003';

Sample Query Q8_1_Deletefield Want to Try?

Teaching remarks

As the BookID field serves as a foreign key in the LoadRecord table to the Book table and there is a corresponding record with the BookID equal to ‘00000003’ in the LoadRecord table, the above DELETE statement cannot be executed successfully. The corresponding rows in the LoadRecord table need to be removed in order to enable the query to run successfully.

Example 2

To delete all records in the table, we can simply use the DELETE statement without setting any condition. After running the following SQL statement successfully, the Book table will become empty.

DELETE FROM Book

Sample Query Q8_2_Deleteall Want to Try?

Teaching remark

Due to the same reason as indicated in the last “Teaching remark”, the above DELETE statement cannot be executed successfully unless no corresponding rows in the LoadRecord table are found.

30

Page 31: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Result Presentation

For various reasons, users may want to organize the result of a query in ascending or descending order of some selected fields in some occasions. In other occasions, they may be interested in the value of some aggregated attribute of the retrieved data, e.g., the total number of books that a student has ever borrowed. The former can be achieved with the use of the ORDER BY clause whereas the latter can be done with the use of the GROUP BY clause, both in a SELECT statement.

The ORDER BY clause

A query result can be sorted in ascending or descending lexicographical order of one or more selected sort fields. A lexicographical ordering refers to how characters are ordered in the corresponding encoding table.

Syntax

SELECT Column(s) FROM TableNameORDER BY Column1 [ASC|DESC], Column2 [ASC|DESC], ...

Full syntax

Optional parts are put inside square brackets. A vertical bar stands for disjunction. Thus [ASC|DESC] means that a user may use none of the keywords, or either one.

Teaching remarks The sort fields may or may not be selected for retrieval purposes. The default sorting order is in lexicographical order.

Example 1

Suppose we would like to sort all rows in the Student table in ascending order of the student name.

SELECT * FROM StudentORDER BY Name

Sample Query Q9_1_sort

Result

31

Page 32: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Example 2

In the following example, we retrieve all rows in the Student table in ascending order of the Class field.

SELECT * FROM StudentORDER BY Class ASC

Sample Query Q9_2_SortASC

Result

Example 3

In this example, we would like to sort all records in the Student table in two levels: first in descending order of the Class field, then in ascending order of the Name field.

SELECT * FROM StudentORDER BY Class DESC, Name ASC

Sample Query Q9_2_SortASC2

Result

32

Page 33: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The GROUP BY … HAVING clause

To facilitate the users to do data analysis, grouping the result in a suitable way is sometimes required. This can be achieved with the use of the GROUP BY clause.

Syntax

SELECT Column(s) FROM TableNameGROUP BY Column1, Column2, ...HAVING Condition(s) The HAVINIG clause is optional.

Full syntax

Example 1

To count the number of students who have borrowed books in each class, we can use the GROUP BY clause (without the HAVING part) as below:

SELECT Class, count(*) AS NumFROM StudentGROUP BY ClassORDER BY Class DESC;

Sample Query Q10_Group

The AS keyword enables a user to assign a new label to a selected object. In the above example, the output of the aggregate function COUNT(*) which counts the number of output rows in each group (as specified by the GROUP BY clause) is labeled as ‘Num’.

Result

A clause which can only be used after the GROUP BY clause is HAVING. It comes after GROUP BY (and before ORDER BY if the clause is needed as well). The purpose of HAVING is to set selection criteria based on some aggregate values. The following SQL query counts the number of students in each of the classes such that its students owe the library more than 20 dollars overdue fine in aggregate.

33

Page 34: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Example 2

SELECT Class, Count(*) AS NumFROM StudentGROUP BY ClassHAVING SUM(OverduePay) > 20 ORDER BY Class DESC;

Sample Query Q10_Group_By-Having

The result of the query is as follows:

Teaching remarks

The WHERE clause sets selection criteria for the SELECT statement based on non-aggregate value(s) only. Any selection based on aggregate value must be done with the HAVING clause. A common student mistake is to use some aggregate function(s) in a WHERE clause. Aggregate functions do not work in a WHERE clause because it is given no information as to how records (i.e., table rows) are to be grouped. Such grouping information is provided to the HAVING clause by the GROUP BY clause.

The SELECT statement can reference values generated by the aggregate functions or columns specified in the GROUP BY clause only.

SELECT Class, Count(*) AS NumFROM StudentGROUP BY ClassHAVING SUM(OverduePay) > 20 AND Class > "3"ORDER BY Class DESC;

The HAVING clause can reference values generated by the aggregate functions or columns specified in the GROUP BY clause only.

As shown in the above example, the parameter (which is a column) specified in an aggregate function referred to by the HAVING clause is not needed to be included as a column referred to by the SELECT statement.

34

Page 35: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Operators Used with WHERE

A number of operators can be used in conjunction with the WHERE clause to specify the condition(s) for data retrieval.

The LIKE operator

Earlier on, we learnt to use the SELECT and WHERE statement to select data from one or more table that meet specified condition(s). Most of those conditions require an exact match. Sometimes, we may interest to retrieve data based on a partial match. This is supported in SQL by the LIKE operator. Wildcard characters (‘_’ and ‘%’) are used for specifying a retrieving pattern. The ‘_’ stands for any character while the

‘%’ means all character combinations (including NULL) are allowed.

Teaching remarks LIKE can only be used with CHAR and VARCHAR field types. Unless the SQL-92 syntax is selected in Microsoft Access, the database uses ‘?’

and ‘*’ for ‘_’ and ‘%’ respectively.

Syntax

SELECT Column(s) FROM TableNameWHERE Column LIKE pattern

Full Syntax

Example 1

In the following example, all students records with the name started with ‘Ch’ are retrieved.

SELECT *FROM StudentWHERE Name LIKE 'Ch%';

Sample Query Q11_like1 Want to Try?

Result

35

Page 36: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Example 2

In this example, we would like to select all students records with the student name’s second letter being ‘h’ and last letter being ‘i’.

SELECT * FROM StudentWHERE Name LIKE '_h%i';

Sample Query Q11_like2 Want to Try?

Result

Example 3

The following query selects all students records with at least one ‘u’ character in.the student name.

SELECT * FROM StudentWHERE Name LIKE '%u%'

Sample Query Q11_like3 Want to Try?

Result

36

Page 37: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The IN operator

When using the WHERE clause, it is possible to use IN to specify a list of values for a selected column that the SELECT statement requires the retrieved rows to have.

Syntax

SELECT Column(s) FROM TableNameWHERE Column IN (value1,value2,...)

Full Syntax

The value list (which is an operand) of the IN operator can be list explicitly as shown in the above syntax or generated by another SELECT statement. The latter is known as nested SELECT statement which will be covered later.

Example

We use the IN operator to select records of student(s) whose name is ‘Cheung Ka Fai’ or ‘Wong Wai Ming’.

SELECT *FROM StudentWHERE Name IN ('Cheung Ka Fai','Wong Wai Ming');

Sample Query Q12_in Want to Try?

Result

37

Page 38: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The BETWEEN Operator

We can specify a range of values for a selected column using the BETWEEN operator within a SELECT statement in order to require the corresponding field values of the retrieved rows to be within the specified value range in an inclusive manner.

Syntax

SELECT Column(s) FROM TableNameWHERE Column BETWEEN value1 AND value2

Full Syntax

Example

We use the BEWTEEN operator to select students with their student ID between 0002013 and 0002015.

SELECT *FROM StudentWHERE StdID Between '0002013' AND '0002015';

Sample Query Q13_between

Result

Teaching remark

The result of the above query may be different in various databases as some may contain the boundary records while some may not. However, according to the SQL-92 and SQL-99 standards, boundary records are to be included.

38

Page 39: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The AND Operator

By using the AND operator, we can require retrieval row(s) of data to meet a number of filtering conditions simultaneously.

Syntax

SELECT Column FROM TableNameWHERE Condition1 AND Condition2

Full Syntax

Example

The following query retrieve student record(s) such that the student is in class 2C and has overdue fine to settle.

SELECT * FROM StudentWHERE Class = '2C' AND OverduePay > 0

Sample Query Q14_AND

Result

The OR operator

By using the OR operator, we can select data rows such that at least one of its operands (which is a condition) is fulfilled.

Syntax

SELECT Column FROM TableNameWHERE Condition1 OR Condition2

Full Syntax

Example

The following query retrieves the student records from Student table such that the student is either a member of Class 2C or his/her name being “Chang Wai Yee”.

SELECT *FROM StudentWHERE Class='2C' OR Name='Chang Wai Yee';

Sample Query Q15_OR

39

Page 40: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Result

Example - using both AND and OR Operators in a query

Retrieve the student record of a Class 2C student whose name is “Chan Ming Wai” and the record of another student whose name is “Chang Wai Yee”

SELECT *FROM StudentWHERE (Class='2C' AND Name='Chan Ming Wai') OR Name='Chang Wai Yee';

Sample Query Q16_ANDOR

Result

40

Page 41: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Add alias to a column

Sometimes, the column name of the resultant table may not be expressive enough for display purpose. In this case, we can assign alias to the column of resultant table using the AS operator.

Syntax

SELECT Column1 AS ColumnAlias1, Column2 AS ColumnAlias2,...FROM TableName

Full Syntax

Example

The following query assigns more meaningful labels to the fields retrieved from the Student table.

SELECT StdID AS Student_ID, Name AS Student_Name, PhoneNo AS Phone_NumberFROM Student;

Sample Query Q17_aliases

Result

41

Page 42: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Joining Tables

Sometimes, we may need to retrieve data from two or more tables. In this case, we can join tables with the use of the relevant field(s) of the tables. In most cases, tables are joined according to search conditions that find only the rows with matching values; this type of join is known as an inner equijoin. Occasionally, non-equijoins, for example, that express a greater-than or less-than relationship, may be used. In some other occasions, decision-support analysis may require outer joins, which retrieve both matching and non-matching rows. The three types of outer joins are left outer join, right outer join, and full outer join.

Equijoin

We can retrieve data from tables by setting up retrieval condition that requires the column values of the “joined” tables being equal. In brief, equijoin is a join in which rows from two tables are combined and added to the result set when there are equal values in the joined columns.

Syntax

SELECT TableName1.Column11, TableName1.Column12,...TableName2.Column21,TableName2.Column22,...FROM TableName1, TableName2WHERE equality_condition(s)

Full Syntax

Example 1 (equijoin with repeated column)

In this example, we find details of students and the library service that they have accessed (i.e., borrow/return/reserve a book). Output will not include any student details who did not use any library service before. In order to do so, we retrieve all details from the LoanRecord table and the Student table where the value of column “StdID” in both tables are equal.

SELECT *FROM LoanRecord, StudentWHERE LoanRecord.StdID=Student.StdID;

Sample Query Q18_EJoin

Result

42

Page 43: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

In the above example, the “StdID” field occurs twice in the equijoin output as it can be found in both the LoanRecord and Student tables.

Obviously there is no point in repeating the same piece of information. One of the two identical columns can be eliminated by changing the SELECT list. The result is called a natural join. More exactly, the natural join operation produces a Cartesian product of its two argument tables, performs a selection that enforces equality on attributes that appears in both tables, and removes duplicate attributes at the end.

Example 2 (natural join)

Suppose we not only want to find the list of students who have accessed library services, but also the title of books the student borrowed/returned/reserved. To do this, we join all the three tables with the following query.

SELECT LoanRecord.LoanRecID, Student.Name, Book.TitleFROM LoanRecord, Student, BookWHERE LoanRecord.StdID=Student.StdID AND LoanRecord.BookID=Book.BookID;

Sample Query Q19_EJoin2

By selecting the fields of interest only, the repeated occurrences of the same piece of information shown in the previous example disappear, i.e. a natural join. In that sense, the natural join is a subtype of the equijoin.

Result

Teaching remark In SQL, all join conditions are to be specified explicitly. The fact that two tables

have the same attribute name, (e.g. StdID in the LoadRecord and Student tables), does not mean that a join will be done between them automatically. Omitting the join conditions when joining tables will result in an output that corresponds to the Cartesian product of the rows in the selected tables.

43

Page 44: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The NATURAL JOIN operator

A NATURAL JOIN operation uses the column in both tables that has the same name (and type) to perform an equijoin. However it relies on the SELECT statement to avoid the retrieval of same pieces information for implementing the natural join operation.

Syntax

SELECT TableName1.Column11, TableName1.Column12,...FROM TableName1NATURAL INNER JOIN TableName2

Full Syntax

Example

In this example, we search the list of students who have at least made use of the library service once, just like the example showed in the second equijoin example. However, this time we do the same query with natural join.

SELECT DISTINCT Student.NameFROM StudentNATURAL INNER JOIN LoanRecord

Result

Name

Chan Ming Wai

Cheung Ka Fai

Wong Wai Ming

Note that the multiple occurrences of output records are eliminated with the use of DISTINCT.

Teaching remark NATURAL JOIN is not supported by Access 2003. However it is easy to model

the NATURAL JOIN operation with the INNER JOIN operation as shown in the next section.

44

Page 45: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The INNER JOIN operator

Rows of two tables can be joined together by using the INNER JOIN operator when the selected rows meet some specified condition(s). Rows that fail to meet the conditions will not be selected. As the prevailing condition type used is the test of equality, INNER JOIN is often used to implement the concept of equijoin.

Syntax

SELECT Column1, Column2,…FROM TableName1INNER JOIN TableName2ON Condition(s)

Full Syntax

Example

This query below models the NATURAL JOIN example given in the last section.

SELECT distinct Student.NameFROM StudentINNER JOIN LoanRecord on (Student.stdid = LoanRecord.stdid)

Sample Query Q19_InnerJoin

Resultant Table:

45

Page 46: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The LEFT (OUTER) JOIN operator

The result of a LEFT JOIN operation contains every row from the first table and all matching rows in the second table. Rows found only in the second table are not displayed. If the rows in the first table have no match in the second table, fields corresponding to the second tables in the output rows will be filled with null.

Syntax

SELECT Column1, Column2,...FROM TableName1LEFT JOIN TableName2ON Condition(s)

Full Syntax

Example

To view all library services that the students have accessed as well as those students who have not made use of the library services at all, we can use the following query.

SELECT Student.StdID, Student.Name, LoanRecord.LoanRecIDFROM Student LEFT JOIN LoanRecord ON LoanRecord.StdID=Student.StdID;

Sample Query Q19_LeftJoin

Result

46

Page 47: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The RIGHT (OUTER) JOIN operator

The RIGHT JOIN will return all the rows contained in the second table and all matching rows in the first table. If there is no match in the first table, the fields corresponding to the first tables in the output rows will be given a null.

Syntax

SELECT Column1, Column2,...FROM TableName1RIGHT JOIN TableName2ON Condition(s)

Full Syntax

Example

To view the student ID, student name, and the types of library services that the student had made use of, we may use the following query.

SELECT Student.StdID, Student.Name, LoanRecord.LoanRecIDFROM Student RIGHT JOIN LoanRecord ON LoanRecord.StdID=Student.StdID;

Sample Query Q19_RightJoin

Result

47

Page 48: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The FULL (OUTER) JOIN operator

Unlike LEFT JOIN and RIGHT JOIN which do not include all non-matching rows into the output table, the result of the FULL (OUTER) JOIN contains those rows that are unique to each table, as well as those rows that are common to both tables. The fields corresponding to any non-matching table rows will be given a null in the relevant output rows.

Syntax

SELECT Column1, Column2,...FROM TableName1OUTER JOIN TableName2ON Condition(s)

Full Syntax

Example

We modify the RIGHT JOIN example by replacing the RIGHT JOIN by a FULL JOIN.

SELECT Student.StdID, Student.Name, LoanRecord.LoanRecIDFROM StudentFULL JOIN LoanRecordON LoanRecord.StdID = Student.StdID

Want to Try?

Result

StdID Name LoanRecID0002011 Chan Ming Wai 20002011 Chan Ming Wai 50002014 Chang Wai Yee0002013 Cheung Ka Fai 40002015 Lee Oi Lam0002016 Sze Yuk Ki0002012 Wong Wai Ming 10002012 Wong Wai Ming 3

Teaching remark FULL (OUTER) JOIN is not supported by Access 2003. However it is easy to

model the FULL (OUTER) JOIN operation by “integrating” the results of the LEFT JOIN operation and the RIGHT JOIN operation as shown in the next section.

48

Page 49: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Combining Query Results

Results of two queries can be merged to a single resultant table through UNION and INTERSECT. The former put all component query results into the resultant table whereas the latter keeps rows that appear in results of both component queries only. Query results can be removed from another query results using MINUS. Another way to combine query results together is known as nested query which is implemented with the use of multiple SELECT statements. In a nested query, the result of a SELECT statement is used as a part of another SELECT statement.

The UNION operator

It may be useful to merge the results of two queries together to form a single output table. This can be done with the UNION operator. UNION only works if each query in the statement has the same number of columns, and each pair of the corresponding columns is of the same type. When using UNION, all duplicating output rows are eliminated.

Syntax

SQL_Statement1UNIONSQL_Statement2

Example

The following example implements the FULL OUTER JOIN example using LEFT JOIN, RIGHT JOIN and UNION.

SELECT Student.StdID,Student.Name,LoanRecord.LoanRecIDFROM StudentLEFT JOIN LoanRecordON LoanRecord.StdID = Student.StdIDUNION SELECT Student.StdID,Student.Name,LoanRecord.LoanRecIDFROM StudentRIGHT JOIN LoanRecordON LoanRecord.StdID = Student.StdID;

Sample Query Q20_Union Want to Try?

Result

49

Page 50: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The INTERSECT operator

The INTERSECT operator returns only those rows that are common to the results returned by two or more query expressions. INTERSECT only works if each query in the statement has the same number of columns, and each pair of the corresponding columns is of the same type. When using INTERSECT, all duplicating output rows are eliminated.

Syntax

SQL_Statement1INTERSECTSQL_Statement2

Example

The following query identifies those students whose names have the substrings “Wai” and “Chan”.

SELECT NameFROM StudentWHERE Name LIKE ‘%Wai%’INTERSECTSELECT NameFROM StudentWHERE Name LIKE ‘%Chan%’

Want to Try?

Result

NameChan Ming WaiChang Wai Yee

Teaching remark INTERSECT is not supported by Access 2003.

50

Page 51: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The EXCEPT/MINUS operator

The EXCEPT/MINUS operator returns only those rows that appear in the first query results but not the second query results. When using EXCEPT/MINUS, all duplicating output rows are eliminated. EXCEPT is defined in SQL92 whereas MINUS is used by Oracle for the same purpose.

Syntax

SQL_Statement1EXCEPTSQL_Statement2

Example

The following query identifies those students whose names have the substring “Wai” but not “Chan”.

SELECT NameFROM StudentWHERE Name LIKE ‘%Wai%’EXCEPTSELECT NameFROM StudentWHERE Name LIKE ‘%Chan%’

Want to Try?

Result

NameWong Wai Ming

Teaching remark EXCEPT/MINUS is not supported by Access 2003.

51

Page 52: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Using nested SELECT statement

Besides using UNION function, we can use the nested SELECT statement to combine query results in a way that the result of a SELECT statement can be used as the values of some input parameter for another SELECT statement. For simplicity, we give the syntax of nested SELECT statements that use the =ANY operator or the IN operator only. Some other commonly used operators in nested SELECT statement are >ALL, <ALL, >=ALL, and <=ALL. The latter two are widely used to find the maximum and minimum values from a list of selected values respectively (see Example2)

Syntax (=ANY)

SELECT (Column1, Column2, ...)FROM TableName1,TableName2WHERE Column =ANY SELECT (Column1, Column2, ...) FROM TableName3

Full Syntax

Note that the =ANY operator can be replaced by the IN operator in the above case.

Example1

In this example, we would like to find students in 2C class who had used some library service(s) before.

SELECT nameFROM StudentWHERE (StdID =ANY (SELECT StdID FROM LoanRecord)) AND Class = '2C';

Sample Query Q21_NestSelect

Another way to implement the above query is as follows:

SELECT DISTINCT NameFROM Student, LoanRecordWHERE Student.StdID = LoanRecord.StdID AND Class = '2C';

To save the effort of referencing the LoanRecord table given earlier, its table content is displayed again as below.

Table “LoanRecord”

LoanRecID StdID BookID DateOfBorrow Status1 0002012 00000001 20051001 12 0002011 00000002 20020112 23 0002012 00000003 20031211 24 0002013 00000002 20031001 25 0002011 00000002 20051018 1

52

Page 53: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Result

Example2

In this example, we would like to find the student who owes the large amount of overdue fine to the library.

SELECT Name, OverduePayFROM StudentWHERE OverduePay >=ALL (SELECT OverduePay from Student)

Sample Query Q21_NestSelect_2

Result

53

Page 54: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Arithmetic Operators/Functions

The following arithmetic operators/functions can be used in relevant expressions within a SQL statement.

Operator/Function Description+ The arithmetic add operator or unary plus operator- The arithmetic subtract operator or unary minus

operator* The multiply operator (a shorthand for all columns

after the SELECT keyword)/ The arithmetic divide operator

ABS(numeric-expresssion)

The ABS() function turns the value of a numeric expression into its absolute value.

Table 8. Some SQL arithmetic operators/functions.

For example, if the loan period for a library item is 28 days, we can use NOW()+28 to compute the due date for return if the item is loaned to a library user now.

String Functions

Some SQL-92 string functions are included below.

Function Type DescriptionCHAR_LENGTH(string-expression) orCHARACTER_LENGTH(string-expression) for SQL92

LENGTH(string-expression)for Oracle

LEN(string-expression)for Access

Returns the number of characters in a string-expression.

Example The following statement will return the value 7.

SELECT CHAR_LENGTH('library')

LOWER(string-expression)for SQL92

LCASE(string-expression)for Access

Converts all letters in a string to lower case.

Example The following statement will return 'library'.

SELECT LOWER('Library')

UPPER(string-expression)for SQL92

UCASE(string-expression)

Converts all letters in a string to upper case.

Example The following statement will return 'LIBRARY'.

54

Page 55: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

for AccessSELECT UPPER('Library')

TRIM(string-expression)for both SQL92 and Access

Removes leading and trailing blanks from a string.

Example The following statement will return the value 9.

SELECT CHAR_LENGTH(TRIM(' chocolate ' )

SUBSTRING/SUBSTR(string-expression, start, length)for SQL92

MID(string-expression, start, length)for Access

Returns a substring of a string.

ExampleThe following statement will return “library”.

SELECT SUBSTRING('library system', 1, 7)

Table 9. Some SQL string functions.

Teaching remark It appears that many databases introduce their own built-in functions although

many of those functions in fact offer the same functionality as the corresponding SQL-92 built-in functions. It is important to check carefully before teaching the topic.

55

Page 56: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Aggregate Functions

Aggregation functions enable the user to perform tasks on more than just one record. They can be used to perform data calculations, such as maximum, minimum, or average.

Function UsageAVG(expression) Computes the average value of a column by the expression COUNT(expression) Counts the rows defined by the expressionCOUNT(*) Counts all rows in the specified table or viewMIN(expression) Finds the minimum value in a column by the expressionMAX(expression) Finds the maximum value in a column by the expressionSUM(expression) Computes the sum of column values by the expression

Table 10. Some SQL aggregate functions.

The AVG function

The AVG function returns the average value of the selected column. Note that any null values will not be included in the calculation.

Syntax

SELECT AVG(Column) FROM TableName

Example

We can calculate the average overdue payment per library user by using the AVG

SELECT AVG(OverduePay) AS Average_Overdue_Payment FROM Student

Sample Query Q22 AVG

Result

Note that the overdue payment of Cheung Ka Fai (student ID 0002013) is set to zero and thus the computation of the average value has included the number. If the field is set to null, the average overdue payment per user will be 13.6 instead.

56

Page 57: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The COUNT function

COUNT function is useful when we would like to find the total number of records retrieved subject to certain selection criteria. There are two kinds of COUNT functions. They are COUNT(Expression) and COUNT (*). The first counts for the non-null records returned by the evaluation of the Expression (which is typically a column name). The second returns the total number of records based on the selection criteria specified in the SELECT statement, no matter the records are NULL or not.

Syntax - COUNT (column)

SELECT COUNT(Column) FROM TableName

Example

The following query counts the number of inactive library users who have never made use of any library service.

SELECT Count(*)-Count(LoanRecord.Status) AS Number_of_idle_usersFROM Student LEFT JOIN LoanRecord ON Student.StdID = LoanRecord.StdID;

Sample Query Q23_COUNT

Result

Syntax - COUNT(*)

SELECT COUNT(*) FROM TableName

Example

The following query counts the number of students whose names start with “Chan”.

SELECT Count(*) AS Number_of_studentsFROM StudentWHERE (Student.Name) LIKE "Chan%";

Sample Query Q24_COUNT

Result

57

Page 58: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The MAX function

The MAX function finds the maximum value in a selected table column.

Syntax

SELECT MAX(Column) FROM TableName

Example

The following query finds the student who owes to the library the largest amount of overdue fine.

SELECT Name, OverduePay FROM Student WHERE OverduePay = (SELECT MAX(OverduePay) FROM Student)

Sample Query Q25_MAX

The following SQL script implements the same query without using the MAX function.

SELECT Name, OverduePay FROM Student WHERE OverduePay >=ALL (SELECT OverduePay FROM Student)

Result

Teaching remark Many students may produce a SQL script similar to the one below for the above

query.

SELECT Name, MAX(OverduePay)FROM Student

The above query violates the syntactic rules of SQL. The problems lies on the fact that a number of student names can be retrieved from the Student table (which correspond to several rows in the output table) but all aggregate functions like MAX() returns exactly one row in the output table only.

58

Page 59: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The MIN function

The MIN function finds the minimum value in a selected table column.

Syntax

SELECT MIN(Column) FROM TableName

Example

The following query finds the student who owes to the library the least amount of overdue fine.

SELECT Name, OverduePay AS Overdue_FineFROM Student WHERE OverduePay = (SELECT MIN(OverduePay) FROM Student)

Sample Query Q26_MIN

Teaching remark The following SQL script implements the same query without using the MIN

function.

SELECT Name, OverduePay FROM Student WHERE OverduePay <=ALL (SELECT OverduePay FROM Student)

Result

59

Page 60: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

The SUM Function

The SUM function computes the sum of values from a selected column.

Syntax

SELECT SUM(Column) FROM TableName

Example

The query below gives the total amount of outstanding overdue fine for each class of students.

SELECT Class, SUM(OverduePay) AS Overdue_FineFROM Student group by Class

Sample Query Q27_SUM

Result

60

Page 61: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Miscellaneous SQL Features

Create/Drop Table Index

Indexing is commonly used to enhance the performance of a database system. With the CREATE INDEX statement, we can create indexing structures (which is a pre-processed list) for database tables so as to provide an efficient access path to various table rows. When running a query, database will examine any relevant index for a more efficient data access instead of traversing the entire table. To delete an index, the DROP INDEX statement can be used.

Syntax (CREATE INDEX)

CREATE INDEX IndexNameON TableName(Column1,Column2,...)

F u ll Syntax

Syntax (DROP INDEX)

DROP INDEX IndexNameON TableName

Example (CREATE INDEX)

In the following, we create an index for the class and student number combination in the Student table as the two fields are often accessed by various queries.

CREATE INDEX ind_class_stdIDON Student (class, StdID)

Sample Query Q28_CREATE_INDEX

Result

61

Page 62: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Example (DROP INDEX)

The following delete the index that was created in the previous example.

DROP INDEX ind_class_stdIDON Student

Sample Query Q28_DROP_INDEX

Result

62

Page 63: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Exporting Data from MS Access

Most databases are equipped with some data export facility so that data within a database can be “exported” for the use of other applications. Many of them also allow not only export of data, but also export of table structures, queries and other database objects. Those features enable user to migrate their data base from one database to another database. In this section, we will briefly mention the data export facility in Microsoft Access. Specifically it allows its users to export data as text, HTML or Microsoft Excel format.

Export Data from an MS Access Database to Another Access Database

1. Open the existing MS database and select the database object that you want to export by clicking on it.

63

Page 64: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

2. Click File Export from the menu bar

3. Enter the file name of another Access database (.mdb) and click the Export button

64

Page 65: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

Export Data from an MS Access Database in other file formats

1. Open the existing MS database and select the database object that you want to export by clicking on it.

2. Click File Export from the menu bar

65

Page 66: Introduction_to_SQL_e_v11.doc.doc.doc

ASCA & ALCS Curriculum Databases V1.1 26/1/2006

3. Change the file format to “TEXT”,”HTML” or “EXCEL”

4. Enter the file name and click the Export button

- END -

66


Recommended