Vous êtes sur la page 1sur 39

BASIC SQL Osameh Al-Kofahi

These slides are a modified version of the ones prepared by the authors
INTRODUCTION
SQL stands for Structured Query Language
 SEQUEL

The SQL standard is maintained by the International Organization for Standards (ISO)
 SQL:2019 is the most recent
 No SQL implementation fully adheres to the standard
 Most syntax is compatible between vendors
 Data types may mismatch or not be implemented at all

We will focus on two implementations:


 MS SQL Server (in class)
 Oracle (in lab)
DDL AND DML IN SQL
SQL is used for Data Definition and Data Manipulation
Action DDL Command (Schema) DML Command (State)
Add CREATE INSERT
Remove DROP DELETE
Modify ALTER UPDATE

What is created with CREATE can be modified with ALTER and removed with DROP
What is added with INSERT can be modified with UPDATE and removed with DELETE
Data retrievals (also part of DML) are done using SELECT, which will be covered later
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
CREATE SCHEMA statement:
CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;
Catalog: Named collection of schemas in an SQL environment
USER DEFINED DATA TYPES
The CREATE command is used to create any schema construct
For example, creating Domains
 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);

 CREATE Type SSN_TYPE From CHAR(9); (MS SQL Server)


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:


1) CREATE TABLE COMPANY.EMPLOYEE ... or
2) CREATE TABLE EMPLOYEE ...
What’s the difference?
The “CREATE TABLE” command creates Base relations not Virtual relations
What gets created with CREATE, can be removed with DROP
COMPANY RELATIONAL DATABASE SCHEMA
SQL CREATE TABLE DATA DEFINITION STATEMENTS
SQL CREATE TABLE
DATA DEFINITION
STATEMENTS
FOREIGN KEY PROBLEMS
Some foreign keys may cause errors
Specified either via:
 Circular references (triggered actions may not be allowed, e.g., in MS SQL Server)
 Or because they refer to a table that has not yet been created

They may also be troublesome if you want to load the DB for the first time
 They enforce a certain order on data entry
 Insert referenced tuples first
SPECIFYING CONSTRAINTS IN SQL
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.

In addition, the following constraints can be defined:


Default value of an attribute
 DEFAULT <value>

NOT NULL constraints (field cannot be left empty)


CHECK clause
 Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
SPECIFYING CONSTRAINTS IN SQL
Constraints can be added in multiple places --Example 1:
in a table definition: CREATE TABLE TEST ( A INT,
 Directly on an attribute after specifying its data type, B INT CHECK (B > 0),
e.g., the CHECK constraint on attribute B in the C CHAR(5),
example to the right PRIMARY KEY (A));
 In a separate clause inside the create table
statement, e.g., the primary key constraint on
attribute A in the same example.
 There are some exceptions -- EXAMPLE 2:
CREATE TABLE TEST ( A INT,
They can also be added to a table after it B INT CHECK (B > 0),
has been created using the ALTER statement C CHAR(5));
 See Example 2 ALTER TABLE TEST ALTER COLUMN A INT NOT NULL;
ALTER TABLE TEST ADD PRIMARY KEY(A);
SPECIFYING CONSTRAINTS IN SQL
A good practice is to give constraints names.
 This is useful for altering data definitions later

The CONSTRAINT keyword is used to do this


 On attribute directly
 Afterwards in table definition
 In ALTER statements -- EXAMPLE 3:
CREATE TABLE TEST ( A INT,
In Example 3: B INT CONSTRAINT CHK_B CHECK (B > 0),
 Note the use of CONSTRAINT C CHAR(5),
CONSTRAINT TEST_PK PRIMARY KEY(A));

ALTER TABLE TEST ADD CONSTRAINT TEST_SK UNIQUE(C);


