BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E) 1. LECTURE OUTLINE  SQL Data Definition and Data Types  Specifying Constraints in SQL  Basic Retrieval Queries.

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
The Relational Model. Introduction Introduced by Ted Codd at IBM Research in 1970 The relational model represents data in the form of table. Main concept.
OUTLINE OF THE LECTURE PART I GOAL: Understand the Data Definition Statements in Fig 4.1 Step1: Columns of the Tables and Data types. Step2: Single column.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
Fall 2005 ICS184/EECS116 – Notes 08 1 ICS 184/EECS116: Introduction to Data Management Lecture Note 8 SQL: Structured Query Language -- DDL.
Database Design -- Basic SQL
1 Lecture 11: Basic SQL, Integrity constraints
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 28 Database Systems I The Relational Data Model.
Sanjay Goel, School of Business, University at Albany, SUNY 1 SQL- Data Definition Language ITM 692 Sanjay Goel.
SQL Sangeeta Devadiga CS157A, Fall Outline Background Data Definition Basic Structure Set Operation.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 SQL: Data Definition, Constraints, and Basic Queries and Updates.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
CS 104 Introduction to Computer Science and Graphics Problems Introduction to Database (2) Basic SQL 12/05/2008 Yang Song.
Database Systems More SQL Database Design -- More SQL1.
SQL Overview Defining a Schema CPSC 315 – Programming Studio Spring 2008 Project 1, Lecture 3 Slides adapted from those used by Jeffrey Ullman, via Jennifer.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Chapter 3: SQL Data Definition Language Data Definition Language Basic Structure of SQL Basic Structure of SQL Set Operations Set Operations Aggregate.
1 CSE 480: Database Systems Lecture 9: SQL-DDL Reference: Read Chapter of the textbook.
Exam 2 Review Dr. Bernard Chen Ph.D. University of Central Arkansas.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL.
CSE314 Database Systems Lecture 4 Basic SQL Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
1 The Relational Model Instructor: Mohamed Eltabakh
CG084&085 / / 1 The Relational Data Model Properties of Relations Keys and Constraints.
Chapter 8 Part 1 SQL-99 Schema Definition, Constraints, Queries, and Views.
Ms. Hatoon Al-Sagri CCIS – IS Department SQL-99 :Schema Definition, Constraints, Queries, and Views 1.
Chapter 7 SQL HUANG XUEHUA. SQL SQL server2005 introduction Install components  management studio.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Advanced Database CS-426 Week 1 - Introduction. Database Management System DBMS contains information about a particular enterprise Collection of interrelated.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
Chapter 8 Part 2 SQL-99 Schema Definition, Constraints, Queries, and Views.
Lu Chaojun, SJTU Relational Data Model 1. Lu Chaojun, SJTU What’s a Data Model? A notation (collection of conceptual tools) for describing data as seen.
CS 338The Relational Model2-1 The Relational Model Lecture Topics Overview of SQL Underlying relational model Relational database structure SQL DDL and.
CMPT 258 Database Systems The Relationship Model PartII (Chapter 3)
CMPT 258 Database Systems The Relationship Model (Chapter 3)
DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E) 1.
Week 8-9 SQL-1. SQL Components: DDL, DCL, & DML SQL is a very large and powerful language, but every type of SQL statement falls within one of three main.
©Silberschatz, Korth and Sudarshan1 Structured Query Language (SQL) Data Definition Language Domains Integrity Constraints.
1 CS 430 Database Theory Winter 2005 Lecture 10: Introduction to SQL.
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe CHAPTER 6 Basic SQL Slide 6- 1.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
Big Data Yuan Xue CS 292 Special topics on.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Chapter 10 SQL DDL.
More SQL: Complex Queries,
CHAPTER 6 Basic SQL. CHAPTER 6 Basic SQL Chapter 6 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries.
CS 480: Database Systems Lecture 13 February 13,2013.
Chapter 4 Basic SQL.
SQL OVERVIEW DEFINING A SCHEMA
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL-1 Week 8-9.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Presentation transcript:

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E) 1

LECTURE OUTLINE  SQL Data Definition and Data Types  Specifying Constraints in SQL  Basic Retrieval Queries in SQL  Set Operations in SQL 2

BASIC SQL  Structured Query Language  Considered one of the major reasons for the commercial success of relational databases  Statements for data definitions, queries, and updates Both DDL and DML Core specification plus specialized extensions  Terminology: 3 Relational ModelSQL relationtable tuplerow attributecolumn  Syntax notes: Some interfaces require each statement to end with a semicolon. SQL is not case-sensitive.

