0% found this document useful (0 votes)
36 views93 pages

Essential SQL Basics and Commands

The document provides an overview of Basic SQL, covering data definition, data types, constraints, and basic retrieval queries. It explains the significance of SQL in relational databases, the structure of SQL commands such as CREATE TABLE, and the types of data supported. Additionally, it discusses constraints, including primary and foreign keys, and the use of SQL for querying data with examples of SELECT statements.

Uploaded by

vroanimations
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views93 pages

Essential SQL Basics and Commands

The document provides an overview of Basic SQL, covering data definition, data types, constraints, and basic retrieval queries. It explains the significance of SQL in relational databases, the structure of SQL commands such as CREATE TABLE, and the types of data supported. Additionally, it discusses constraints, including primary and foreign keys, and the use of SQL for querying data with examples of SELECT statements.

Uploaded by

vroanimations
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Copyright © 2016 Ramez Elmasri and Shamkant B.

Navathe
Unit 4

Basic SQL

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Outline (Part 1)
◼ SQL Data Definition and Data Types
◼ Specifying Constraints in SQL
◼ Basic Retrieval Queries in SQL
◼ INSERT, DELETE, and UPDATE Statements in
SQL

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Basic SQL
◼ SQL language
◼ Considered one of the major reasons for the
commercial success of relational databases
◼ SQL
◼ The origin of SQL is relational predicate calculus called
tuple calculus (see Ch.8) which was proposed initially
as the language SQUARE.
◼ SQL Actually comes from the word “SEQUEL” which was the
original term used in the paper: “SEQUEL TO SQUARE” by
Chamberlin and Boyce. IBM could not copyright that term, so they
abbreviated to SQL and copyrighted the term SQL.
◼ Now popularly known as “Structured Query Language”.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Data Definition, Data Types,
Standards
◼ Terminology:
◼ Table, row, and column used for relational model
terms relation, tuple, and attribute
◼ The language has features for : Data definition, Data
Manipulation, Transaction control (Transact-SQL, Ch.
20), Indexing (Ch.17), Security specification (Grant and
Revoke- see Ch.30), Active databases (Ch.26), Multi-
media (Ch.26), Distributed databases (Ch.23) etc.
◼ CREATE statement
◼ Main SQL command for data definition

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Schema and Catalog Concepts in
SQL
◼ Variations in existing RDBMS systems
◼ SQL schema
◼ Identified by a schema name
◼ Includes an authorization identifier and descriptors
for each element
◼ Schema elements include
◼ Tables, constraints, views, domains, and other
constructs
◼ Each statement in SQL ends with a semicolon

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Schema and Catalog Concepts in
SQL (cont’d.)
◼ CREATE SCHEMA statement
◼ CREATE SCHEMA COMPANY AUTHORIZATION
‘Jsmith’;
◼ Catalog
◼ Named collection of schemas in an SQL
environment
◼ SQL also has the concept of a cluster of catalogs.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The CREATE TABLE Command in
SQL
◼ Specifying a new relation
◼ Provide name of table
◼ Specify attributes, their types and initial
constraints
◼ Can optionally specify schema:
◼ CREATE TABLE [Link] ...
or
◼ CREATE TABLE EMPLOYEE ...

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The CREATE TABLE Command in
SQL (cont’d.)
◼ Base tables (base relations)
◼ Relation and its tuples are actually created and
stored as a file by the DBMS
◼ Virtual relations (views)
◼ Created through the CREATE VIEW statement.
Do not correspond to any physical file.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


COMPANY relational database
schema (Fig. 5.7)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


One possible database state for the
COMPANY relational database schema
(Fig. 5.6)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


One possible database state for the
COMPANY relational database schema –
continued (Fig. 5.6)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


An Example of CREATE Statement

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL CREATE TABLE data definition statements
for defining the COMPANY schema from Figure
5.7 (Fig. 6.1)

