Introduction To SQL
Introduction To SQL
INTRODUCTION TO
SQL
Mr. Zeeshan Ali
Lecturer CS
Govt.Postgraduate College Sheikhupura
[email protected]
2
Chapter 5 - Objectives
• Purpose and importance of SQL.
• How to retrieve data from database using SELECT and:
• Use compound WHERE conditions.
• Sort query results using ORDER BY.
• Use aggregate functions.
• Group data using GROUP BY and HAVING.
• Use subqueries.
Chapter 5 - Objectives
• Join tables together.
• Perform set operations (UNION, INTERSECT, EXCEPT).
Objectives of SQL
• Ideally, database language should allow user to:
• create the database and relation structures;
• perform insertion, modification, deletion of data from relations;
• perform simple and complex queries.
• Must perform these tasks with minimal user effort and
command structure/syntax must be easy to learn.
Objectives of SQL
• SQL is a transform-oriented language with 2 major
components:
• A DDL for defining database structure.
• A DML for retrieving and updating data.
Objectives of SQL
• SQL is relatively easy to learn:
Objectives of SQL
• Consists of standard English words:
Objectives of SQL
• Can be used by range of users including DBAs,
management, application developers, and other types of
end users.
History of SQL
• In 1974, D. Chamberlin (IBM San Jose Laboratory)
defined language called ‘Structured English Query
Language’ (SEQUEL).
• A revised version, SEQUEL/2, was defined in 1976 but
name was subsequently changed to SQL for legal
reasons.
History of SQL
• Still pronounced ‘see-quel’, though official pronunciation is
‘S-Q-L’.
• IBM subsequently produced a prototype DBMS called
System R, based on SEQUEL/2.
• Roots of SQL, however, are in SQUARE (Specifying
Queries as Relational Expressions), which predates
System R project.
History of SQL
• In late 70s, ORACLE appeared and was probably first
commercial RDBMS based on SQL.
• In 1987, ANSI and ISO published an initial standard for
SQL.
• In 1989, ISO published an addendum that defined an
‘Integrity Enhancement Feature’.
• In 1992, first major revision to ISO standard occurred,
referred to as SQL2 or SQL/92.
• In 1999, SQL:1999 was released with support for object-
oriented data management.
• In late 2003, SQL:2003 was released.
Importance of SQL
• SQL has become part of application architectures such as
IBM’s Systems Application Architecture.
• It is strategic choice of many large and influential
organizations (e.g. X/OPEN).
• SQL is Federal Information Processing Standard (FIPS) to
which conformance is required for all sales of databases
to American Government.
Importance of SQL
• SQL is used in other standards and even influences
development of other standards as a definitional tool.
Examples include:
• ISO’s Information Resource Directory System (IRDS) Standard
• Remote Data Access (RDA) Standard.
Literals
• Literals are constants used in SQL statements.
SELECT Statement
SELECT [DISTINCT | ALL]
{* | [columnExpression [AS newName]] [,...] }
FROM TableName [alias] [, ...]
[WHERE condition]
[GROUP BY columnList] [HAVING condition]
[ORDER BY columnList]
SELECT Statement
FROM Specifies table(s) to be used.
WHERE Filters rows.
GROUP BY Forms groups of rows with same
column value.
HAVING Filters groups subject to some
condition.
SELECT Specifies which columns are to
appear in output.
ORDER BY Specifies the order of the output.
SELECT Statement
• Order of the clauses cannot be changed.
SELECT PropertyNo
FROM Viewing;
SELECT *
FROM Branch
WHERE city = ‘London’ OR city = ‘Glasgow’;
39
© Pearson Education Limited 1995, 2005
40
50
© Pearson Education Limited 1995, 2005
Example 5.14 Use of COUNT(DISTINCT)
51
© Pearson Education Limited 1995, 2005
Example 5.15 Use of COUNT and SUM
52
© Pearson Education Limited 1995, 2005
Example 5.16 Use of MIN, MAX, AVG
53
© Pearson Education Limited 1995, 2005
54
SELECT branchNo,
COUNT(staffNo) AS myCount,
SUM(salary) AS mySum
FROM Staff
GROUP BY branchNo
HAVING COUNT(staffNo) > 1
ORDER BY branchNo;
Subqueries
• Some SQL statements can have a SELECT embedded
within them.
• A subselect can be used in WHERE and HAVING
clauses of an outer SELECT, where it is called a
subquery or nested query.
• Subselects may also appear in INSERT, UPDATE, and
DELETE statements.
Subquery Rules
• ORDER BY clause may not be used in a subquery
(although it may be used in outermost SELECT).
• Subquery SELECT list must consist of a single column
name or expression, except for subqueries that use
EXISTS.
• By default, column names refer to table name in FROM
clause of subquery. Can refer to a table in FROM using
an alias.
Subquery Rules
• When subquery is an operand in a comparison,
subquery must appear on right-hand side.
• A subquery may not be used as an operand in an
expression.
Multi-Table Queries
• Can use subqueries provided result columns come from
same table.
• If result columns come from more than one table must
use a join.
• To perform join, include more than one table in FROM
clause.
• Use comma as separator and typically include WHERE
clause to specify join column(s).
Multi-Table Queries
• Also possible to use an alias for a table named in FROM
clause.
• Alias is separated from table name with a space.
Computing a Join
Procedure for generating results of a join are:
1. Form Cartesian product of the tables named in FROM
clause.
2. If there is a WHERE clause, apply the search condition
to each row of the product table, retaining those rows that
satisfy the condition.
3. For each remaining row, determine value of each item in
SELECT list to produce a single row in result table.
Computing a Join
4. If DISTINCT has been specified, eliminate any duplicate
rows from the result table.
5. If there is an ORDER BY clause, sort result table as
required.
• SQL provides special format of SELECT for Cartesian
product:
Outer Joins
• If one row of a joined table is unmatched,
row is omitted from result table.
• Outer join operations retain rows that do
not satisfy the join condition.
• Consider following tables:
Outer Joins
• The (inner) join of these two tables:
Outer Joins
• Result table has two rows where cities are same.
• There are no rows corresponding to branches in Bristol
and Aberdeen.
• To include unmatched rows in result table, use an Outer
join.
(SELECT * ...)
(SELECT city
FROM Branch
WHERE city IS NOT NULL) UNION
(SELECT city
FROM PropertyForRent
WHERE city IS NOT NULL);
(SELECT *
FROM Branch
WHERE city IS NOT NULL)
UNION CORRESPONDING BY city
(SELECT *
FROM PropertyForRent
WHERE city IS NOT NULL);
SELECT b.city
FROM Branch b PropertyForRent p
WHERE b.city = p.city;
• Or:
SELECT DISTINCT city FROM Branch b
WHERE EXISTS
(SELECT * FROM PropertyForRent p
WHERE p.city = b.city);
INSERT
INSERT INTO TableName [ (columnList) ]
VALUES (dataValueList)
INSERT
• dataValueList must match columnList as follows:
• number of items in each list must be same;
• must be direct correspondence in position of items in two lists;
• data type of each item in dataValueList must be compatible with
data type of corresponding column.
INSERT … SELECT
• Second form of INSERT allows multiple rows to be
copied from one or more tables to another:
UPDATE
UPDATE TableName
SET columnName1 = dataValue1
[, columnName2 = dataValue2...]
[WHERE searchCondition]
UPDATE
• WHERE clause is optional:
• if omitted, named columns are updated for all rows in table;
• if specified, only those rows that satisfy searchCondition are
updated.
• New dataValue(s) must be compatible with data type for
corresponding column.
UPDATE Staff
SET salary = salary*1.05
WHERE position = ‘Manager’;
UPDATE Staff
SET position = ‘Manager’, salary = 18000
WHERE staffNo = ‘SG14’;
DELETE
DELETE FROM TableName
[WHERE searchCondition]