0% found this document useful (0 votes)
6 views47 pages

Lecture 4

The document provides an overview of SQL, including its definition, data types, and schema creation. It covers essential SQL commands such as SELECT, INSERT, DELETE, and UPDATE, along with constraints and complex queries involving JOINs and aggregate functions. The lecture emphasizes the importance of SQL in database management and its role in manipulating and retrieving data efficiently.

Uploaded by

trol.man890
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)
6 views47 pages

Lecture 4

The document provides an overview of SQL, including its definition, data types, and schema creation. It covers essential SQL commands such as SELECT, INSERT, DELETE, and UPDATE, along with constraints and complex queries involving JOINs and aggregate functions. The lecture emphasizes the importance of SQL in database management and its role in manipulating and retrieving data efficiently.

Uploaded by

trol.man890
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
You are on page 1/ 47

Lecture 5.

Basic and Advanced


SQL
(Chapter 6 and 7)
[email protected]
Connection to previous lectures
ER/EER Relational Model
Lecture 3 ER and EER Lecture 4 Relation Lecture 5
Conceptual models Model SQL

• High –level data • Medium-level • Low-level


abstraction using data abstraction abstraction
Entity Relation using Relational • SQL standard
(ER) and Models language to
Enhanced Entity • From ER to create and
Relation (EER) Relational Model manipulate the
models database

2(44)
Outline
• SQL Data Definition and Data Types
• Specifying Constraints in SQL
• Basic Retrieval Queries in SQL
• INSERT, DELETE, and UPDATE Statements in SQL
• Break 10 min
• More Complex SQL Retrieval Queries:
• JOIN, Aggregation, GROUP BY, nested queries

3(44)
About SQL
• SQL (Structured Query Language, come from the word “SEQUEL”
(Structured English Query Language)) is a standard language for storing,
manipulating, and retrieving data in database.
• SQL was developed in the 1970s by IBM Computer Scientists
• Considered one of the major reasons for the commercial success of
relational databases
• SQL uses the terms table, row, and column for the formal relational terms
relation, tuple, and attribute respectively.
• SQL allows a table to have two or more tuples that are identical in all their
attribute values
• Every statement in SQL finished by semicolon “;”
• SQL Syntax: https://www.tutorialspoint.com/sql/sql-syntax.htm

4(44)
SQL Schema
• SQL Schema is a database description which :
• Identified by a schema name
• Includes an authorization identifier to indicate the user or account who owns
schema
• Includes description of each elements of the schema (tables, types,
constrains, views, domains, etc.)
• A Schema is created via the CREATE SCHEMA statement which can
include all the schema elements definitions.

5(44)
Defining COMPANY Schema (1)

Some foreign keys may cause errors


Specified either via:
Circular references
Or because they refer to a
table that has not yet been
created

6(44)
Defining COMPANY Schema (1)

7(44)
Attribute Data Types 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)
• 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
• Multiple mapping functions available in RDBMSs to change date formats

8(44)
Additional Data Types in SQL
• 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
• INTERVAL data type
• Specifies a relative value that can be used to increment or decrement an absolute value
of a date, time, or timestamp
• DATE, TIME, Timestamp, INTERVAL data types can be cast or converted to
string formats for comparison
• Different DBMS have added more data types to SQL which are not presented
in this lecture.

9(44)
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);

10(44)
Specifying Constraints 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.
• 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);

11(44)
Specifying Key and Referential Integrity
Constraints
PRIMARY KEY clause
Specifies one or more attributes that make up the primary key of a relation
Example: Dnumber INT PRIMARY KEY;
UNIQUE clause
Specifies alternate (secondary) keys (called CANDIDATE keys in the relational model).
Example: Dname VARCHAR(15) UNIQUE;
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

12(44)
Example

Constraints can be specified when a


table is created with the CREATE
TABLE statement or you can use
the ALTER TABLE statement to
create constraints even after the
table is created.

13(44)
Basic Commands in SQL
• CREATE
Used for creating/removing new database, table, column
• DROP
• SELECT
• INSERT
Used for manipulating with data in database
• DELETE
• UPDATE