continued on next slide

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL CREATE TABLE data definition
statements for defining the COMPANY
schema from Figure 5.7 (Fig. 6.1)-continued

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The CREATE TABLE Command in
SQL (cont’d.)
◼ Some foreign keys may cause errors
◼ Specified either via:
◼ Circular references
◼ Or because they refer to a table that has not yet
been created
◼ DBA’s have ways to stop referential integrity
enforcement to get around this problem.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Attribute Data Types and Domains in
SQL
◼ Basic data types
◼ Numeric data types
◼ Integer numbers: INTEGER, INT, and SMALLINT
◼ Floating-point (real) numbers: FLOAT or REAL, and
DOUBLE PRECISION
◼ Character-string data types
◼ Fixed length: CHAR(n), CHARACTER(n)
◼ Varying length: VARCHAR(n), CHAR
VARYING(n), CHARACTER VARYING(n)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Attribute Data Types and Domains in
SQL (cont’d.)
◼ Bit-string data types
◼ Fixed length: BIT(n)
◼ Varying length: BIT VARYING(n)
◼ BLOB (Binary Large Object), BLOB(10G)
◼ Boolean data type
◼ Values of TRUE or FALSE or NULL
◼ DATE data type
◼ Ten positions
◼ Components are YEAR, MONTH, and DAY in the form YYYY-
MM-DD
◼ Multiple mapping functions available in RDBMSs to change
date formats

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Attribute Data Types and Domains in
SQL (cont’d.)
◼ Additional data types
◼ Timestamp data type
Includes the DATE and TIME fields
◼ Plus a minimum of six positions for decimal
fractions of seconds
◼ Optional WITH TIME ZONE qualifier
◼ DATE, TIME, Timestamp, INTERVAL data types
can be cast or converted to string formats for
comparison.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Attribute Data Types and Domains in
SQL (cont’d.)
◼ Domain
◼ Name used with the attribute specification
◼ Makes it easier to change the data type for a
domain that is used by numerous attributes
◼ Improves schema readability
◼ Example:
◼ CREATE DOMAIN SSN_TYPE AS CHAR(9);
◼ TYPE
◼ User Defined Types (UDTs) are supported for
object-oriented applications. (See Ch.12) Uses the
command: CREATE TYPE
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Specifying Constraints in SQL
Basic constraints:
◼ Relational Model has 3 basic constraint types that

are supported in SQL:


◼ Key constraint: A primary key value cannot be
duplicated
◼ Entity Integrity constraint: A primary key value
cannot be null
◼ Referential integrity constraints : The “foreign key
“ must have a value that is already present as a
primary key, or may be null.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Attribute Constraints
Other Restrictions on attribute domains:
◼ Default value of an attribute

◼ DEFAULT <value>
◼ NULL is not permitted for a particular attribute
(NOT NULL)
◼ CHECK clause
◼ Dnumber INT NOT NULL CHECK (Dnumber >
0 AND Dnumber < 21);
◼ Restrict to numbers 1-20

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Key and Referential
Integrity Constraints
◼ PRIMARY KEY clause
◼ Specifies one or more attributes that make up the
primary key of a relation
◼ Dnumber INT PRIMARY KEY;
◼ UNIQUE clause
◼ Specifies alternate (secondary) keys (called
CANDIDATE keys in the relational model).
◼ Dname VARCHAR(15) UNIQUE;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Key and Referential
Integrity Constraints (cont’d.)
◼ FOREIGN KEY clause
◼ Default operation: reject update on violation
◼ Attach referential triggered action clause
◼ Options include SET NULL, CASCADE, and SET
DEFAULT
◼ Action taken by the DBMS for SET NULL or SET
DEFAULT is the same for both ON DELETE and ON
UPDATE
◼ CASCADE option suitable for “relationship” relations

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Giving Names to Constraints
◼ Using the Keyword CONSTRAINT
◼ Name a constraint (unique name)
◼ Useful for later altering

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Default attribute values and referential
integrity triggered action specification (Fig.
6.2)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Constraints on Tuples
Using CHECK
◼ Additional Constraints on individual tuples within a
relation are also possible using CHECK
◼ CHECK clauses at the end of a CREATE TABLE
statement
◼ Apply to each tuple individually
◼ A manager’s starting date should be after a
department’s creation
◼ CHECK (Dept_create_date <= Mgr_start_date);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Basic Retrieval Queries in SQL
◼ SELECT statement
◼ One basic statement for retrieving information from
a database
◼ SQL allows a table to have two or more tuples
that are identical in all their attribute values
◼ Unlike relational model (relational model is strictly
set-theory based)
◼ Multiset or bag behavior

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The SELECT-FROM-WHERE
Structure of Basic SQL Queries
◼ Basic form of the SELECT statement:

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The SELECT-FROM-WHERE Structure
of Basic SQL Queries (cont’d.)

◼ Logical comparison operators


