ITCS 3160 DATA BASE DESIGN AND IMPLEMENTATION JING YANG 2010 FALL Class 3: Basic SQL TA Information 2 Sandhya Charugulla charugulla.sandhya.rani@gmail.com Office hours: Thursday and Tuesday 2-3 pm Woodward Hall 335 1
Outline 3 Oracle installation 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 Install Oracle (1) 4 Go to the following website: http://www.oracle.com/technetwork/database/expr ess-edition/downloads/index.html 2
Install Oracle (2) 5 Install Oracle (3) 6 If you do not have an Oracle.com account, create one through sign up now before you sign in. 3
Install Oracle (4) 7 Save file and run OracleXE.exe Install Oracle (5) 8 Specify a password for the SYS and SYSTEM accounts. You need this password in the future so please keep a record of it. 4
Using SQL Command Line 9 Use Online Help 10 Programs\Oracle Database 10g Express Edition\Get Help\ Read Online Help 5
Basic SQL 11 SQL language Considered d 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 SQL Data Definition and Data Types 12 Terminology: Table, row, and column used for relational l model terms relation, tuple, and attribute CREATE statement Main SQL command for data definition 6
Schema and Catalog Concepts in SQL 13 SQL schema Identified d 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 14 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 Note: examples in red are not tested in Oracle by the instructor. 7
The CREATE TABLE Command in SQL 15 Specify a new relation Provide name Specify attributes and initial constraints Can optionally specify schema: CREATE TABLE COMPANY.EMPLOYEE... or CREATE TABLE EMPLOYEE... 16 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 Created through the CREATE VIEW statement 8
17 RED 18 RED 9
19 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 Solution: add foreign keys later 20 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) 10
Data Types in Oracle 21 Numeric Data Types in Oracle 22 NUMBER Store integers and real numbers in a fixed-point i or floating-point format. Can be used for nearly all cases where you need to store numeric data 11
Numeric Data Types in Oracle (cont d) 23 NUMBER(p) for an integer Equivalent to NUMBER(p,0). NUMBER(p, s) for a fixed-point number NUMBER for a floating-point number The absence of precision and scale designators specifies the maximum range and precision for an Oracle number. Numeric Data Types in Oracle (cont d) 24 BINARY_FLOAT and BINARY_DOUBLE exclusively for floating-point numbers. Support all of the basic functionality provided by NUMBER. While NUMBER uses decimal precision, BINARY_FLOAT and BINARY_DOUBLE use binary precision. This enables faster arithmetic calculations and usually reduces storage requirements. 12
Character Data Types in Oracle 25 Types supported: VARCHAR2 - stores variable-length character literals. (specify a string length between 1 and 4000 bytes. Example: VARCHAR2(25). CHAR - stores fixed-length character literals (specify a string length between 1 and 2000 bytes) NCHAR - store fixed-length Unicode character literals. NVARCHAR2 - stores variable-length Unicode character literals. 26 Character Data Types in Oracle (cont d) Which one to select: Space usage - To store data more efficiently, use VARCHAR2. CHAR adds blanks to maintain a fixed column length for all column values, whereas the VARCHAR2 datatype does not add extra blanks. Comparison semantics Use CHAR when trailing blanks are not important in string comparisons. Use VARCHAR2 when trailing blanks are important in string comparisons. Future compatibility - CHAR and VARCHAR2 are fully supported. 13
27 Attribute Data Types and Domains in SQL (cont d.) 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 (Note: in different RDBMSs, the format of DATE data types may be different) 28 Attribute Data Types and Domains in SQL (cont d.) 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 14
Date and Time in Oracle 29 Default date format is DD-MON-RR. The RR date- time format element enables you store 20th century dates in the 21st century by specifying only the last two digits of the year. Time is stored in a 24-hour format as HH24:MI:SS. Date and Time in Oracle (cont d) 30 Oracle provide SQL functions to calculate and convert date-time data add months to, extract a specific field from, truncate, and round a date value calculate the number of months between two dates convert a value from one datatype to another datatype. convert a character value to a numeric or date datatype convert a numeric or date value to a character datatype. When converting a value, you can also specify a format model. A format model is a character literal that specifies the format of data. A format model does not change the internal representation of the value in the database. Example: the following adds 3 months to the hire_date of an employee SELECT employee_id, hire_date, ADD_MONTHS(hire_date, 3) FROM employees; 15
31 Attribute Data Types and Domains in SQL (cont d.) Domain Name used with the attribute specification i 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); Specifying Constraints in SQL 32 Basic constraints: Key and referential integrity i constraints Restrictions on attribute domains and NULLs Constraints on individual tuples within a relation 16
Not NULL 33 NOT NULL NULL is not permitted for a particular attribute CREATE TABLE student (Id NUMBER, Name VARCHAR2(30) NOT NULL, PRIMARY KEY (id)); Valid or Invalid? INSERT INTO student VALUES (2, NULL); Default 34 DEFAULT <value> DROP TABLE student; CREATE TABLE student (Id NUMBER, City CHAR(30) DEFAULT 'Charlotte', Age Number, PRIMARY KEY (id)); INSERT INTO student VALUES (1, 'New York', 18); INSERT INTO student(id, Age) VALUES (2, 19); ID CITY AGE ---------- ------------------------------ ---------- 1 New York 18 2 Charlotte 19 17
Check 35 CHECK clauses at the end of a CREATE TABLE statement Apply to each tuple individually Boolean expression evaluated using column value to be inserted or updated Enforce integrity rules based on logical expressions, such as comparisons. Not use if other types of integrity constraints can provide the necessary checking. Examples of check constraints include the following: A check constraint on employee salaries so that no salary value is less than 0. A check constraint on department locations so that only the locations Boston, New York, and Dallas are allowed. A check constraint on the salary and commissions columns to prevent the commission from being larger than the salary. Check in Oracle (cont d) 36 CREATE TABLE EMPOLYEE (Id NUMBER, Age NUMBER CHECK (age > 15 AND age < 80), PRIMARY KEY (Id)); Valid or not? INSERT INTO EMPOLYEE VALUES (1, 23); INSERT INTO EMPOLYEE VALUES (2, 12); 18
37 Specifying Key and Referential Integrity Constraints PRIMARY KEY clause Specifies one or more attributes that make up the primary key of a relation If primary key has only one attribute Id NUMBER PRIMARY KEY; If primary key has more than two attributes CREATE TABLE course (Course_id NUMBER, Section_id NUMBER, PRIMARY KEY (Course_id, Section_id)); id)) UNIQUE clause Specifies alternate (secondary) keys Dname VARCHAR2(15) UNIQUE; 38 Specifying Key and Referential Integrity Constraints (cont d.) FOREIGN KEY clause Default operation: reject update on violation i Attach referential triggered action clause Options include SET NULL, CASCADE, and SET DEFAULT ON DELETE and ON UPDATE Action for SET NULL or SET DEFAULT is the same for both ON DELETE and ON UPDATE CASCADE different for ON DELETE and ON UPDATE 19
39 Giving Names to Constraints 40 Keyword CONSTRAINT Name a constraint Useful for later altering See figure 4.2 for examples 20