SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Similar documents
Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Full file at

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

Data about data is database Select correct option: True False Partially True None of the Above

Follow these steps to get started: o Launch MS Access from your start menu. The MS Access startup panel is displayed:

1) Introduction to SQL

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

Basant Group of Institution

Lecture 07. Spring 2018 Borough of Manhattan Community College

Mahathma Gandhi University

Lab # 4. Data Definition Language (DDL)

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

SQL functions fit into two broad categories: Data definition language Data manipulation language

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Physical Design of Relational Databases

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Solved MCQ on fundamental of DBMS. Set-1

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

GridDB Advanced Edition SQL reference

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

Index. Bitmap Heap Scan, 156 Bitmap Index Scan, 156. Rahul Batra 2018 R. Batra, SQL Primer,

Exact Numeric Data Types

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Relational Database Language

SQL Data Definition and Data Manipulation Languages (DDL and DML)

Oracle Database 10g: Introduction to SQL

UNIT-IV (Relational Database Language, PL/SQL)

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

Basic SQL. Basic SQL. Basic SQL

Chapter 1 SQL and Data

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

SQL - Subqueries and. Schema. Chapter 3.4 V4.0. Napier University

Database Management System 9

SQL Interview Questions

CMP-3440 Database Systems

Course Outline and Objectives: Database Programming with SQL

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

Creating and Managing Tables Schedule: Timing Topic

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

MTAT Introduction to Databases

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109

Chapter-14 SQL COMMANDS

INTRODUCTION TO DATABASE

Introduction to Computer Science and Business

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

An Introduction to Structured Query Language

@vmahawar. Agenda Topics Quiz Useful Links

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

Midterm Review. Winter Lecture 13

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

Exam code: Exam name: Database Fundamentals. Version 16.0

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

CSC Web Programming. Introduction to SQL

SQL Data Definition Language

Data Definition Language (DDL)

Principles of Data Management

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts

SQL: The Query Language Part 1. Relational Query Languages

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course:

SQL Data Definition Language: Create and Change the Database Ray Lockwood

The SQL database language Parts of the SQL language

ITCertMaster. Safe, simple and fast. 100% Pass guarantee! IT Certification Guaranteed, The Easy Way!

Oracle Syllabus Course code-r10605 SQL

An Introduction to Structured Query Language

Chapter 3: Introduction to SQL

DS Introduction to SQL Part 1 Single-Table Queries. By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

BEGINNING T-SQL. Jen McCown MidnightSQL Consulting, LLC MinionWare, LLC

An Introduction to Structured Query Language

Assignment Session : July-March

Optional SQL Feature Summary

Slides by: Ms. Shree Jaswal

Chapter 3: Introduction to SQL

SQL: Data Definition Language

Deccansoft softwareservices-microsoft Silver Learing Partner. SQL Server Syllabus

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

user specifies what is wanted, not how to find it

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

Lecture 3 SQL. Shuigeng Zhou. September 23, 2008 School of Computer Science Fudan University

Querying Data with Transact SQL

An Introduction to Structured Query Language

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

An Introduction to Structured Query Language

TINYINT[(M)] [UNSIGNED] [ZEROFILL] A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2

DATABASE DESIGN I - 1DL300

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model

T-SQL Training: T-SQL for SQL Server for Developers

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

STRUCTURED QUERY LANGUAGE (SQL)

How to define a relational schema for a data base?

MTA Database Administrator Fundamentals Course

Data Definition Language with mysql. By Kautsar

Sql Server Syllabus. Overview

Transcription:

SQL Fundamentals Chapter 3 Class 03: SQL Fundamentals 1

Class 03: SQL Fundamentals 2

SQL SQL (Structured Query Language): A language that is used in relational databases to build and query tables. Earlier versions named Structured English Query Language (SEQUEL) Class 03: SQL Fundamentals 3