SQL DATA DEFINITION  CREATE statement Main SQL command for data definition  SQL schema Identified by a schema name Includes an authorization identifier (owner) Components are descriptors for each schema element Tables, constraints, views, domains, and other constructs  CREATE SCHEMA statement CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’; 4

CREATE TABLE COMMAND  Specify a new relation Provide name Specify attributes and initial constraints Base tables (base relations) Relation and its tuples are physically stored and managed by DBMS  Can optionally specify schema: CREATE TABLE COMPANY.EMPLOYEE... or CREATE TABLE EMPLOYEE...  Include information for each column (attribute) plus constraints Column name Column type (domain) Key, uniqueness, and null constraints 5

BASIC DATA TYPES  Numeric data types Integer numbers: INT, INTEGER, SMALLINT, BIGINT Floating-point (real) numbers: REAL, DOUBLE, FLOAT Fixed-point numbers: DECIMAL(n,m), DEC(n,m), NUMERIC(n,m), NUM(n,m) Character-string data types Fixed length: CHAR(n), CHARACTER(n) Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER VARYING(n), LONG VARCHAR  Large object data types Characters: CLOB, CHAR LARGE OBJECT, CHARACTER LARGE OBJECT Bits: BLOB, BINARY LARGE OBJECT  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 6

MORE DATA TYPES  Additional data types 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  Columns can be declared to be NOT NULL  Columns can be declared to have a default value Assigned to column in any tuple for which a value is not specified  Example CREATE TABLE EMPLOYEE ( … NICKNAME VARCHAR(20) DEFAULT NULL, … Province CHAR(2) NOT NULL DEFAULT 'ON', … ); 7

8

DOMAINS IN SQL  Name used in place of built-in data type  Makes it easier to change the data type used by numerous columns  Improves schema readability  Example: CREATE DOMAIN SIN_TYPE AS CHAR(9); 9

SPECIFYING KEY CONSTRAINTS  PRIMARY KEY clause Specifies one or more attributes that make up the primary key of a relation Dnumber INT NOT NULL PRIMARY KEY, Primary key attributes must be declared NOT NULL  UNIQUE clause Specifies alternate (candidate) keys Dname VARCHAR(15) UNIQUE; May or may not allow null values, depending on declaration  If no key constraints, two or more tuples may be identical in all columns. SQL deviates from pure relational model! Multiset (bag) behaviour 10

REFERENTIAL CONSTRAINTS  FOREIGN KEY clause FOREIGN KEY (Dept) REFERENCES DEPARTMENT (Dnum), Default operation: reject update on violation Attach referential triggered action clause in case referenced tuple is deleted Options include SET NULL, CASCADE, and SET DEFAULT  Foreign key declaration must refer to a table already created 11

SPECIFYING TUPLE CONSTRAINTS  Some constraints involve several columns  CHECK clause at the end of a CREATE TABLE statement Apply to each tuple individually  Example CHECK (Dept_create_date <= Mgr_start_date) 12

EXAMPLE  Recall Employee example: 13

14

15

BASIC SQL RETRIEVAL QUERIES  All retrievals use SELECT statement: SELECT FROM [ WHERE ] ; where is a list of expressions or column names whose values are to be retrieved by the query is a list of relation names required to process the query is a Boolean expression that identifies the tuples to be retrieved by the query  Example SELECT title, year, genre FROM Film WHERE director = 'Steven Spielberg' AND year > 1990;  Omitting WHERE clause implies all tuples selected. 16

SEMANTICS FOR 1 RELATION 1.Start with the relation named in the FROM clause 2.Consider each tuple one after the other, eliminating those that do not satisfy the WHERE clause. Boolean condition that must be true for any retrieved tuple Logical comparison operators =,, >=, and <> 3.For each remaining tuple, create a return tuple with columns for each expression (column name) in the SELECT clause. Use SELECT * to select all columns. 17 Film titlegenreyeardirectorminutes budget gross The Company Mendrama2010John Wells104 15,000,000 4,439,063 Lincolnbiography2012Steven Spielberg150 65,000, ,408,467 War Horsedrama2011Steven Spielberg146 66,000,000 79,883,359 Argodrama 2012Ben Affleck120 44,500, ,178,251

