y y y y y SQL was first implemented in IBM's System R in the late 1970's. SQL is the de-facto standard query language for creating and manipulating data in relational databases. Some minor syntax differences, but the majority of SQL is standard across MS Access, Oracle, Sybase, Informix, etc. SQL is either specified by a command-line tool or is embedded into a general purpose programming language such as COBOL, "C", Pascal, Java, C++, etc. SQL is a standardized language monitored by the American National Standards Institute (ANSI) as well as by National Institute of Standards (NIST). o ANSI 1990 - SQL 1 standard o ANSI 1992 - SQL 2 Standard (sometimes called SQL-92) o ANSI 1999 - SQL 1999 - adds regular expressions, triggers, some Object oriented concepts o ANSI 2003 - SQL 2003 - XML features, auto generated data (e.g., auto number) o ANSI 2006 - SQL 2006 - Further XML Integration using XQuery, XPath, etc. o ANSI 2008 - SQL 2008 - Additional commands usch as Truncate

SQL HAS TWO MAJOR PARTS: 1. Data Definition Language (DDL) Used to create (define) data structures such as tables, indexes, clusters 2. Data Manipulation Language (DML) is used to store, retrieve and update data from tables. 3. Data Control Languages(DCL) is used to control the access of data and rights of the users SQL DATA TYPES Each implementation of SQL uses slightly different names for the data types. 1. Numeric Data Types y Integers: INTEGER, INT or SMALLINT y Real Numbers: FLOAT, REAL, DOUBLE, PRECISION y Formatted Numbers: DECIMAL(i,j), NUMERIC(i,j) 2. Character Strings y TWO MAIN TYPES: FIXED LENGTH AND VARIABLE LENGTH. 1. Fixed length of n characters: CHAR(n) or CHARACTER(n) 2. Variable length up to size n: VARCHAR(n)

Date and Time Note: Implementations vary widely for these data types. DATE: Has 10 positions in the format: YYYY-MM-DD TIME: Has 8 positions in the format: HH:MM:SS 1. TIME (i): Defines the TIME data type with an additional i positions for fractions of a second. For example: HH:MM:SS:dd and Offset from UTZ. +/- HH:MM 2. TIMESTAMP 3. INTERVAL: Used to specify some span of time measured in days or minutes, etc. 4. Other ways of expressing dates: y Store as characters or integers with Year, Month Day: 19972011 y Store as Julian date: 1997283 Note: MS Access, SQL Server and Oracle store date and time information together in a DATE data type. Examples of Data Types for Some Popular RDBMS Data types most often used are shown in bold letters Data Type Byte Boolean Integer Long (long integer) Single (singleprecision floating-point) Double (doubleprecision floating-point) Currency Storage Size 1 byte 2 bytes 2 bytes 4 bytes 4 bytes 0 to 255 True or False. -32,768 to 32,767. -2,147,483,648 to 2,147,483,647. -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values. -1.79769313486232E308 to 4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. -922,337,203,685,477.5808 to Range of Values

8 bytes 8 bytes

DECIMAL. Creating a Schema . INTEGER. RAW DATA DEFINITION LANGUAGE DDL is used to define the schema of the database. Any Object reference. 2 billion (approx. 9999.400. POSITIVEN. DEC. NATURALN.477. 100 to December 31. 1. SMALLINT 2. January 1.203.337. Same range as for variable-length String.5807. Oracle supports the following data types: 1. LONG RAW. 2. NUMERIC. NATURAL. POSITIVE. VARCHAR2 4.400 for MS Windows version 3.1). REAL. VARCHAR. Numeric: BINARY_INTEGER.(scaled integer) Date Object String (variablelength) String (fixedlength) Variant (with numbers) Variant (with characters) 8 bytes 4 bytes 10 bytes + string length Length of string 16 bytes 22 bytes + string length 922. Date: DATE (Note: Also stores time. NUMBER. CHARACTER. INT. Create a database schema  Create. Drop or Alter a table  Create or Drop an Index  Define Integrity constraints  Define access privileges to users  Define access privileges on objects NOTE: SQL2 specification supports the creation of multiple schemas per database each with a distinct owner and authorized users. 65. Any numeric value up to the range of a Double. Character: CHAR. PLS_INTEGER. DOUBLE PRECISION. Others: BOOLEAN.) 3. 1 to approximately 65. LONG. FLOAT. 0 to approx. STRING.685.