ALTER TABLE TEST NOCHECK CONSTRAINT CHK_B;
ALTER TABLE TEST DROP CONSTRAINT TEST_PK;
SPECIFYING PRIMARY KEY CONSTRAINTS
-- PK EXAMPLES:
CREATE TABLE TEST (A INT PRIMARY KEY);
-- OR
CREATE TABLE TEST (A INT CONSTRAINT TEST_PK PRIMARY KEY);
-- OR
CREATE TABLE TEST (A INT, CONSTRAINT TEST_PK PRIMARY KEY (A));
-- OR
CREATE TABLE TEST (A INT NOT NULL)
ALTER TABLE TEST ADD CONSTRAINT TEST_PK PRIMARY KEY(A));
SPECIFYING FOREIGN KEY CONSTRAINTS
Referenced relation must exist. Assume: CREATE TABLE TEST (A INT, CONSTRAINT TEST_PK PRIMARY KEY (A));
-- FK EXAMPLES:
CREATE TABLE REFERENCING (FK INT REFERENCES TEST);
-- OR
CREATE TABLE REFERENCING (FK INT CONSTRAINT REF_FK REFERENCES TEST);
-- OR
CREATE TABLE REFERENCING (FK INT, CONSTRAINT REF_FK FOREIGN KEY (FK) REFERENCES TEST);
-- OR
CREATE TABLE REFERENCING (FK INT, CONSTRAINT REF_FK FOREIGN KEY (FK) REFERENCES TEST(A));
SPECIFYING FOREIGN KEY CONSTRAINTS
Foreign key triggered actions on update or delete:
 CASCADE the action
 SET NULL or SET DEFAULT
 If not specified, the default is to reject the violating operation
 If no default value for the FK attribute is specified, then SET DEFAULT cannot be used

CREATE TABLE REFERENCING (FK INT,


CONSTRAINT REF_FK FOREIGN KEY (FK) REFERENCES TEST(A)
ON DELETE SET NULL ON UPDATE CASCADE);

When will these actions be triggered?


OTHER CONSTRAINTS

Secondary keys can be defined using the UNIQUE constraint

Check constraints can be used to check the values of an attribute in a certain relation, or
to check the values in individual tuples
CHECK clauses at the end of a CREATE TABLE statement
 Apply to each tuple individually
 CHECK (Dept_create_date <= Mgr_start_date);
 This constraint verifies that the manager start date is after the department creation date
IN-CLASS EXERCISE:
Consider the following tables that describe two mini-world entities
Employee(SSN, Name, phone)
Department(Dno, Dname)
Modify table definitions given the following information, then write the needed SQL
statements to create them:
 Many employees may work in the same department, while an employee works in one department only
 How will table definitions change if an employee can have more than phone number
INSERTING DATA INTO TABLES
There are two ways to use the INSERT command: CREATE TABLE CAR(VIN INT
CONSTRAINT CAR_PK PRIMARY KEY,
The shorthand version: MAKE VARCHAR(20) NOT NULL,
MODEL VARCHAR(20),
INSERT INTO CAR VALUES(123,'HONDA', 'ACCORD', 5) NO_OF_SEATS INT
-- THE FOLLOWING WILL CAUSE AN ERROR CONSTRAINT SEATS_DEF DEFAULT 5);
INSERT INTO CAR VALUES(321,'TOYOTA', 'CAMREY')
The full (long) version:
INSERT INTO CAR(VIN, MAKE, MODEL) VALUES (321,'TOYOTA', 'CAMREY')
INSERT INTO CAR(MAKE, VIN) VALUES ('NISSAN', 111)
INSERTING DATA INTO TABLES
In the full version, you can choose which
attributes to assign values to in any order
you like.
The attributes that are not assigned values
will have either NULLs or their default values
Remember that the following insertions were
made:
INSERT INTO CAR VALUES(123,'HONDA', 'ACCORD', 5)
INSERT INTO CAR(VIN, MAKE, MODEL) VALUES (321,'TOYOTA', 'CAMREY')
INSERT INTO CAR(MAKE, VIN) VALUES ('NISSAN', 111)
DELETING FROM TABLES
The DELETE command can be used to delete rows from tables.
Usually used with a WHERE clause to choose which rows to delete
Otherwise, all table content will be deleted. The table will not be removed.
Examples:
DELETE CAR WHERE VIN = 111