◼ =, <, <=, >, >=, and <>
◼ Projection attributes
◼ Attributes whose values are to be retrieved
◼ Selection condition
◼ Boolean condition that must be true for any
retrieved tuple. Selection conditions include join
conditions (see Ch.8) when multiple relations are
involved.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Basic Retrieval Queries

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Basic Retrieval Queries (Contd.)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Ambiguous Attribute Names
◼ Same name can be used for two (or more)
attributes in different relations
◼ As long as the attributes are in different relations
◼ Must qualify the attribute name with the relation
name to prevent ambiguity

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Aliasing and Renaming
◼ Aliases or tuple variables
◼ Declare alternative relation names E and S to refer
to the EMPLOYEE relation twice in a query:

Query 8. For each employee, retrieve the employee’s first and last name
and the first and last name of his or her immediate supervisor.
◼ SELECT [Link], [Link], [Link], [Link]
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn=[Link];
◼ Recommended practice to abbreviate names and
to prefix same or similar attribute from multiple
tables.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Aliasing,Renaming and Tuple
Variables (contd.)
◼ The attribute names can also be renamed
EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd,
Addr, Sex, Sal, Sssn, Dno)
◼ Note that the relation EMPLOYEE now has a
variable name E which corresponds to a tuple
variable
◼ The “AS” may be dropped in most SQL
implementations

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Unspecified WHERE Clause
and Use of the Asterisk
◼ Missing WHERE clause
◼ Indicates no condition on tuple selection
◼ Effect is a CROSS PRODUCT
◼ Result is all possible tuple combinations (or the
Algebra operation of Cartesian Product– see Ch.8)
result

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Unspecified WHERE Clause
and Use of the Asterisk (cont’d.)
◼ Specify an asterisk (*)
◼ Retrieve all the attribute values of the selected
tuples
◼ The * can be prefixed by the relation name; e.g.,
EMPLOYEE *

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Tables as Sets in SQL
◼ SQL does not automatically eliminate duplicate tuples in
query results
◼ For aggregate operations (See sec 7.1.7) duplicates must
be accounted for
◼ Use the keyword DISTINCT in the SELECT clause
◼ Only distinct tuples should remain in the result

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Tables as Sets in SQL (cont’d.)
◼ Set operations
◼ UNION, EXCEPT (difference), INTERSECT
◼ Corresponding multiset operations: UNION ALL,
EXCEPT ALL, INTERSECT ALL)
◼ Type compatibility is needed for these operations
to be valid

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Substring Pattern Matching and
Arithmetic Operators
◼ LIKE comparison operator
◼ Used for string pattern matching
◼ % replaces an arbitrary number of zero or more
characters
◼ underscore (_) replaces a single character
◼ Examples: WHERE Address LIKE ‘%Houston,TX%’;
◼ WHERE Ssn LIKE ‘_ _ 1_ _ 8901’;
◼ BETWEEN comparison operator
E.g., in Q14 :
WHERE(Salary BETWEEN 30000 AND 40000)
AND Dno = 5;
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Arithmetic Operations

◼ Standard arithmetic operators:


◼ Addition (+), subtraction (–), multiplication (*), and
division (/) may be included as a part of SELECT

◼ Query 13. Show the resulting salaries if every employee working on


the ‘ProductX’ project is given a 10 percent raise.

SELECT [Link], [Link], 1.1 * [Link] AS Increased_sal


FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE [Link]=[Link] AND [Link]=[Link] AND
[Link]=‘ProductX’;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Ordering of Query Results
◼ Use ORDER BY clause
◼ Keyword DESC to see result in a descending order
of values
◼ Keyword ASC to specify ascending order explicitly
◼ Typically placed at the end of the query

ORDER BY [Link] DESC, [Link] ASC,


[Link] ASC

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Basic SQL Retrieval Query Block

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


INSERT, DELETE, and UPDATE
Statements in SQL
◼ Three commands used to modify the database:
◼ INSERT, DELETE, and UPDATE

◼ INSERT inserts a tuple (row) in a relation (table)


◼ UPDATE may update a number of tuples (rows) in
a relation (table) that satisfy the condition
◼ DELETE may also update a number of tuples
(rows) in a relation (table) that satisfy the
condition

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


INSERT
◼ In its simplest form, it is used to add one or more
tuples to a relation
◼ Attribute values should be listed in the same
order as the attributes were specified in the
CREATE TABLE command
◼ Constraints on data types are observed
automatically
◼ Any integrity constraints as a part of the DDL
specification are enforced

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The INSERT Command
◼ Specify the relation name and a list of values for
the tuple. All values including nulls are supplied.

◼ The variation below inserts multiple tuples where