14(44)
SELECT Command
• This command helps in retrieving a single or multiple rows from one
or multiple tables of the database. We can also use this command
with the WHERE clause.
• Basic form of the SELECT statement:

15(44)
WHERE clause
• Selection condition:
• OR, AND: Boolean condition that must be true for any retrieved tuple. Selection conditions include join
conditions when multiple relations are involved.
• Logical comparison operators
=, <, <=, >, >=, and <>
• Projection attributes
• Attributes whose values are to be retrieved
• 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
Example: WHERE (Salary BETWEEN 30000 AND 40000) AND Dno = 5;

16(44)
Example Basic SELECT Queries (1)

17(44)
Example Basic SELECT Queries (2)

18(44)
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

19(44)
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 Example. For each employee, retrieve the employee’s first and last name and the first and
last name of his or her immediate supervisor.
SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn=S.Ssn;
• Recommended practice to abbreviate names and to prefix same or similar
attribute from multiple tables.

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

21(44)
DISTINCT clause
• 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

22(44)
Arithmetic Operations in SELECT
• Standard arithmetic operators:
• Addition (+), subtraction (–), multiplication (*), and division (/) may be
included as a part of SELECT
Query Example: Show the resulting salaries if every employee working on the ‘ProductX’
project is given a 10 percent raise.

SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal


FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE E.Ssn=W.Essn AND W.Pno=P.Pnumber AND P.Pname=‘ProductX’;
• Also standard statistical operations (such as max, min, count, sum,
mean, etc.)
23(44)
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 D.Dname DESC, E.Lname ASC, E.Fname ASC

24(44)
Break 10 min

25(44)
Basic SQL Retrieval Query Block

where, [] brackets mean not mandatory/optional


Every block is finished by semicolon ‘;’

26(44)
INSERT Command
• INSERT typically inserts a tuple (row) in a relation (table)
• 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
• Specify the relation name and a list of values for the tuple. All values
including nulls are supplied.
• Example:

27(44)
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

28(44)
Example 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.

29(44)
UPDATE (1)
• 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
• Example: Change the location and controlling department number of
project number 10 to 'Bellaire' and 5, respectively
UPDATE PROJECT
SET PLOCATION = 'Bellaire', DNUM = 5
WHERE PNUMBER=10

30(44)
UPDATE (2)
• Example: Give all employees in the 'Research' department a 10% raise in salary.
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

31(44)
More Complex SQL Retrieval Queries

• Additional features allow users to specify more complex retrievals


from database:
• nested queries,
• joined tables and JOIN operations
• aggregate functions, and grouping

32(44)
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

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

34(44)
Comparisons Involving NULL
and Three-Valued Logic
• SQL allows queries that check whether an attribute value is NULL
• IS or IS NOT NULL
Example:

35(44)
Nested Queries Example 1 (using IN)

36(44)
Nested Queries Example 2 (using Comparison
Operator)
• Use other comparison operators to compare a single value v
• = ANY (or = SOME) operator
• Returns TRUE if the value v is equal to some value in the set V and is hence equivalent
to IN
• Other operators that can be combined with ANY (or SOME): >, >=, <, <=, and
<>
• ALL: value must exceed all values from nested query

37(44)
Nested Queries
• Avoid potential errors and ambiguities
• Create tuple variables (aliases) for all tables referenced in SQL query

38(44)
SQL Joins

39(44)
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
• Following query returns a single row of computed values from EMPLOYEE
table:
SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG(Salary)
FROM EMPLOYEE;

• The result can be presented with new names:


SELECT SUM (Salary) AS Total_Sal, MAX (Salary) AS Highest_Sal, MIN (Salary) AS Lowest_Sal, AVG (Salary) AS
Average_Sal
FROM EMPLOYEE;

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

41(44)
GROUP BY clause
• The grouping attribute must appear in the SELECT clause:
Example: 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:
Example: SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno
GROUP BY Pnumber, Pname;

42(44)
Summary of SQL Syntax

43(44)
Summary of SQL Syntax

44(44)
More Examples from the Book

45(44)
46(44)
47(44)

You might also like