Syntax Conventions Keyword identifies the operation Statement ended with an optional semi colon Statements divided into clauses Most clauses are optional Clauses usually must be in a specific sequence White space separates elements (keywords, operators, constants, etc.) Class 03: SQL Fundamentals 4

Constants in SQL Numeric constants are simply numbers; may include: A decimal point A sign E (scientific notation) Character constants are enclosed in single quotes Class 03: SQL Fundamentals 5

Object Names SQL Standard specifies up to 128 character names Many SQL implementations have lower length limits Names should not be case sensitive per the standard However, there are exceptions Names are composed of letters, numeric digits, and the underscore (spaces within names are not supported) SQL Standard allows for quoted identifiers (using double quotes to enclose the entire name) Supports names with keywords, spaces, special characters Quoted identifiers must match exactly, including case Class 03: SQL Fundamentals 6

SQL Statement Categories Data Query Language (DQL) Statements that query data but change nothing SELECT statement Data Manipulation Language (DML) Statements that modify data values but not data structures (tables, views, etc.) INSERT, UPDATE, DELETE statements Class 03: SQL Fundamentals 7

SQL Statement Categories Data Definition Language (DDL) Statements that add/change/delete database objects, but not the data within them (the containers but not the contents) CREATE, ALTER, DROP statements Data Control Language (DCL) Statements that manage privileges users have regarding database objects GRANT, REVOKE statements Class 03: SQL Fundamentals 8

Data Types SQL Standard specifies data types, but vendor extensions are common Data Type Classes: String: for character strings and bit strings Numeric: for numbers Datetime: for dates, times, timestamps Boolean: logical true/false (sparsely supported) Class 03: SQL Fundamentals 9

String Data Types CHARACTER (CHAR) CHARACTER VARYING (VARCHAR) CHARACTER LARGE OBJECT (CLOB) XML NATIONAL CHARACTER (NCHAR) NATIONAL CHARACTER VARYING (NVARCHAR) BINARY BINARY VARYING BINARY LARGE OBJECT (BLOB) Class 03: SQL Fundamentals 10

Numeric Data Types NUMERIC DECIMAL INTEGER SMALLINT BIGINT FLOAT REAL DOUBLE PRECISION Class 03: SQL Fundamentals 11

DateTime Data Types DATE Some implementations store time down to seconds in DATE data types TIME TIME WITH TIME ZONE TIMESTAMP Use DATETIME in SQL Server it uses TIMESTAMP for an entirely different purpose TIMESTAMP WITH TIME ZONE Class 03: SQL Fundamentals 12

NULL Values NULL represents an unknown value (instead of using false data to represent unknown ) NULL is not the same as a blank or a zero or an empty string NULLs are not equal to anything else, including other NULLs Test for NULL using IS NULL rather than = NULL Nulls cause problems because they introduce three value logic where Boolean is two valued Class 03: SQL Fundamentals 13

The Need for Null Values Class 03: SQL Fundamentals 14

DDL Data Definition Language Class 03: SQL Fundamentals 15

DDL Statements CREATE creates new objects (tables, indexes, views, etc.) ALTER changes the definition of existing objects DROP destroys objects TRUNCATE efficiently empties a table (without the need for row byrow deletion of the data) Not described in the text because TRUNCATE was added to the standard after the text was written Class 03: SQL Fundamentals 16

Creating Tables CREATE TABLE table_name (column_name data_type [(length)] [NOT NULL], ) IN tablespace_name PRIMARY KEY [key_name] (column list) FOREIGN KEY [constraint_name] (column list) REFERENCES table_name (column list) ON DELETE {RESTRICT CASCADE SET NULL} Class 03: SQL Fundamentals 17

CREATE TABLE Example DROP TABLE INVOICE; CREATE TABLE INVOICE ( ID CHAR(5), ORDER_DATE DATE, AMOUNT DECIMAL(8,2), CUSTOMER_ID CHAR(5), EMPLOYEE_ID CHAR(11) ); Class 03: SQL Fundamentals 18