a new table is loaded values from the result of a
query.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


BULK LOADING OF TABLES
◼ Another variation of INSERT is used for bulk-loading
of several tuples into tables
◼ A new table TNEW can be created with the same
attributes as T and using LIKE and DATA in the
syntax, it can be loaded with entire data.
◼ EXAMPLE:

CREATE TABLE D5EMPS LIKE EMPLOYEE


(SELECT E.*
FROM EMPLOYEE AS E
WHERE [Link]=5)
WITH DATA;
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
DELETE
◼ Removes tuples from a relation
◼ Includes a WHERE-clause to select the tuples to be

deleted
◼ Referential integrity should be enforced

◼ Tuples are deleted from only one table at a time

(unless CASCADE is specified on a referential integrity


constraint)
◼ A missing WHERE-clause specifies that all tuples in

the relation are to be deleted; the table then becomes


an empty table
◼ The number of tuples deleted depends on the number

of tuples in the relation that satisfy the WHERE-clause


Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
The DELETE Command
◼ Removes tuples from a relation
◼ Includes a WHERE clause to select the tuples to be
deleted. The number of tuples deleted will vary.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


UPDATE
◼ Used to modify attribute values of one or more
selected tuples
◼ A WHERE-clause selects the tuples to be
modified
◼ An additional SET-clause specifies the attributes
to be modified and their new values
◼ Each command modifies tuples in the same
relation
◼ Referential integrity specified as part of DDL
specification is enforced
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
UPDATE (contd.)
◼ Example: Change the location and controlling
department number of project number 10 to
'Bellaire' and 5, respectively

U5: UPDATE PROJECT


SET PLOCATION = 'Bellaire',
DNUM = 5
WHERE PNUMBER=10

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


UPDATE (contd.)
◼ Example: Give all employees in the 'Research'
department a 10% raise in salary.
U6: UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research')

◼ In this request, the modified SALARY value depends on


the original SALARY value in each tuple

◼ The reference to the SALARY attribute on the right of =


refers to the old SALARY value before modification
◼ The reference to the SALARY attribute on the left of =
refers to the new SALARY value after modification
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Summary Part 1
◼ SQL
◼ A Comprehensive language for relational database
management
◼ Data definition, queries, updates, constraint
specification, and view definition
◼ Covered :
◼ Data definition commands for creating tables
◼ Commands for constraint specification
◼ Simple retrieval queries
◼ Database update commands
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Part 2

More SQL: Complex Queries, View


and Schema Modification

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Outline (Part 2)
◼ More Complex SQL Retrieval Queries
◼ Views (Virtual Tables) in SQL
◼ Schema Modification in SQL

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Comparisons Involving NULL
and Three-Valued Logic
◼ Meanings of NULL
◼ Unknown value
◼ Unavailable or withheld value
◼ Not applicable attribute
◼ Each individual NULL value considered to be
different from every other NULL value
◼ SQL uses a three-valued logic:
◼ TRUE, FALSE, and UNKNOWN (like Maybe)
◼ NULL = NULL comparison is avoided

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Comparisons Involving NULL
and Three-Valued Logic (cont’d.)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Three-Valued
Logic

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Comparisons Involving NULL
and Three-Valued Logic (cont’d.)
◼ SQL allows queries that check whether an
attribute value is NULL
◼ IS or IS NOT NULL

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Nested Queries, Tuples,
and Set/Multiset Comparisons
◼ Nested queries
◼ Complete select-from-where blocks within WHERE
clause of another query
◼ Outer query and nested subqueries
◼ Comparison operator IN
◼ Compares value v with a set (or multiset) of values
V
◼ Evaluates to TRUE if v is one of the elements in V

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Nested Queries (cont’d.)

Make a list of all project numbers for projects that involve


employee Smith either as worker or as a manager of the
department that controls the project:

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Nested Queries (cont’d.)
◼ Use tuples of values in comparisons
◼ Place them within parentheses

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Nested Queries (cont’d.)
◼ Use other comparison operators to compare a
single value v
◼ = ANY (or = SOME) operator [equivalent to IN]
◼ Returns TRUE if the value v is equal to some value in
the set
◼ Other operators that can be combined with ANY (or
SOME): >, >=, <, <=, and <>
◼ ALL: value must exceed all values from nested
query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


General Form of ALL, ANY, SOME

