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

Similar documents
Basic SQL. Basic SQL. Basic SQL

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

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

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

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

Slides by: Ms. Shree Jaswal

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

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

CSIE30600 Database Systems Basic SQL 2. Outline

CS 338 Basic SQL Part II

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

ECE 650 Systems Programming & Engineering. Spring 2018

Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries

SQL STRUCTURED QUERY LANGUAGE

SQL. Copyright 2013 Ramez Elmasri and Shamkant B. Navathe

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

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

SQL-99: Schema Definition, Basic Constraints, and Queries. Create, drop, alter Features Added in SQL2 and SQL-99

Chapter 8. Joined Relations. Joined Relations. SQL-99: Schema Definition, Basic Constraints, and Queries

COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1)

Database design process

Structured Query Language (SQL)

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

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

Overview Relational data model

Database Technology. Topic 3: SQL. Olaf Hartig.

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

SQL: Data Definition Language

SQL Introduction. CS 377: Database Systems

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Database Technology. Topic 2: Relational Databases and SQL. Olaf Hartig.

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

2.9 Table Creation. CREATE TABLE TableName ( AttrName AttrType, AttrName AttrType,... )

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

Database System Concepts, 5th Ed.! Silberschatz, Korth and Sudarshan See for conditions on re-use "

Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations Views Modification of the Database Data Definition

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

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

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

Data Manipulation Language (DML)

SQL Structured Query Language Introduction

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

SQL Data Definition Language

Principles of Data Management

Exact Numeric Data Types

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

Lecture 07. Spring 2018 Borough of Manhattan Community College

Ref1 for STUDENT RECORD DB: Ref2 for COMPANY DB:

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

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

Chapter 3: Introduction to SQL

The SQL data-definition language (DDL) allows defining :

The Relational Model of Data (ii)

SQL. Lecture 4 SQL. Basic Structure. The select Clause. The select Clause (Cont.) The select Clause (Cont.) Basic Structure.

CSEN 501 CSEN501 - Databases I

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

Data and Tables. Bok, Jong Soon

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

QQ Group

A taxonomy of SQL queries Learning Plan

SQL: Advanced Queries, Assertions, Triggers, and Views. Copyright 2012 Ramez Elmasri and Shamkant B. Navathe

CS2300: File Structures and Introduction to Database Systems

More SQL: Complex Queries, Triggers, Views, and Schema Modification

The SQL database language Parts of the SQL language

Unit 1 - Chapter 4,5

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

Chapter 3: Introduction to SQL

SQL DATA DEFINITION LANGUAGE

Lab # 4. Data Definition Language (DDL)

CSC 261/461 Database Systems Lecture 6. Fall 2017

DATABASE TECHNOLOGY - 1MB025

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

user specifies what is wanted, not how to find it

Chapter 4: SQL. Basic Structure

DATABASE TECHNOLOGY. Spring An introduction to database systems

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

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

DATABASTEKNIK - 1DL116

DATABASE TECHNOLOGY - 1MB025

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Data Definition Language (DDL)

DATABASE DESIGN I - 1DL300

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

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E)

Midterm Review. Winter Lecture 13

Programming and Database Fundamentals for Data Scientists

SQL DATA DEFINITION LANGUAGE

An Introduction to Structured Query Language

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

1) Introduction to SQL

Database Management Systems,

Relational Database Systems Part 01. Karine Reis Ferreira

Applied Databases. Sebastian Maneth. Lecture 7 Simple SQL Queries. University of Edinburgh - February 1 st, 2016

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

Simple SQL. Peter Y. Wu. Dept of Computer and Information Systems Robert Morris University

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

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

Transcription:

Basic SQL Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

MIDTERM EXAM 2

Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases 3

Basic SQL Terminology: Table, row, and column used for relational model terms relation, tuple, and attribute 4

The CREATE TABLE Command in SQL Specifying a new relation Provide name of table Specify attributes, their types and initial constraints Can optionally specify schema: CREATE TABLE COMPANY.EMPLOYEE... or CREATE TABLE EMPLOYEE... 5