Primary Key Constraint A Primary Key constraint forces uniqueness on a column or set of columns. The DBMS creates a Unique Index to enforce the constraint. Each table may have only one primary key (but that key may be one or several columns) Alternatively, you can create a Unique Index to do the same thing, but it won t have a constraint name. Class 03: SQL Fundamentals 19

Primary Key Example ALTER TABLE INVOICE ADD CONSTRAINT PK_INVOICE PRIMARY KEY (ID); VS. CREATE UNIQUE INDEX PK_INVOICE ON INVOICE (ID); Class 03: SQL Fundamentals 20

Altering Table Definitions ALTER TABLE table_name ADD column_name RENAME column_name TO new_name MODIFY column_name DROP PRIMARY KEY DROP FOREIGN KEY constraint_name CHECK (check constraint condition) Class 03: SQL Fundamentals 21

Alter Table ALTER TABLE CUSTOMER ADD CONSTRAINT PK_CUSTOMER PRIMARY KEY (ID); ALTER TABLE INVOICE ADD CONSTRAINT FK_CUST_ID FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER(ID); Class 03: SQL Fundamentals 22

Create Index Indexes can make queries run more efficiently but they are never necessary to achieve correct results Indexes are used to enforce uniqueness of single columns or sets of columns Example: CREATE INDEX invoice_customer_ix ON invoice (customer_id); Class 03: SQL Fundamentals 23

DROP Statement DROP statement destroys an object and its contents. If you merely want to remove the data from a table, use TRUNCATE or DELETE instead. DROP INDEX RACE_RESULT_HORSE; DROP TABLE RACE_RESULT CASCADE CONSTRAINTS; Class 03: SQL Fundamentals 24

DQL Data Query Language (The SELECT Statement) Class 03: SQL Fundamentals 25

Relational Operations Selection: Defines a relation that contains only those tuples (rows) that satisfy the specified condition (predicate) Projection: Defines a relation that extracts the values of specified attributes (and eliminates duplicates) Cartesian Product: Defines a relation that is the concatenation of every tuple in one relation with every tuple in another Class 03: SQL Fundamentals 26

Relational Operations Union: The concatenation of two relations (duplicates eliminated); relations must be union compatible Union compatible: relations with the same number of attributes and matching domains Set Difference: Defines a relation that contains all tuples from one relation that are not contained in another; must be unioncompatible Class 03: SQL Fundamentals 27

Relational Operations Join: a combination of two relations to form a new relation; a derivative of a Cartesian product that uses a join predicate to specify how tuples are to be joined There are multiple types of joins, but in a language like SQL, they are all written using the same syntax Class 03: SQL Fundamentals 28

Relational Joins Equi join: A join where the join predicate contains only the equality operator (=) The most commonly used form Theta Join: A join where the join predicate contains any comparison operator: <, <=, >, >=,!= (<>), BETWEEN Class 03: SQL Fundamentals 29

Relational Joins Outer Join: A join that includes a row from one of the relations even when there is no matching row in the other; missing attributes appear as null Left Outer Join: Outer join that returns every row for the left hand relation Right Outer Join: Outer join that returns every row from the right hand relation Class 03: SQL Fundamentals 30

SQL Demo (see separate presentation) Class 03: SQL Fundamentals 31

Views Class 03: SQL Fundamentals 32

Views View: A dynamic result of one or more relational operations on the base relations to produce another relation; a virtual relation that does not exist in the database, but is produced upon request Base Relation: A named relation corresponding to an entity in the conceptual schema whose tuples are physically stored in the database Class 03: SQL Fundamentals 33

Views Views can be constructed on the fly by performing various relational operations The definition of a view can be permanently stored in the catalog and used in relational operations in the same way as tables; stored views never contain data Changes made to the data in the base relations are automatically reflected in the view. Class 03: SQL Fundamentals 34

Class 03: SQL Fundamentals 35

