Chapter 4
Basic SQL
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 4 Outline
SQL Data Definition and Data Types
Specifying Constraints in SQL
Basic Retrieval Queries in SQL
INSERT, DELETE, and UPDATE Statements in SQL
Additional Features of SQL
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Basic SQL
SQL language
Considered one of the major reasons for the commercial
success of relational databases
SQL
Structured Query Language
Statements for data definitions, queries, and updates (both DDL
and DML)
Core specification
Plus specialized extensions
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
SQL Data Definition and Data Types
Terminology:
Table, row, and column used for relational model terms
relation, tuple, and attribute
CREATE statement
Main SQL command for data definition
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Schema and Catalog Concepts in SQL
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 © 2011 Ramez Elmasri and Shamkant 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 environment
Installation of an SQL-compliant RDBMS on a computer system
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The CREATE TABLE Command in SQL
Specify a new relation
Provide name
Specify attributes and initial constraints
Can optionally specify schema:
CREATE TABLE COMPANY.EMPLOYEE ...
or
CREATE TABLE EMPLOYEE ...
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The CREATE TABLE Command in SQL
Base tables (base relations)
Relation and its tuples are actually created and stored as a file
by the DBMS
Virtual relations
Created through the CREATE VIEW statement
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The CREATE TABLE Command in SQL
Some foreign keys may cause errors
Specified either via:
• Circular references
• Or because they refer to a table that has not yet been created
Copyright © 2011 Ramez Elmasri and Shamkant 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 © 2011 Ramez Elmasri and Shamkant Navathe
Attribute Data Types and Domains in SQL
Bit-string data types
• Fixed length: BIT(n)
• Varying length: BIT VARYING(n)
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
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Attribute Data Types and Domains in SQL
Additional data types
Timestamp data type (TIMESTAMP)
• Includes the DATE and TIME fields
• Plus a minimum of six positions for decimal fractions of seconds
• Optional WITH TIME ZONE qualifier
INTERVAL data type
• Specifies a relative value that can be used to increment or decrement an
absolute value of a date, time, or timestamp
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Attribute Data Types and Domains in SQL
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);
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Specifying Constraints in SQL
Basic constraints:
Key and referential integrity constraints
Restrictions on attribute domains and NULLs
Constraints on individual tuples within a relation
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Specifying Attribute Constraints and Attribute
Defaults
NOT NULL
NULL is not permitted for a particular attribute
Default value
DEFAULT <value>
CHECK clause
Dnumber INT NOT NULL CHECK (Dnumber > 0 AND
Dnumber < 21);
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Copyright © 2011 Ramez Elmasri and Shamkant 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
Dname VARCHAR(15) UNIQUE;
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Specifying Key and Referential Integrity
Constraints
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 © 2011 Ramez Elmasri and Shamkant 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
Multiset or bag behavior
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The SELECT-FROM-WHERE Structure of Basic
SQL Queries
Basic form of the SELECT statement:
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The SELECT-FROM-WHERE Structure of Basic
SQL Queries
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
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Ambiguous Attribute Names
Same name can be used for two (or more) attributes
As long as the attributes are in different relations
Must qualify the attribute name with the relation name to
prevent ambiguity
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Ambiguous Attribute Names
Fully qualified attribute names can be used for clarity even if there is no
ambiguity in attribute names.
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Ambiguous Attribute Names
The ambiguity of attribute names also arises in the case of queries that
refer to the same relation twice
Query: For each employee, retrieve the employee’s first and last name
and the first and last name of his or her immediate supervisor
Alternative relation names E and S, called aliases or tuple variables, for
the EMPLOYEE relation
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Aliasing, Renaming, and Tuple Variables
Aliases or tuple variables
Declare alternative relation names E and S
EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd, Addr, Sex,
Sal, Sssn, Dno)
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Unspecified WHERE Clause
and Use of the Asterisk
Missing WHERE clause
Indicates no condition on tuple selection
CROSS PRODUCT
All possible tuple combinations
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Unspecified WHERE Clause
and Use of the Asterisk (cont’d.)
Specify an asterisk (*)
Retrieve all the attribute values of the selected tuples
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Tables as Sets in SQL
SQL does not automatically eliminate duplicate tuples in
query results
Use the keyword DISTINCT in the SELECT clause
Only distinct tuples should remain in the result
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Tables as Sets in SQL
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Tables as Sets in SQL (cont’d.)
Set operations
UNION, EXCEPT (difference), INTERSECT
Corresponding multiset operations: UNION ALL, EXCEPT ALL,
INTERSECT ALL)
Copyright © 2011 Ramez Elmasri and Shamkant 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
Standard arithmetic operators:
Addition (+), subtraction (–), multiplication (*), and division (/)
BETWEEN comparison operator
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Substring Pattern Matching and Arithmetic
Operators
Retrieve all employees whose address is in Houston, Texas
Find all employees who were born during the 1970s
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Substring Pattern Matching and Arithmetic
Operators
If an underscore or % is needed as a literal character in the string, the character
should be preceded by an escape character, which is specified after the string
using the keyword ESCAPE.
For example, ‘AB\_CD\%EF’ ESCAPE ‘\’ represents the literal string
‘AB_CD%EF’ because \ is specified as the escape character.
Another feature allows the use of arithmetic in queries. The standard arithmetic
operators for addition (+), subtraction (−), multiplication (*), and division (/) can be
applied to numeric values or attributes with numeric domains.
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Substring Pattern Matching and Arithmetic
Operators
Query: Show the resulting salaries if every employee working on the
‘ProductX’ project is given a 10% raise.
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Substring Pattern Matching and Arithmetic
Operators
Another comparison operator, which can be used for convenience, is BETWEEN.
Query: Retrieve all employees in department 5 whose salary is between
$30,000 and $40,000.
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Ordering of Query Results
Use ORDER BY clause
SQL allows the user to order the tuples in the result of a query by the
values of one or more of the attributes that appear in the query result, by
using the ORDER BY clause
Keyword DESC to see result in a descending order of values
Keyword ASC to specify ascending order explicitly
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
Ordering of Query Results
Query: Retrieve a list of employees and the projects they are working on,
ordered by department and, within each department, ordered
alphabetically by last name, then first name
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
INSERT, DELETE, and UPDATE Statements in SQL
Three commands used to modify the database:
INSERT, DELETE, and UPDATE
The INSERT Command
• INSERT is used to add a single tuple (row) to a relation (table).
• We must specify the relation name and a list of values for the tuple.
• The values should be listed in the same order in which the corresponding
attributes were specified in the CREATE TABLE command.
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The INSERT Command
Specify the relation name and a list of values for the tuple
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The INSERT Command
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The INSERT Command
A variation of the INSERT command inserts multiple tuples into a relation in
conjunction with creating the relation and loading it with the result of a query.
For example, to create a temporary table that has the employee last name,
project name, and hours per week for each employee working on a project, we
can write the statements in U3A and U3B:
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The DELETE Command
Removes tuples from a relation
Includes a WHERE clause to select the tuples to be deleted
Copyright © 2011 Ramez Elmasri and Shamkant Navathe
The UPDATE Command
Modify attribute values of one or more selected tuples
Additional SET clause in the UPDATE command
Specifies attributes to be modified and new values
Copyright © 2011 Ramez Elmasri and Shamkant Navathe