The CREATE TABLE Command in SQL CREATE TABLE "table_name" ("column1" "data type", "column2" "data type", "column3" "data type"); 6

The CREATE TABLE Command in SQL CREATE TABLE employee (first varchar(15), last varchar(20), age int(3), address varchar(30)); 7

The CREATE TABLE Command in SQL Base tables (base relations) Relation and its tuples are actually created and stored as a file by the DBMS Virtual relations (views) Created through the CREATE VIEW statement. Do not correspond to any physical file. 8

SQL Data Types 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) 9

SQL Data Types Numeric data types Integer numbers: INTEGER(p): Precision p TINYINT: Precision 3 SMALLINT: Precision 5 MEDIUMINT: Precision 7 INTEGER, INT: Precision 10 BIGINT: Precision 19 10

SQL Data Types Numeric data types Type Storage Minimum Value Maximum Value (Bytes) (Signed/Unsigned) (Signed/Unsigned) TINYINT 1-128 127 0 255 SMALLINT 2-32768 32767 0 65535 MEDIUMINT 3-8388608 8388607 0 16777215 INT 4-2147483648 2147483647 0 4294967295 BIGINT 8-9223372036854775808 9223372036854775807 0 18446744073709551615 11

SQL Data Types Numeric data types Floating-point (real) numbers: FLOAT, mantissa precision 16 -(Approximate Value) DOUBLE, mantissa precision 16 -(Approximate Value) REAL, mantissa precision 7 -(Approximate Value) DECIMAL, mantissa precision 16 -(Exact Value) 12

SQL Data Types Numeric data types Floating-point (real) numbers: MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE(M,D). Here, (M,D) means than values can be stored with up to M digits in total, of which D digits may be after the decimal point. 13

SQL Data Types FLOAT(4,2) (a) (b) (c) 7689.23 76.89 76.8923 14

SQL Data Types Numeric data types Floating-point (real) numbers: For example, a column defined as FLOAT(7,4) will look like -999.9999 when displayed. MySQL performs rounding when storing values, so if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001. 15

SQL Data Types Boolean data type Values of TRUE or FALSE or NULL Valid examples Invalid examples TRUE 1 true yes FALSE 0 false no 16

SQL Data Types Basic data types Character-string data types Fixed length: CHAR(n), CHARACTER(n) Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER VARYING(n) 17

SQL Data Types Basic data types Character-string data types Value CHAR(4) VARCHAR(4) '' ' ' '' 'ab' 'ab ' 'ab' 'abcd' 'abcd' 'abcd' 'abcdefgh' 'abcd' 'abcd' 18

SQL Data Types Date and Time Types The date and time types for representing temporal values are DATE, TIME, DATETIME, TIMESTAMP, and YEAR. Each temporal type has a range of valid values, as well as a zero value that may be used when you specify an invalid value that SQL cannot represent. 19

SQL Data Types Date and Time Types Date parts must always be given in year-monthday order (for example, '98-09-04'), rather than in the month-day-year or day-month-year orders commonly used elsewhere (for example, '09-04-98', '04-09-98'). 20

SQL Data Types Date and Time Types Dates containing two-digit year values are ambiguous. MySQL interprets two-digit year values using these rules: Year values in the range 70-99 are converted to 1970-1999. Year values in the range 00-69 are converted to 2000-2069. 21

SQL Data Types Date and Time Types MySQL permits you to store a zero value of '0000-00-00' as a dummy date. This is in some cases more convenient than using NULL values, and uses less data and index space. To disallow '0000-00-00', enable the NO_ZERO_DATE mode. 22

SQL Data Types Date and Time Types Data Type Zero Value DATE '0000-00-00' TIME '00:00:00' DATETIME '0000-00-00 00:00:00' TIMESTAMP '0000-00-00 00:00:00' YEAR 0000 23

SQL Data Types Quiz 24

Specifying Constraints in SQL Basic constraints: Relational Model has 3 basic constraint types that are supported in SQL: Key constraint: A primary key value cannot be duplicated Entity Integrity Constraint: A primary key value cannot be null Referential integrity constraints: The foreign key must have a value that is already present as a primary key, or may be null. 25