NOT NULL constraints and referential integrity constraints) are not supported. Note: When naming tables. Date_of_Birth DATE. First_name VARCHAR(18) NOT NULL.0) NOT NULL. go to the Queries form and choose New. order_date DATE. bill_to_state VARCHAR(2). 3. Creating a Table:  CREATE TABLE employee ( Last_Name VARCHAR(20) NOT NULL. Date_of_Birth DATE. CREATE TABLE order_items ( order_number NUMBER(10. bill_to_zip VARCHAR(10).Note: To try out these SQL examples in MS Access. Most of the DDL statements below (including domains. Soc_Sec VARCHAR(11) NOT NULL. Salary NUMBER(8. do not call the last name column: Last Name If you wish to separate words in a name. Employee_Soc_Sec VARCHAR(11) NOT NULL ). First_name VARCHAR(18) NOT NULL.2) ) . 4. For example. bill_to_address VARCHAR(45). Under the View menu. Specifying Primary and Foreign keys: CREATE TABLE order_header ( order_number NUMBER(10. use the underscore character. . line_item NUMBER(4. PRIMARY KEY (order_number) ). columns and other database objects. you can type in any SQL statement and execute it. Note that MS Access's DDL syntax is extremely limited. Soc_Sec VARCHAR(11) NOT NULL.0) NOT NULL.0) NOT NULL. From this point. bill_to_city VARCHAR(20). choose SQL. bill_to VARCHAR(35).  CREATE TABLE dependant ( Last_Name VARCHAR(20) NOT NULL. do not include spaces in the names. sales_person VARCHAR(25). then choose Design View and then close the next dialog box.

Indicate which attribute(s) form a foreign key.  SET DEFAULT . PRIMARY KEY (order_number.Indicates which attribute(s) must have unique values. line_item) ASC . FORIEGN KEY (order_number) REFERENCES order_header (order_number). Example: CREATE INDEX employee_index ON employee (ssn) .Child tuples foreign key is set to NULL .0). Immediate Deferrable until commit time 6.  CREATE INDEX items_index ON order_items (order_number. quantity NUMBER(4. Specifying Constraints on Columns and Tables Constraints on attributes:  NOT NULL . line_item). II.Orphans.part_number VARCHAR(12) NOT NULL. Specify when constraint should be enforced: I. . 5.Indicate which attribute(s) form the primary key  FOREIGN KEY . Referential Integrity Constraint: Specify the behavior for child tuples when a parent tuple is modified. Action to take if referential integrity is violated:  SET NULL . FOREIGN KEY (part_number) REFERENCES parts (part_number) ).  CREATE INDEX order_index ON order_header (order_number) ASC .Set the value of the foreign key to some default value.Attribute may not take a NULL value  DEFAULT . This enforces referential integrity  UNIQUE .Store a given default value i no value is specified  PRIMARY KEY .

PRIMARY KEY (order_number.0) NOT NULL. bill_to_address VARCHAR(45). line_item). CASCADE . CONSTRAINT pk_order_header PRIMARY KEY (order_number) ). order_date DATE. . quantity NUMBER(4.0) NOT NULL.  CREATE TABLE order_items ( order_number NUMBER(10. quantity NUMBER(4.Child tuples are updated (or deleted) according to the action take on the parent tuple.0) NOT NULL. bill_to VARCHAR(35). line_item).0) NOT NULL.0). Examples of ON DELETE and ON UPDATE  CREATE TABLE order_items ( order_number NUMBER(10. CONSTRAINT pk_order_items PRIMARY KEY (order_number. bill_to_city VARCHAR(20). part_number VARCHAR(12) NOT NULL. part_number VARCHAR(12) NOT NULL.  CREATE TABLE order_header ( order_number NUMBER(10. sales_person VARCHAR(25). FOREIGN KEY (part_number) REFERENCES parts (part_number) ). bill_to_state VARCHAR(2). line_item NUMBER(4. line_item NUMBER(4. FORIEGN KEY (order_number) REFERENCES order_header (order_number) ON DELETE SET DEFAULT ON UPDATE CASCADE. Constraints can also be given names so that they can later be modified or dropped easily.0) NOT NULL. bill_to_zip VARCHAR(10).0).

line_item) .0) NOT NULL.  ALTER TABLE order_items ADD CONSTRAINT fk1_order_items FORIEGN KEY (order_number) . An even better approach is to create the tables without constraints and then add them separately with ALTER TABLE statements  CREATE TABLE order_header ( order_number NUMBER(10.  ALTER TABLE order_items ADD CONSTRAINT pk_order_items PRIMARY KEY (order_number.  ALTER TABLE order_header ADD CONSTRAINT pk_order_header PRIMARY KEY (order_number). line_item NUMBER(4. bill_to_city VARCHAR(20). bill_to_state VARCHAR(2).0) NOT NULL. quantity NUMBER(4.CONSTRAINT fk1_order_items FORIEGN KEY (order_number) REFERENCES order_header (order_number) ON DELETE SET DEFAULT ON UPDATE CASCADE. order_date DATE. CONSTRAINT fk2_order_items FOREIGN KEY (part_number) REFERENCES parts (part_number) ON DELETE SET DEFAULT ON UPDATE CASCADE ).  CREATE TABLE order_items ( order_number NUMBER(10. bill_to_address VARCHAR(45). part_number VARCHAR(12) NOT NULL.0) ). sales_person VARCHAR(25). bill_to VARCHAR(35).0) NOT NULL. bill_to_zip VARCHAR(10) ).

 DROP INDEX index_name Removes an index.constraint_name Removes a constraint from a table. domains.  DROP SCHEMA schema_name RESTRICT Removes the schema only if it is empty.REFERENCES order_header (order_number) ON DELETE SET DEFAULT ON UPDATE CASCADE.  To speed up retrieval of orders given sales person: CREATE INDEX idx_sales_person ON order_header (sales_person) .  DROP TABLE table_name Remove the table and all of its data. all tables.  DROP TABLE table_name RESTRICT Remove the table only if it is not referenced (via a FORIEGN KEY constraint) by other tables. Creating indexes on table columns:  To speed up retrieval of orders given order_number: CREATE INDEX idx_order_number ON order_header (order_number) . indexes. .  ALTER TABLE order_items ADD CONSTRAINT fk2_order_items FOREIGN KEY (part_number) REFERENCES parts (part_number) ON DELETE SET DEFAULT ON UPDATE CASCADE. We give the first part of the index name as "idx" just as a convention.  DROP CONSTRAINT table_name. CASCADE option deletes all data. 7.  DROP TABLE table_name CASCADE Remove the table and all related tables as specified by FOREIGN KEY constraints. Removing Schema Components with DROP  DROP SCHEMA schema_name CASCADE Drop the entire schema including all tables. 8. etc.

val2. update. 88. delete) data.25). "03-JUN-94".  INSERT INTO stocks (symbol.. ..  INSERT INTO student_grades (student_id. test_name.9. insert. close_date. Retrieving Data from Tables with Select Main way of getting data out of tables is with the SELECT statement. last_name. "B+").. Examples:  INSERT INTO employee (first_name. . "123 Sticks Ln. Changing Schema Components with ALTER  Changing Attributes: ALTER TABLE student ALTER last_name VARCHAR(35). "31212").. grade) VALUES (101.". 1. column2.  Removing Attributes (not widely implemented): ALTER TABLE student DROP home_phone. ALTER TABLE student ALTER gpa DROP DEFAULT ALTER TABLE student ALTER gpa SET DEFAULT 0. DML is then used to manipulate (select. "Fillville". street. state. close_price) VALUES ("IBM". "Quiz 1".  Adding Attributes: ALTER TABLE student ADD admission DATE. "TN".00. city. zip) VALUES ("Buddy". "Rich". valX). 2. columnX) VALUES (val1. DATA MANIPULATION LANGUAGE DDL is used to create and specify the schema. score. 104. . Inserting Data into Tables General syntax: INSERT INTO tablename (column1.

columnN FROM tableA. close_date. last_name. first_name. close_price FROM stocks WHERE close_date >= "01-JAN-95" ORDER BY symbol. city. state. last_name. tableZ WHERE condition1.conditionM GROUP BY column1. first_name FROM employees WHERE last_name = "Smith" ORDER BY first_name DESC  SELECT employee_id. first_name DESC  SELECT * FROM employees ORDER BY 2. ..  SELECT symbol. close_price FROM stocks WHERE close_date > "01-JAN-95" AND symbol = "IBM" ORDER BY close_date  SELECT symbol. . zip) and a "Stocks" table: stocks(symbol. . column2.. last_name...SELECT syntax: SELECT column1. close_date. column2. first_name FROM employees WHERE salary > 40000 ORDER BY last_name... close_date . tableB. condition2.. columnN Assume an employees table: employees(employee_id. . close_price) Some example queries:  SELECT employee_id.... . HAVING condition ORDER BY column1. street.

first_name FROM employee WHERE salary > 40000 AVG (salary) ( state = 'NJ' (EMPLOYEE) ) SELECT AVG(salary) FROM employee WHERE state = 'NJ' last_name = 'Smith' state = 'NY' (EMPLOYEE) SELECT * FROM employee WHERE last_name = 'Smith' AND state = 'NY'  SQL Built-in Functions Example Table students: Name Major Grade Bill CIS 95 Mary CIS 98 Sue Marketing 88 Tom Finance 92 Alex CIS 79 Sam Marketing 89 Jane Finance 83 . Go to the Queries form and choose New. last_name.. choose SQL.. create the table in MS Access and enter the data shown above.RELATIONAL OPERATORS AND SQL Relational operators each have implementations in SQL. Note: To try out these examples. then choose Design View and then close the next dialog box.  Average grade in the class: . employee_id. first_name ( salary > 40000 (EMPLOYEE) ) SELECT employee_id. Under the View menu. last_name.

major. Results: AVG (GRADE) ---------89.1428571  Give the name of the student with the highest grade in the class: This is an example of a subquery SELECT name.-------------------Mary CIS Tom Finance Sam Marketing GRADE ----98 92 89 . grade FROM students s1 WHERE grade = ( SELECT max (grade) FROM students s2 WHERE s1. Results: NAME MAJOR ------------.----Mary 98  Show the students with the highest grades in each major: SELECT name. grade FROM students WHERE grade = (SELECT MAX (grade) FROM students).major = s2.major ) ORDER BY grade DESC.SELECT AVG(grade) FROM students. Results: NAME GRADE -------------.

name FROM employee.department ORDER BY department. Called a Join. department WHERE employee. employee. List them in order of location and name: SELECT employee. department = department.location.Note the two aliases given to the students table: s1 and s2. department.location FROM employee. . The WHERE part becomes the Join Condition Example table EMPLOYEE: Name Department Salary Joe Finance 50000 Alice Finance 52000 Jill MIS 48000 Jack MIS 32000 Fred Accounting 33000 Example table DEPARTMENTS: Department Location Finance NJ MIS CA Accounting CA Marketing NY  List all of the employees working in California: SELECT employee. location = 'CA'. These allow us to refer to different views of the same table. list all tables separated by commas. Results: NAME -------------------------------Jill Jack Fred  List each employee name and what state (location) they work in. department WHERE SELECTING FROM 2 OR MORE TABLES In the FROM portion. department = department. department AND

department. employee. Show the department and location even if no employees work = 'CA'.  List each department and all employees that work there.department ORDER BY department. Results: DEPARTMENT LOCATION NAME ---------------------------.department = department.salary) FROM employee.location.location. department WHERE employee.department AND department. SELECT FROM employee RIGHT JOIN department ON employee. Results: MAX(SALARY) -----------48000 .Results: NAME LOCATION --------------.------------Fred CA Jack CA Jill CA Alice NJ Joe NJ This is similar to a LEFT JOIN. employee.---------------Accounting CA Fred MIS CA Jack MIS CA Jill Finance NJ Alice Finance NJ Joe Marketing NY NULL  What is the highest paid salary in California ? SELECT MAX(employee.department = department.department.

CustomerID = accounts.customerid GROUP BY customers.LastName Results: LASTNAME SUM(BALANCE) --------. Cartesian Product of the two tables: SELECT * FROM employee. Results: Name employee.Department Salary Department.  List the Customer name and their total account holdings: SELECT customers. department.------------ .LastName. Sum(Balance) FROM customers.3. y From our Bank Accounts example. accounts WHERE customers.Dep Location Joe Finance 50000 Finance NJ Joe Finance 50000 MIS CA Joe Finance 50000 Accounting CA Joe Finance 50000 Marketing NY Alice Finance 52000 Finance NJ Alice Finance 52000 MIS CA Alice Finance 52000 Accounting CA Alice Finance 52000 Marketing NY Jill MIS 48000 Finance NJ Jill MIS 48000 MIS CA Jill MIS 48000 Accounting CA Jill MIS 48000 Marketing NY Jack MIS 32000 Finance NJ Jack MIS 32000 MIS CA Jack MIS 32000 Accounting CA Jack MIS 32000 Marketing NY Fred Accounting 33000 Finance NJ Fred Accounting 33000 MIS CA Fred Accounting 33000 Accounting CA Fred Accounting 33000 Marketing NY  In which states do our employees work? SELECT DISTINCT location FROM department.

000. Name.00 Here is a combination of a function and a column alias: SELECT name. (salary * 1. Sum(Balance) AS TotalBalance FROM customers. A student has only one tutor. salary AS CurrentSalary. department.03) AS ProposedRaise FROM employee.CustomerID = accounts. STUDENTS (StudentID. Results: name -------Alice Fred Jack Jill Joe department -----------Finance Accounting MIS MIS Finance CurrentSalary ProposedRaise ------------.00 Smith $6.300. Recursive Queries and Aliases For example: A student can tutor one or more other students.300.00 Jones $1. Student_TutorID) StudentID Name Student_TutorID .customerid GROUP BY customers.000.000.000.------------52000 53560 33000 33990 32000 32960 48000 49440 50000 51500 4.LastName.000.00 Builder $1.00 We can also use a Column Alias to change the title of the columns SELECT customers. accounts WHERE customers.00 Jones $1.LastName Results: LASTNAME TotalBalance -------------------Axe $15.00 Smith $6.00 Builder $1.Axe $15.000.

We give the table two aliases called s1 and tutors so that we can compare different aspects of the same table.studentid.S101 S102 S103 S104 S105 S106 S107 Bill Alex Mary Liz Ed Sue Petra NULL S101 S101 S103 S103 S101 S106 Provide a listing of each student and the name of their tutor: SELECT s1. Use LEFT JOIN: SELECT s1.studentid. the table is missing something: We don't see who is tutoring Bill Smith. students tutors WHERE s1. However.student_tutorid = AS Tutor FROM students s1. as is. Results: Student ---------Tutor ---------- . tutors. AS Student.student_tutorid = tutors. Results: Student ---------Alex Mary Sue Liz Ed Petra Tutor ---------Bill Bill Bill Mary Mary Sue The above is called a "recursive" query because it access the same table two AS AS Tutor FROM students s1 LEFT JOIN students tutors ON s1.

COUNT( AS TutorName. grade FROM students . grade. Results: TutorName NumberTutored ---------.------------Bill 3 Mary 2 Sue 1 5.Bill Alex Mary Sue Liz Ed Petra Bill Bill Bill Mary Mary Sue Here is one more twist: Suppose we were interested in those students who do not tutor anyone? Use RIGHT JOIN  How many students does each tutor work with ? SELECT i) Typical Logic expressions: COLUMN = value ii) Also: < > = != <= >= iii) Also consider BETWEEN SELECT name.student_tutorid GROUP BY s1. students tutors WHERE s1.studentid = tutors. WHERE Clause Expressions There are a number of expressions one can use in a WHERE clause.student_tutorid) AS NumberTutored FROM students s1. "You Got an A" FROM students WHERE grade between 91 and 100 iv) Subqueries using = (equals): SELECT name.