SELECT-FROM-WHERE SEMANTICS  What if there are several relations in the FROM clause? 1.Start with cross-product of all relation(s) listed in the FROM clause. Every tuple in R 1 paired up with every tuple in R 2 paired up with … 2.Consider each tuple one after the other, eliminating those that do not satisfy the WHERE clause. 3.For each remaining tuple, create a return tuple with columns for each expression (column name) in the SELECT clause. Steps 2 and 3 are just the same as before. SELECT actor, birth, movie FROM Role, Person WHERE actor = name and birth > 1940; 18 Role actormoviepersona Ben AffleckArgoTony Mendez Alan ArkinArgoLester Siegel Ben AffleckThe Company MenBobby Walker Tommy Lee JonesThe Company MenGene McClary Person namebirthcity Ben Affleck1972Berkeley Alan Arkin1934New York Tommy Lee Jones1946San Saba

AMBIGUOUS COLUMN NAMES  Same name may be used for two (or more) columns (in different relations) Must qualify the column name with the relation name to prevent ambiguity 19 SELECT name, date, product, quantity FROM Customer, Sale, LineItem WHERE price > 100 AND Customer.custid = Sale.custid AND Sale.saleid = LineItem.saleid;  Note If SELECT clause includes custid, it must specify whether to use Customer.custid or Sale.custid even though the values are guaranteed to be identical.  Customer custidnameaddressphone Sale saleiddatecustid LineItem saleidproductquantityprice

2-RELATION SELECT-FROM-WHERE 20 Role actormoviepersona Ben AffleckArgoTony Mendez Tommy Lee JonesLincolnThaddeus Stevens Daniel Day-LewisThe BoxerDanny Flynn Daniel Day-LewisLincolnAbraham Lincoln SELECT award, actor, persona, Role.movie FROM Honours, Role WHERE category = 'actor' AND winner = actor AND Honours.movie = Role.movie Honours movieawardcategorywinner LincolnCritic's ChoiceactorDaniel Day-Lewis ArgoCritic's ChoicedirectorBen Affleck LincolnSAGsupporting actorTommy Lee Jones LincolnCritic's ChoicescreenplayTony Kushner War HorseBMI FlimmusicJohn Williams Honours.movieawardcategorywinneractorRole.moviepersona LincolnCritic's ChoiceactorDaniel Day-LewisBen AffleckArgoTony Mendez  LincolnCritic's ChoiceactorDaniel Day-LewisTommy Lee JonesLincolnThaddeus Stevens  LincolnCritic's ChoiceactorDaniel Day-Lewis The BoxerDanny Flynn  LincolnCritic's ChoiceactorDaniel Day-Lewis LincolnAbraham Lincoln  ArgoCritic's ChoicedirectorBen Affleck ArgoTony Mendez  ArgoCritic's ChoicedirectorBen AffleckTommy Lee JonesLincolnThaddeus Stevens  ArgoCritic's ChoicedirectorBen AffleckDaniel Day-LewisThe BoxerDanny Flynn  ArgoCritic's ChoicedirectorBen AffleckDaniel Day-LewisLincolnAbraham Lincoln  LincolnSAGsupporting actorTommy Lee JonesBen AffleckArgoTony Mendez  LincolnSAGsupporting actorTommy Lee Jones LincolnThaddeus Stevens  LincolnSAGsupporting actorTommy Lee JonesDaniel Day-LewisThe BoxerDanny Flynn  …

RECALL SAMPLE TABLES 21

22

23

24

TABLES AS SETS IN SQL  Duplicate tuples may appear in query results From duplicates in base tables From projecting out distinguishing columns  Keyword DISTINCT in the SELECT clause eliminates duplicates 25

SET OPERATIONS  Result treated as a set (no duplicates) UNION, EXCEPT (difference), INTERSECT  Corresponding multiset (bag) operations: UNION ALL, EXCEPT ALL, INTERSECT ALL  Arguments must be union-compatible Same number of columns Corresponding columns of same type 26

OTHER OPERATORS  Standard arithmetic operators: Addition (+), subtraction (–), multiplication (*), and division (/)  [NOT] LIKE comparison operator Used for string pattern matching Percent sign (%) matches zero or more characters Underscore (_) matches a single character e.g., to also match Tommy Lee Jones as supporting actor: SELECT award, actor, persona, Role.movie FROM Honours, Role WHERE category LIKE ' % actor' AND winner = actor AND Honours.movie = Role.movie;  [NOT] BETWEEN comparison operator WHERE year BETWEEN 1990 AND 2010 equivalent to WHERE year >= 1990 AND YEAR <=

LECTURE SUMMARY  Introduction to SQL Comprehensive language Data definition including constraint specification Basic SELECT-FROM-WHERE Set operators 28