SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To.

Slides:



Advertisements
Similar presentations
Announcements Read 6.4 – 6.6 for Monday Homework 5, due Friday (today) Project Step 4, due Monday Research paper –List of sources - due 10/29.
Advertisements

SQL Rohit Khokher.
Virtual training week 4 structured query language (SQL)
Database Systems: Design, Implementation, and Management Tenth Edition
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
1 Announcements Read 6.7 – 6.10 for Friday Homework 6, due Friday 10/29 Research paper –List of sources - due 10/29 Department Seminar –The Role of Experimentation.
Database Systems Lecture 5 Natasha Alechina
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Oracle Data Definition Language (DDL)
SQL Basics. SQL SQL (Structured Query Language) is a special-purpose programming language designed from managing data in relational database management.
Chapter 9 SQL and RDBMS Part C. SQL Copyright 2005 Radian Publishing Co.
1 IT420: Database Management and Organization SQL - Data Manipulation Language 27 January 2006 Adina Crăiniceanu
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Announcements Read JDBC Project Step 5, due Monday.
Relational Database Management Systems. A set of programs to manage one or more databases Provides means for: Accessing the data Inserting, updating and.
Announcements Read 6.7 – 6.10 for Wednesday Homework 6, due Friday 10/29 Project Step 4, due today Research paper –List of sources - due 10/29.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
BACS--485 SQL 11 BACS 485 Structured Query Language.
Oracle Data Definition Language (DDL) Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
Wednesday, January 14,  Proposed by E.F.Codd in his 1970 paper  Used in System R, IBM’s research relational database in early 1970s-D.D. Chamberlin.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
BACS 287 Structured Query Language 1. BACS 287 Visual Basic Table Access Visual Basic provides 2 mechanisms to access data in tables: – Record-at-a-time.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
DBSQL 5-1 Copyright © Genetic Computer School 2009 Chapter 5 Structured Query Language.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
CMPT 258 Database Systems The Relationship Model (Chapter 3)
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
IS6146 Databases for Management Information Systems Lecture 3: SQL III – The DDL Rob Gleasure robgleasure.com.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
SQL Basics Review Reviewing what we’ve learned so far…….
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
Fundamentals of DBMS Notes-1.
SQL Query Getting to the data ……..
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Chapter 2 Views.
Database systems Lecture 3 – SQL + CRUD
Chapter 7 Introduction to Structured Query Language (SQL)
Chapter 2 Views.
Contents Preface I Introduction Lesson Objectives I-2
CSC 453 Database Systems Lecture
IST 318 Database Administration
Presentation transcript:

SQL

Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To access data Authorization language –To grant privileges to users SQL supports dynamic database definition –Structures can be modified easily

About SQL Its fairly standard across the all relational database management systems but… There are some differences in –Syntax –Data types –Functionality As a rule, Oracle is a better environment in which to learn SQL than Access… –But we will look at both, with an emphasis on Oracle

DDL Commands CREATE TABLE CREATE INDEX ALTER TABLE RENAME TABLE DROP TABLE DROP INDEX CREATE VIEW

CREATE TABLE CREATE TABLE base-table-name (colname datatype [column constraints NULL/NOT NULL, DEFAULT…, UNIQUE, CHECK…, PRIMARY KEY], [,colname datetype [column constraints …]]... [table constraints PRIMARY KEY…, FOREIGN KEY…, UNIQUE…, CHECK…] [storage specifications]);

Student Table CREATE TABLE Student( stuIdCHAR(6), lastNameCHAR(20) NOT NULL, firstName CHAR(20) NOT NULL, majorCHAR(10), credits SMALLINT DEFAULT 0, CONSTRAINT Student_stuId_pk PRIMARY KEY (stuId), CONSTRAINT Student_credits_cc CHECK (credits>=0 AND credits < 150)) ;