Purpose/Benefits of Views Provides a powerful and flexible security mechanism by hiding parts of the database from certain users Permits users to access data that is customized to their needs Can simplify complex operations on base relations (e.g. views can handle joins) Class 03: SQL Fundamentals 36

Updating Views The ability to apply updates to views varies widely from one DBMS to another Most DBMSs recognize views as updateable and not updateable ; a few recognize partially updateable views Generally, views formed form a single relation that contain either a primary or candidate key can be updated Class 03: SQL Fundamentals 37

Updating Views Updates are generally not allowed through views involving multiple base relations Updates are generally not allowed through views involving aggregation or grouping operations Updates are generally not allowed on derived/calculated attributes in views Class 03: SQL Fundamentals 38

Updating Views Class 03: SQL Fundamentals 39

DML Data Manipulation Language Class 03: SQL Fundamentals 40

INSERT Statement Adds new rows to a table Column list is optional, but highly recommended for flexibility and data independence Two forms: INSERT with VALUES: VALUES clause provides values for a row of data Some implementation support multiple VALUES clauses, each of which causes one row to be added INSERT with Subquery SELECT statement provides the rows and column values to be inserted. Class 03: SQL Fundamentals 41

INSERT Statement Examples INSERT INTO RACE_RESULT (TRACK_ID, RACE_NUMBER, RACE_DATE, HORSE_ID, PLACE PURSE, LENGTHS_BEHIND) VALUES ('Winona','1','2015-07-04','KY0993',4,0,10); INSERT INTO RACE_RESULT (TRACK_ID, RACE_NUMBER, RACE_DATE, HORSE_ID, PLACE PURSE, LENGTHS_BEHIND) VALUES ('Winona','1','2015-07-04','QH0334',1,2500,0), ('Winona','1','2015-07-04','QH3993',5,0,11), ('Winona','1','2015-07-04','QH0443',3,500,1.5); Class 03: SQL Fundamentals 42

INSERT Statement Examples INSERT INTO RACE_RESULT (TRACK_ID, RACE_NUMBER, RACE_DATE, HORSE_ID, PLACE PURSE, LENGTHS_BEHIND) SELECT TRACK_ID, RACE_NUMBER, RACE_DATE, HORSE_ID, PLACE, PURSE, LENGTHS_BEHIND FROM RACE_RESULT WHERE RACE_DATE BETWEEN '2015-01-01' AND '2015-12-31'; Class 03: SQL Fundamentals 43

Update Statement Modifies data values within a table SET clause specifies the list of columns to be updated, along with an expression that provides a new value for each column If WHERE clause is omitted, will attempt to update very row in the table UPDATE OWNER SET OWNER_LAST_NAME = 'McMillan, STREET_ADDRESS = '3205 Equine Ct., Apt. 6' WHERE OWNER_ID = '00011'; Class 03: SQL Fundamentals 44

DELETE Statement Removes rows from a table If WHERE clause is omitted, attempts to delete all the rows in the table DELETE FROM RACE_RESULT WHERE RACE_DATE < '2012-01-01'; Class 03: SQL Fundamentals 45

Data Control Language DCL Class 03: SQL Fundamentals 46

Privileges DCL statements manage privileges for database accounts. Privileges can be: System privileges, which permit the grantee to perform a general DBMS function, such as creating views or connecting to the database. Object privileges, which permit the grantee to perform specific actions on specific objects, such as selecting from the OWNER table or inserting into the RACE_RESULT table Class 03: SQL Fundamentals 47

GRANT Statement Gives one or more privileges to grantee(s). Examples: GRANT CREATE VIEW TO HR; GRANT SELECT, INSERT, UPDATE ON RACE_RESULT TO Mgr123; Class 03: SQL Fundamentals 48

REVOKE Statement Takes privileges away from grantees Examples: REVOKE CREATE VIEW FROM HR; REVOKE SELECT, INSERT, UPDATE ON RACE_RESULT FROM Mgr123; Class 03: SQL Fundamentals 49