SELECT [column_name ]
FROM [table_name]
WHERE expression operator
{ALL | ANY | SOME} ( subquery )

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Nested Queries (cont’d.)
◼ Avoid potential errors and ambiguities
◼ Create tuple variables (aliases) for all tables
referenced in SQL query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Understanding a nested (correlated
query

For each E tuple,


Evaluate the nested query
which retrieves the Essn values of all D tuples
with the same sex and name as E tuple
If the Ssn value of E tuple is in the result,
then select the E tuple

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Correlated Nested Queries
◼ Queries that are nested using the = or IN
comparison operator can be collapsed into one
single block: E.g., Q16 can be written as:

◼ Q16A: SELECT [Link], [Link]


FROM EMPLOYEE AS E, DEPENDENT AS D
WHERE [Link]=[Link] AND [Link]=[Link] AND
[Link]=D.Dependent_name;

◼ Correlated nested query


◼ Evaluated once for each tuple in the outer query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Explicit Sets and Renaming of
Attributes in SQL
◼ Can use explicit set of values in WHERE clause
Q17: SELECT DISTINCT Essn
FROM WORKS_ON
WHERE Pno IN (1, 2, 3);

◼ Use qualifier AS followed by desired new name


◼ Rename any attribute that appears in the result of
a query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Joined Tables in the
FROM Clause of SQL
◼ Joined table
◼ Permits users to specify a table resulting from a
join operation in the FROM clause of a query
◼ The FROM clause in Q1A
◼ Contains a single joined table. JOIN may also be
called INNER JOIN

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Different Types of JOINed Tables in
SQL
◼ Specify different types of join
◼ NATURAL JOIN
◼ Various types of OUTER JOIN (LEFT, RIGHT,
FULL )
◼ NATURAL JOIN on two relations R and S
◼ No join condition specified
◼ Is equivalent to an implicit EQUIJOIN condition for
each pair of attributes with same name from R and
S

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


NATURAL JOIN
◼ Rename attributes of one relation so it can be joined with
another using NATURAL JOIN:

Q1B: SELECT Fname, Lname, Address


FROM (EMPLOYEE NATURAL JOIN
(DEPARTMENT AS DEPT (Dname, Dno, Mssn,
Msdate)))
WHERE Dname=‘Research’;

The above works with [Link] = [Link] as an


implicit join condition

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


INNER and OUTER Joins
◼ INNER JOIN (versus OUTER JOIN)
◼ Default type of join in a joined table

◼ Tuple is included in the result only if a matching tuple exists

in the other relation


◼ LEFT OUTER JOIN
◼ Every tuple in left table must appear in result

◼ If no matching tuple

◼ Padded with NULL values for attributes of right table

◼ RIGHT OUTER JOIN


◼ Every tuple in right table must appear in result

◼ If no matching tuple

◼ Padded with NULL values for attributes of left table

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Example: LEFT OUTER JOIN

SELECT [Link] AS Employee_Name


[Link] AS Supervisor_Name

FROM Employee AS E LEFT OUTER JOIN EMPLOYEE AS S


ON E.Super_ssn = [Link])

ALTERNATE SYNTAX:
SELECT [Link] , [Link]
FROM EMPLOYEE E, EMPLOYEE S
WHERE E.Super_ssn + = [Link]

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Multiway JOIN in the FROM clause
◼ FULL OUTER JOIN – combines result if LEFT
and RIGHT OUTER JOIN
◼ Can nest JOIN specifications for a multiway join:

Q2A: SELECT Pnumber, Dnum, Lname, Address, Bdate


FROM ((PROJECT JOIN DEPARTMENT ON
Dnum=Dnumber) JOIN EMPLOYEE ON
Mgr_ssn=Ssn)
WHERE Plocation=‘Stafford’;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Aggregate Functions in SQL
◼ Used to summarize information from multiple
tuples into a single-tuple summary
◼ Built-in aggregate functions
◼ COUNT, SUM, MAX, MIN, and AVG
◼ Grouping
◼ Create subgroups of tuples before summarizing
◼ To select entire groups, HAVING clause is used
◼ Aggregate functions can be used in the SELECT
clause or in a HAVING clause

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Renaming Results of Aggregation
◼ Following query returns a single row of computed values
from EMPLOYEE table:

Q19: SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG


(Salary)
FROM EMPLOYEE;
◼ The result can be presented with new names:

Q19A: SELECT SUM (Salary) AS Total_Sal, MAX (Salary) AS