Create Tables for University DB CREATE TABLE Student( previous slide ) CREATE TABLE Faculty( facIdCHAR(6), name CHAR(20) NOT NULL, departmentCHAR(20) NOT NULL, rank CHAR(10), CONSTRAINT Faculty_facId_pk PRIMARY KEY (facId)); CREATE TABLE Class( classNumberCHAR(8), facId CHAR(6) NOT NULL, schedule CHAR(8), roomCHAR(6), CONSTRAINT Class_classNumber_pk PRIMARY KEY (classNumber), CONSTRAINT Class_facId_fk FOREIGN KEY (facId) REFERENCES Faculty (facId)) ; CREATE TABLE Enroll( stuIdCHAR(6), classNumberCHAR(8), gradeCHAR(2), CONSTRAINT Enroll_classNumber_stuId_pk PRIMARY KEY (classNumber, stuId), CONSTRAINT Enroll_classNumber_fk FOREIGN KEY (classNumber) REFERENCES Class (classNumber), CONSTRAINT Enroll_stuId_fk FOREIGN KEY (stuId) REFERENCES Student(stuId)) ;

Rules for Identifiers No SQL keywords may be used Table name must be unique within the database Column names user must be unique within the table

Data Types Each column must have a data type specified –Numeric, fixed and varying-length character strings, bit strings, and user-defined types Data types vary by rdbms –See text and mysql documentation

User-defined Data Types We can declare our own domains and set constraints at the domain level: CREATE DOMAIN creditValues INTEGER DEFAULT 0 CHECK (VALUE >=0 AND VALUE <150); This domain (data) type can then be used in defining columns: –In Student, can write credits creditValues –And we can use creditValues to define other data

Constraints These can be defined at: –column level –table level Column-level constraints –NULL/NOT NULL –UNIQUE –PRIMARY KEY –CHECK –DEFAULT –Written immediately after column name or datatype

Table-level constraints PRIMARY KEY –For composite keys (simple ones at column level) FOREIGN KEY –Requires that the referenced table has already been created UNIQUE –Specifies values in a combination of columns that must be unique –Used to specify candidate keys ON DELETE / ON UPDATE for foreign keys –CASCADE / SET NULL/ SET DEFAULT / NO ACTION; Constraints can be given a name –This can be useful for disabling them at times

Indexes We can create any number of indexes for a given table –They facilitate fast retrieval of records with specific values in a column –They don’t always return unique values Overhead is involved –The rdbms must maintain the index Tree data structures used to order values on index

CREATE INDEX CREATE [UNIQUE] INDEX indexname ON basetablename (colname [order] [,colname [order]]...) [CLUSTER] ; CREATE INDEX Student_lastName_firstName_ndx ON Student (lastName, firstName); UNIQUE enforces unique values for indexed column or combination of columns –The column need not be unique –Order is ASC (default) or DESC CLUSTER specification keeps records with same value for indexed field together (only one per table)

ALTER TABLE To add a new column ALTER TABLE basetablename ADD columnname datatype; ALTER TABLE Student ADD COLUMN birthdate DATETYPE; To drop a column ALTER TABLE basetablename DROP COLUMN columnname; ALTER TABLE Student DROP COLUMN major; To add a constraint ALTER TABLE basetablename ADD CONSTRAINT constraint_defn; To drop a constraint ALTER TABLE basetablename DROP CONSTRAINT constraint_name;

Other Changes to Tables Renaming a table: RENAME TABLE old-table-name TO new-table-name; RENAME TABLE FACULTY TO TEACHERS; Dropping a table: DROP TABLE basetablename; DROP TABLE CLASS; Dropping an index: DROP INDEX indexname; DROP INDEX Student_lastName_fristName_ndx;

SQL DML Non-procedural, declarative language Can be –interactive –embedded in host language –stand-alone (SQL/PSMs) Basic commands SELECT UPDATE INSERT DELETE