Specifying Attribute Constraints Other Restrictions on attribute domains: Default value of an attribute DEFAULT <value> NULL is not permitted for a particular attribute NOT NULL CHECK clause Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21); 26

Specifying Key and Referential Integrity Constraints PRIMARY KEY clause Specifies one or more attributes that make up the primary key of a relation D_number INT PRIMARY KEY; UNIQUE clause Specifies alternate (secondary) keys (called CANDIDATE keys in the relational model). D_name VARCHAR(15) UNIQUE; 27

Specifying Key and Referential Integrity Constraints FOREIGN KEY clause Default operation: reject update on violation Attach referential triggered action clause Options include SET NULL, CASCADE, and SET DEFAULT Action taken by the DBMS for SET NULL or SET DEFAULT is the same for both ON DELETE and ON UPDATE CASCADE option suitable for relationship relations 28

Basic Retrieval Queries in SQL SELECT statement One basic statement for retrieving information from a database 29

The SELECT-FROM-WHERE Structure of Basic SQL Queries Basic form of the SELECT statement: 30

The SELECT-FROM-WHERE Structure of Basic SQL Queries Logical comparison operators =, <, <=, >, >=, <> Projection attributes Attributes whose values are to be retrieved Selection condition Boolean condition that must be true for any retrieved tuple. 31

Basic Retrieval Queries 32

Basic Retrieval Queries 33

Basic Retrieval Queries Retrieve employee with salary more than 3000 34

Basic Retrieval Queries (Q0) 35

Basic Retrieval Queries (Q0) 36

Basic Retrieval Queries (Q1) 37

Basic Retrieval Queries (Q1) 38

Basic Retrieval Queries (Q2) 39

Basic Retrieval Queries (Q2) 40

Ambiguous Attribute Names Same name can be used for two (or more) attributes in different relations As long as the attributes are in different relations Must qualify the attribute name with the relation name to prevent ambiguity 41

Aliasing, and Renaming Aliases or tuple variables Declare alternative relation names E and S to refer to the EMPLOYEE relation twice in a query: Query 8. For each employee, retrieve the employee s first and last name and the first and last name of his or her immediate supervisor. SELECT E.Fname, E.Lname, S.Fname, S.Lname FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.Super_ssn = S.Ssn; 42

Unspecified WHERE Clause Missing WHERE clause Indicates no condition on tuple selection Effect is a CROSS PRODUCT Result is all possible tuple combinations result 43

Use of the Asterisk Specify an asterisk (*) Retrieve all the attribute values of the selected tuples The * can be prefixed by the relation name; e.g., EMPLOYEE * 44

Tables as Sets in SQL SQL does not automatically eliminate duplicate tuples in query results For aggregate operations duplicates must be accounted for Use the keyword DISTINCT in the SELECT clause Only distinct tuples should remain in the result 45

Tables as Sets in SQL Set operations UNION, EXCEPT (difference), INTERSECT Corresponding multiset operations: UNION ALL, EXCEPT ALL, INTERSECT ALL) Type compatibility is needed for these operations to be valid 46

Tables as Sets in SQL 47

Tables as Sets in SQL 48

Substring Pattern Matching LIKE comparison operator Used for string pattern matching (%) replaces an arbitrary number of zero or more characters underscore (_) replaces a single character Examples: WHERE Address LIKE %Houston,TX% ; WHERE Ssn LIKE 1 8901 ; 49

Arithmetic Operators BETWEEN comparison operator SELECT * FROM employee WHERE(Salary BETWEEN 30000 AND 40000 ) ; 50

Arithmetic Operations Standard arithmetic operators: Addition (+), subtraction ( ), multiplication (*), and division (/) may be included as a part of SELECT Query 13. Show the resulting salaries if every employee working on the ProductX project is given a 10 percent raise. SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P WHERE E.Ssn=W.Essn AND W.Pno=P.Pnumber AND P.Pname= ProductX ; 51

Ordering of Query Results Use ORDER BY clause Keyword DESC to see result in a descending order of values Keyword ASC to specify ascending order explicitly Typically placed at the end of the query ORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC 52

Ordering of Query Results 53