Highest_Sal, MIN (Salary) AS Lowest_Sal, AVG
(Salary) AS Average_Sal
FROM EMPLOYEE;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Aggregate Functions in SQL (cont’d.)
◼ NULL values are discarded when aggregate
functions are applied to a particular column

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Aggregate Functions on Booleans
◼ SOME and ALL may be applied as functions on
Boolean Values.
◼ SOME returns true if at least one element in the
collection is TRUE (similar to OR)
◼ ALL returns true if all of the elements in the
collection are TRUE (similar to AND)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Grouping: The GROUP BY Clause
◼ Partition relation into subsets of tuples
◼ Based on grouping attribute(s)
◼ Apply function to each such group independently
◼ GROUP BY clause
◼ Specifies grouping attributes
◼ COUNT (*) counts the number of rows in the
group

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Examples of GROUP BY
◼ The grouping attribute must appear in the SELECT
clause:
Q24: SELECT Dno, COUNT (*), AVG (Salary)
FROM EMPLOYEE
GROUP BY Dno;
◼ If the grouping attribute has NULL as a possible value,
then a separate group is created for the null value (e.g.,
null Dno in the above query)
◼ GROUP BY may be applied to the result of a JOIN:
Q25: SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno
GROUP BY Pnumber, Pname;
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Grouping: The GROUP BY and
HAVING Clauses (cont’d.)
◼ HAVING clause
◼ Provides a condition to select or reject an entire
group:
◼ Query 26. For each project on which more than two employees work,
retrieve the project number, the project name, and the number of
employees who work on the project.

Q26: SELECT Pnumber, Pname, COUNT (*)


FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno
GROUP BY Pnumber, Pname
HAVING COUNT (*) > 2;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Combining the WHERE and the
HAVING Clause
◼ Consider the query: we want to count the total number of
employees whose salaries exceed $40,000 in each
department, but only for departments where more than
five employees work.

◼ INCORRECT QUERY:
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000
GROUP BY Dno
HAVING COUNT (*) > 5;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Combining the WHERE and the
HAVING Clause (continued)
Correct Specification of the Query:
◼ Note: the WHERE clause applies tuple by tuple

whereas HAVING applies to entire group of


tuples

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Views (Virtual Tables) in SQL
◼ Concept of a view in SQL
◼ Single table derived from other tables called the
defining tables
◼ Considered to be a virtual table that is not
necessarily populated

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specification of Views in SQL
◼ CREATE VIEW command
◼ Give table name, list of attribute names, and a query to
specify the contents of the view
◼ In V1, attributes retain the names from base tables. In
V2, attributes are assigned names

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specification of Views in SQL
(cont’d.)
◼ Once a View is defined, SQL queries can use the
View relation in the FROM clause
◼ View is always up-to-date
◼ Responsibility of the DBMS and not the user
◼ DROP VIEW command
◼ Dispose of a view

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The DROP Command
◼ DROP command
◼ Used to drop named schema elements, such as
tables, domains, or constraint
◼ Drop behavior options:
◼ CASCADE and RESTRICT
◼ Example:
◼ DROP SCHEMA COMPANY CASCADE;
◼ This removes the schema and all its elements
including tables, views, constraints, etc.
◼ RESTRICT: drops only nothing in it
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
The ALTER table command
◼ Alter table actions include:
◼ Adding or dropping a column (attribute)
◼ Changing a column definition
◼ Adding or dropping table constraints
◼ Example:
◼ ALTER TABLE [Link] ADD
COLUMN Job VARCHAR(12);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Adding and Dropping Constraints
◼ Change constraints specified on a table
◼ Add or drop a named constraint

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Dropping Columns, Default Values
◼ To drop a column
◼ Choose either CASCADE or RESTRICT
◼ CASCADE would drop the column from views etc.
RESTRICT is possible if no views refer to it.
ALTER TABLE [Link] DROP COLUMN
Address CASCADE;
◼ Default values can be dropped and altered :
ALTER TABLE [Link] ALTER COLUMN Mgr_ssn
DROP DEFAULT;
ALTER TABLE [Link] ALTER COLUMN Mgr_ssn SET
DEFAULT ‘333445555’;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Table 7.2 Summary of SQL
Syntax

continued on next slide

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Table 7.2 (continued)
Summary of SQL Syntax

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Summary Part 2
◼ Complex SQL:
◼ Nested queries, joined tables (in the FROM
clause), outer joins, aggregate functions, grouping
◼ CREATE VIEW statement and materialization
strategies
◼ Schema Modification for the DBAs using ALTER
TABLE , ADD and DROP COLUMN, ALTER
CONSTRAINT etc.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe

You might also like