SELECT Statement SELECT [DISTINCT] col-name [AS newname], [,col-name..]… FROMtable-name [alias] [,table-name]… [WHEREpredicate] [GROUP BY col-name [,col-name]…[HAVING predicate] or … [ORDER BY col-name [,col-name]…];

UniversityDB stuID lastName firstName major credits classNo schedule room facID name dept rank stuID classNo grade Student Enroll Class Faculty

Get names & ids of all Math majors SELECT lastname, firstname, stuID FROM Student WHERE major = ‘Math’;

Get all info about CSC faculty SELECT * FROM Faculty WHERE dept = ‘CSC’;

Get the course numbers for all courses with enrollment SELECT DISTINCT classNum FROM Enroll;

Display the Student table SELECT * FROM Student;

Get names & ID’s of all faculty, listed alphabetically SELECT name, facID FROM Faculty ORDER BYname; SELECT name, facID FROM Faculty ORDER BYname, facID;

Get names of all math majors with > 30 credits SELECT lastName, firstName FROM Student WHEREmajor = ‘MATH’ AND credits > 30;

Find ID’s and names of all students in ART 103A SELECT Student.stuID, lastName, firstName FROM Student, Enroll WHEREStudent.stuID = Enroll.stuID; (Joining two tables)

Find ID’s (in ascending order) and grades of all students taking a course with faculty ‘F110’ SELECT stuID, grade FROM Class, Enroll WHEREClass.classNumber = Enroll.classNumber AND facID = ‘F110’ ORDER BYstuID;

Find class #’s, names & majors of all students taking a course with faculty ‘F110’ SELECT Enroll.classNumber, lastName, firstName, major FROM Class, Enroll, Student WHEREClass.classNumber = Enroll.classNumber AND Enroll.stuID = Student.stuID AND facID = ‘F110’ ORDER BYstuID;

Find class #’s of all of classes that meet in the same room SELECT C1.classNumber, C2.classNumber FROM Class C1, Class C2 WHEREC1.room = C2.room AND C1.classNumber <> C2.classNumber Must compare the Class table with itself – requires aliases. This example works on the assumption that a maximum of two classes will meet in the same room

Subqueries These are queries within queries SELECT columnName(s) FROMtableName(s) WHEREsomeColumnName = or IN (SELECT columnName(s) FROMtableName(s) WHEREsomeCondition); The subquery executes FIRST

Find all class #’s for Byrne of the Math Dept SELECT classNumber FROM Class WHERE facID = (SELECT facID FROM Faculty WHERE name = ‘Byrne’ AND dept = ‘Math’);

Aggregate functions COUNT SUM MAX MIN AVG

How many students are in ART 103A? SELECT COUNT (DISTINCT stuID) FROM ENROLL WHEREclassNumber = ‘ART103A’;

Find the ID of the student with the most credits SELECT stuID FROM Student WHERE credits = (SELECT MAX(credits) FROMStudent); Must use subquery

List each class# along with its enrollment SELECT classNumber, COUNT(stuID) FROM Enroll GROUP BYclassNumber;

Recap SQL commands so far SELECT is basic –* is the ‘wildcard’ or list column names WHERE for all conditions –Including joins ORDER BY for sorting AND, OR, NOT logical operations AS for aliases –good for using same table twice Subqueries Aggregate functions (Example 18 is excellent) –COUNT, SUM, MAX, MIN, AVG –GROUP BY

Some new SQL DML Nested subqueries EXISTS / NOT EXISTS UNION Formatting query results HAVING with GROUP BY LIKE NULL Updating operators

Nested queries Get an alphabetical list of names & id’s of all students in any class taught by F110 SELECT lastName, firstName, stuID FROM Student WHERE stuID IN (SELECT stuID FROM Enroll WHERE classNumber IN (SELECT classNumber FROM Class WHERE facID = 'F110')) ORDER BY lastName, firstName; 1 2 3

EXISTS / NOT EXISTS Correlated subqueries Names of all students enrolled in CSC201A Also, NOT EXISTS SELECT lastName, firstName FROMStudent WHERE EXISTS (SELECT * FROM Enroll WHERE Enroll.stuID = Student.stuID ANDclassNumber = ‘CSC201A’;

UNION Can be used instead of OR in a condition if the condition SELECT facID FROM Faculty WHERE department = 'History' UNION SELECT facID FROM Class WHERE room = 'H221'; One query

Formatting query results List the student id and # courses each student has taken. –Uses an expression, a string constant and an alias for a column name. SELECT stuID, 'Number of courses =', credits/3 AS Courses FROM Student;

HAVING HAVING : GROUP BY as WHERE : SELECT Find all courses with fewer than 3 students SELECT className FROM Enroll GROUP BYclassName HAVINGCOUNT(*) < 3;

LIKE For pattern matching List the names of all Math classes SELECT * FROM Class WHERE classNumber LIKE 'MTH*'; In Access, use *

NULL Find the stuID & classes of all students with missing grades. SELECT stuID, classNumber FROM Enroll WHERE grade IS NULL; Can’t use = here

Updating operators UPDATE INSERT DELETE

UPDATE Operator UPDATEtablename SETcolumnname = expression [columnname = expression]... [WHEREpredicate]; Used for changing values in existing records Can update one or many records in a table –All that meet the WHERE condition will be changed For null value, use SET columnname = NULL Can use a sub-query to identify records to be updated

UPDATE examples See hand-out, pp –Examples 1-6

INSERT Operator INSERT INTOtablename [(colname [,colname]...)] VALUES(constant [,constant]...); Used for inserting new records into database, one at a time Not necessary to name columns if values are supplied for all columns, in proper order To insert null value for a column, specify only the other columns or write null as the value Can specify values for some columns, in any order, as long as values match order

INSERT examples See hand-out, –Examples 1-4

DELETE Operator DELETE FROMtablename WHEREpredicate; Used to remove records from a table Can delete one or many records at a time Operation may not work if it would violate referential integrity Can use a sub-query to target records to be deleted If you delete all records from a table, its structure still remains, and you can insert into it later

DELETE examples See hand-out, pp –Examples 1-4

Exercises Use the ASSIGNS DDL commands to create an Access database –Code the SQL commands for Hand-out, pp , problems ; –Code the SQL commands for Hand-out, pp , Lab Exercise 6.2c

Active Databases DBMS monitors database to prevent illegal states –Constraints –Triggers

Constraints –Specified when table is created, or later –IMMEDIATE MODE constraint checked when each INSERT, DELETE, UPDATE is performed –DEFERRED MODE – see pp postpones constraint checking to end of transaction SET CONSTRAINT name DEFERRED –Can use DISABLE CONSTRAINT name, ENABLE CONSTRAINT name

Triggers ECA model: –Event some change made to the database –Condition a logical predicate –Action a procedure done when the event occurs and the condition is true, also called firing the trigger

Triggers Can be fired before or after –Insert –Update –Delete It accesses values it needs as :OLD. and :NEW. –:OLD refers to values being deleted or replaced –:NEW refers to the values just inserted or those replacing old values Can specify how many times a trigger fires –once for each triggering statement, or –for each row that is changed by the statement

Trigger Syntax CREATE TRIGGER trigger_name [BEFORE/AFTER] [INSERT/UPDATE/DELETE] ON table_name [FOR EACH ROW] [WHEN condition] BEGIN trigger body END; Can ALTER TRIGGER name DISABLE; ALTER TRIGGER name ENABLE; DROP TRIGGER name; See examples in Figure 6.5

Relational Views Can be subsets of base tables, subsets of joins, or contain calculated data Many reasons for views –Allow different users to see the data in different forms –Provide a simple authorization control device –Free users from complicated DML operations –If database is restructured, view can keep the user's model constant

Create View CREATE VIEWviewname [(viewcolname(s)…] ASSELECT colname(s)... FROM basetablename(s)… WHERE condition(s); Value-independent view –A vertical subset of a table, with no WHERE, Value-dependent view –Choose only certain rows, using WHERE Join view Can use functions in SELECT

Using Views Views can be queried –SELECT colname(s) FROM viewname –Views can be used to create other views Views can be updated –The primary key must be in the view –An INSTEAD OF trigger is used to update base table(s), and the change is reflected in the view CREATE TRIGGER InsertStuVw2 INSTEAD OF INSERT ON StudentVw2 FOR EACH ROW BEGIN INSERT INTO Student VALUES (:NEW.stuId, :NEW.lastName, :NEW.firstName, :NEW. Credits); END;

Ending Transactions COMMIT makes permanent changes in the current transaction ROLLBACK undoes changes made by the current transaction