DELETE CAR WHERE MAKE = 'HONDA’

DELETE CAR
UPDATING DATA
The UPDATE command is used to modify the values for one or more attributes in one
or more rows
Like DELETE, UPDATE is usually used with a WHERE clause to specify which rows to
update. Otherwise, the values in the whole column will be updated.

UPDATE CAR SET NO_OF_SEATS=6, MAKE='MAZDA’

UPDATE CAR SET NO_OF_SEATS=6, MAKE='MAZDA', MODEL='M6' WHERE VIN = 111

UPDATE CAR SET NO_OF_SEATS=7 WHERE VIN = 123


THE SELECT STATEMENT
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
 Tuple-id may be used as a key
THE SELECT STATEMENT
Basic form of the SELECT statement:
THE SELECT STATEMENT
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.
BASIC RETRIEVAL QUERIES
From the query you should be able
to identify:
 The needed attributes
 The conditions that the values must meet

You need to determine the table(s)


In this example, only select
conditions are used
How is the query evaluated?
BASIC RETRIEVAL QUERIES
Are all the attributes you need in
the same table?
Why are we using the second
table?
Note the two types of conditions:
Select condition:
 Dname = ‘Research’
Join condition:
 Dnumber = Dno

How is the query evaluated?


BASIC RETRIEVAL QUERIES
BASIC RETRIEVAL QUERIES
Attributes are known
Conditions are known
Determine tables
Formulate conditions
Select conditions filter data
Join conditions relate data
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 result
AMBIGUOUS ATTRIBUTE NAMES
Query: For every department
located in Stafford, retrieve the
department name and the
manager ssn SELECT DNAME, MGR_SSN
FROM DEPARTMENT, DEPT_LOCATIONS
Two tables may have attributes WHERE DNUMBER = DNUMBER AND
with similar names DLOCATION='STAFFORD'
Attribute name should be fully
qualified SELECT DNAME, MGR_SSN
FROM DEPARTMENT, DEPT_LOCATIONS
WHERE DEPARTMENT.DNUMBER = DEPT_LOCATIONS.DNUMBER AND
DLOCATION='STAFFORD'
ALIASING, AND RENAMING
Aliases or tuple variables
Aliases and tuple variables are the same thing. Both can be defined by following a
table name with an “AS” then defining the alias or the tuple variable.
How do they differ? Depends on your understanding

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 E.FNAME, E.LNAME, S.FNAME, S.LNAME


FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.SUPER_SSN = S.SSN
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
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
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
SELECT FNAME
FROM EMPLOYEE
WHERE FNAME LIKE '_o%'

BETWEEN comparison operator


SELECT FNAME, SALARY
FROM EMPLOYEE
WHERE SALARY BETWEEN 30000 AND 40000
CHECKING FIELD FORMAT WITH LIKE
LIKE and BETWEEN can be used in constraints also

CREATE TABLE TEST(NAME VARCHAR(30), PHONE CHAR(14),


AGE INT CONSTRAINT AGE_LIMIT CHECK (AGE BETWEEN 18 AND 60),
CONSTRAINT PHONE_FORMAT CHECK (PHONE LIKE '(___) ___-____’))

-- WILL NOT WORK, IT VIOLATES BOTH CONSTRAINTS


INSERT INTO TEST VALUES ('ALI', '1234567890', 10)

-- OK
INSERT INTO TEST VALUES ('ALI', '(123) 456-7890', 20)
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 FNAME, SALARY * 1.1 AS INCREASED_SAL


FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN = ESSN AND PNO = PNUMBER AND PNAME='PRODUCTX'

Will this update the salaries of employees in the base relation?


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

SELECT FNAME, LNAME, SALARY


FROM EMPLOYEE
ORDER BY SALARY ASC, FNAME DESC

In this example, tuples will be in descending order of first name only if they have
equal salaries. That is the second ordering criterion will not be used unless a tie in the
first occurred.

Vous aimerez peut-être aussi