salary < employee.salary) Results: name salary ----------. the subquery returns a set of tuples. . v) Subqueries using IN:  SELECT name FROM employee WHERE department IN ('Finance'.  SELECT name FROM employee WHERE department IN (SELECT department FROM departments WHERE location = 'CA'). salary FROM employee WHERE EXISTS (SELECT name FROM EMPLOYEE e2 WHERE e2. In the above case.salary) AND EXISTS (SELECT name FROM EMPLOYEE e3 WHERE e3. 'MIS'). The IN clause returns true when a tuple matches a member of the set. This assumes the subquery returns only one tuple as a result.---------Joe 50000 Jill 48000 Fred 33000 The above query shows all employees names and salaries where there is at least one person who makes more money (the first exists) and at least one person who makes less money (second exists).WHERE grade = (SELECT MAX(grade) FROM students ). Typically used for aggregate functions.salary > employee. vi) Subqueries using EXISTS:  SELECT name.

vii) NOT EXISTS:  SELECT name.salary) Results: name salary --------. the * character is used. salary FROM employee . Generally.  Show all employees whose name contains the letter 'e' and the letter 'n' in that order: SELECT name.  Show all employees whose name starts with 'S' SELECT name.salary > employee. salary FROM employee WHERE name LIKE 'S%'.  Show all employees whose name contains the letters 'en' SELECT name.---------Alice 52000 Above query shows all employees for whom there does not exist an employee who is paid less. salary FROM employee WHERE NOT EXISTS (SELECT name FROM EMPLOYEE e2 WHERE e2. Note that chatacters within quotes are case sensitive. the % character is used as the wild card although in some DBMS. viii) LIKE operator: Use the LIKE operator to perform a partial string match. salary FROM employee WHERE name LIKE '%en%'.

salary FROM employee WHERE name LIKE '%e%n%' OR name LIKE '%n%e%'.  Remove only employees making more than $50.  Remove all employees: DELETE employee. For example. Removing a department would then be contingent upon no employees working in that department. DELETE will not be successful if a constraint would be violated. DELETE will remove all tuples from a table. Change Values using UPDATE The UPDATE command is used to change attribute values in the database. 6.  Show all employees whose name contains the letter 'e' and the letter 'n' in any order: SELECT name. . With no WHERE clause. This is what we call enforcing Referential Integrity 7. consider the department attribute in the Employee table as a Foreign Key. Deleting Tuples with DELETE DELETE is used to remove tuples from a table.000 DELETE employee WHERE salary > 50000.  Remove all employees working in California: DELETE employee WHERE department IN (SELECT department FROM department WHERE location = 'CA').WHERE name LIKE '%e%n%'. UPDATE uses the SET clause to overwrite the value.

One can then query these views as if they were tables  SELECT * FROM emp_address ORDER BY last_name. state. if we commonly access just 2 or 3 columns in a table. department. For example. last_name. city. salary)  CREATE VIEW emp_address AS SELECT first_name. we can define a view on that table and then use the view name when specifying queries. state. first_name. last_name. Change the last name of an Employee: UPDATE employee SET last_name = 'Smith' WHERE employee_id = 'E1001'. zip FROM employee. zip. street. Assume an employees table: employees(employee_id. AVG(salary) FROM employee GROUP BY department. salary FROM employee. DEFINING VIEWS: It is possible to define a particular view of a table (or tables).05 WHERE employee_id = 'E1001'.  SELECT * FROM avg_sal_dept . street.  CREATE VIEW avg_sal_dept AS SELECT department.  Give an Employee a raise: UPDATE employee SET salary = salary * 1. city. last_name. 8.  CREATE VIEW emp_salary AS SELECT first_name.

.WHERE department = 'Finance'.