Lecture 5: SQL s Data Definition Language

Similar documents
Data Definition and Data Manipulation. Lecture 5: SQL s Data Definition Language CS1106/CS5021/CS6503 Introduction to Relational Databases

Lecture 7: Two-Table Queries

Lecture 1: Relational Databases

Lecture 3: More SQL Basics CS1106/CS5021/CS6503 Introduction to Relational Databases. Single-Criterion WHERE Conditions. SQL Conditions.

Lecture 2: SQL Basics

Lecture 2: SQL Basics CS1106/CS5021/CS6503 Introduction to Relational Databases. Brief Note on Naming Conventions. Our Running Example.

Lecture 3: More SQL Basics

Lecture 4: SQL Data Manipulation Basics

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

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

SQL: Data Definition Language

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

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

SQL DATA DEFINITION LANGUAGE

SQL DATA DEFINITION LANGUAGE

Basic SQL. Basic SQL. Basic SQL

Data Types in MySQL CSCU9Q5. MySQL. Data Types. Consequences of Data Types. Common Data Types. Storage size Character String Date and Time.

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

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

More MySQL ELEVEN Walkthrough examples Walkthrough 1: Bulk loading SESSION

SQL DATA DEFINITION LANGUAGE

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

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

user specifies what is wanted, not how to find it

CS143: Relational Model

INFORMATION TECHNOLOGY NOTES

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

Lab # 2 Hands-On. DDL Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia

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

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

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

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

Lecture 2: Python Arithmetic

Chapter 3 Introduction to relational databases and MySQL

Programming and Database Fundamentals for Data Scientists

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

Full file at

This lab will introduce you to MySQL. Begin by logging into the class web server via SSH Secure Shell Client

Data Base Concepts. Course Guide 2

MTAT Introduction to Databases

Full file at

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

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

MySQL Creating a Database Lecture 3

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

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

Principles of Data Management

Chapter 9: Working with MySQL

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

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

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

Chapter 03: Computer Arithmetic. Lesson 09: Arithmetic using floating point numbers

SQL: DDL. John Ortiz Cs.utsa.edu

Lab # 4. Data Definition Language (DDL)

MySQL: an application

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

CSE 530A. Inheritance and Partitioning. Washington University Fall 2013

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 2

The Relational Model of Data (ii)

In This Lecture. SQL Data Definition SQL SQL. Non-Procedural Programming. Notes. Database Systems Lecture 5 Natasha Alechina

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

Lecture 07. Spring 2018 Borough of Manhattan Community College

Introduction to SQL Part 1 By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

CS 4604: Introduc0on to Database Management Systems. B. Aditya Prakash Lecture #4: SQL---Part 2

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

Information Systems for Engineers Fall Data Definition with SQL

UFCEKG 20 2 : Data, Schemas and Applications

An Introduction to Structured Query Language

An Introduction to Structured Query Language

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

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

Lecture 0: Overview of cs1106/cs6503

SQL (Structured Query Language)

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

Physical Design of Relational Databases

An Introduction to Structured Query Language

CSCC43H: Introduction to Databases. Lecture 4

Slides by: Ms. Shree Jaswal

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

The Top 20 Design Tips

An Introduction to Structured Query Language

An Introduction to Structured Query Language

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

Database Systems CSE 303. Lecture 02

Database Systems CSE 303. Lecture 02

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

Exam code: Exam name: Database Fundamentals. Version 16.0

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

CSIE30600 Database Systems Basic SQL 2. Outline

Basis Data Terapan. Yoannita

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

CS2300: File Structures and Introduction to Database Systems

Simple Quesries in SQL & Table Creation and Data Manipulation

COMP 430 Intro. to Database Systems

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Deepak Bhinde PGT Comp. Sc.

The Relational Model. Outline. Why Study the Relational Model? Faloutsos SCS object-relational model

Unit 7: Database Development (Basic)

SQL DDL. Intro SQL CREATE TABLE ALTER TABLE Data types Service-based database in Visual Studio Database in PHPMyAdmin

Transcription:

Lecture 5: SQL s Data Definition Language CS1106/CS5021/CS6503 Introduction to Relational Databases Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 1 / 1

Data Definition and Data Manipulation So far we ve looked at SQL s data manipulation language (DML) Extract information from table Manipulate table by adding/removing rows of changing values How to we specify and create a table in the first place? SQL s also includes a data definition language (DDL) that allows us to Specify the structure of your database s table(s) Create a table with this structure KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 2 / 1

A Table Definition for Our Running Example CREATE TABLE students ( id number CHAR(9), first name VARCHAR(20), last name VARCHAR(30), date of birth DATE, hometown VARCHAR(30), course CHAR(5), points INTEGER,... ); Creates table named students with specified structure Structure specified as list of attribute names and associated types judgement required in choosing appropriate types (and lengths) (Health warning: Above could be improved!) KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 3 / 1

Overview of SQL s Data Types Remember that databases are used in a huge variety of applications to house very diverse types of data SQL provides a range of different data types with which to populate our tables Textual Strings of characters Numerical Numbers both integers and real Temporal Dates, times, date-time timestamps Others Also other types: BLOB (Binary Large Object) Most DBMSs support many flavours; often system dependent KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 4 / 1

Integer Types For integer (whole) numbers we use INTEGER (or INT) e.g. num points INTEGER Range of allowed values (MySQL 1 ) 2, 147, 483, 468 2, 147, 483, 467 MySQL should be good enough for most purposes. Most systems offer variants (SMALLINT, BIGINT) with different ranges; require different amount of space; need to choose carefully 1 Limits typically DBMS specific. KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 5 / 1

Other Numerical Types DECIMAL(n, d) any n-digit number with a d-digit mantissa FLOAT temperature DECIMAL(4, 1) 123.4 ok; 12.34 rounded to 12.3; 1234.5 error scientific notation (e.g. 1.34E+12 for 1.34 10 +12 ) Useful for scientific data system-dependent limits on number size KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 6 / 1

Temporal Types DATE Dates in YYYY-MM-DD format TIME Time (24-hour clock) in hh:mm:ss format Others e.g. DATETIME MySQL NOTES DBMSs support useful functions for manipulating dates and times e.g. MONTH(.), DATE ADD(.,.) MySQL KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 7 / 1

Textual Types CHAR(n) Shortish, fixed-length strings Space for exactly n characters allocated shorter strings right-padded with blanks, longer ones truncated Useful for id numbers, course codes etc. VARCHAR(n) Strings of any any length up to max of n characters May be more space-efficient than CHAR Useful where precise string length not fixed or known in advance, e.g. addresses Note Both draw individual characters from underlying character set latin1 swedish ci by default in our case KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 8 / 1

Textual Types cont d Need to be careful in choosing appropriate size n too large: wasteful of space (CHAR) n too small: String may be truncated if assigned to a CHAR(n)/VARCHAR(n) column of insufficient size i.e only first n characters retained KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 9 / 1

Meanwhile Back At The Example CREATE TABLE students ( id number CHAR(9), first name VARCHAR(20), last name VARCHAR(30), date of birth DATE, hometown VARCHAR(30), course CHAR(5), points INTEGER,... ); Should only execute CREATE once when table is first set up Can also specify other useful information within CREATE statement: Information about DB keys, Default values for columns, Constraints on values. Will look at this later. KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 10 / 1

Other Structure-Altering SQL Commands To expunge a table: DROP TABLE X; DROP TABLE IF EXISTS Y; Careful deletes table and contents Altering table structure Adding an attribute/column: ALTER TABLE students ADD gender CHAR(1); Deleting an attribute/column: ALTER TABLE students DROP hometown; If you design your DB properly, you should rarely need these KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 11 / 1

Keys students id number first name last name date of birth hometown course points 112345678 Aoife Ahern 1993-01-25 Cork ck401 500 112467389 Barry Barry 1980-06-30 Tralee ck402 450 112356489 Ciara Callaghan 1993-03-14 Limerick ck401 425 112986347 Declan Duffy 1993-11-03 Cork ck407 550 112561728 Eimear Early 1993-07-18 Thurles ck406 475 112836467 Fionn Fitzgerald 1994-06-13 Bandon ck405 485 Each table should have one or more attributes (collectively known as the key) the values of which uniquely identify each row i.e. no two rows should have the same key Example: id number plays this role in students Table definition should specify key as shown CREATE TABLE students (... PRIMARY KEY (id number) ) Yes, there are also non-primary keys; more on this later KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 12 / 1

Simple Possible Refinements MySQL Table Specification CREATE TABLE guests ( id number INTEGER AUTO INCREMENT, new rows automatically issued fresh id use with primary key column only name VARCHAR(20) NOT NULL, inserting/setting NULL will trigger error nationality VARCHAR(20) DEFAULT Irish all guests Irish unless specified otehrwise ); PRIMARY KEY (id number) KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 13 / 1

Simple Possible Refinements MySQL Table Specification CREATE TABLE guests ( id number INTEGER AUTO INCREMENT, new rows automatically issued fresh id use with primary key column only name VARCHAR(20) NOT NULL, inserting/setting NULL will trigger error nationality VARCHAR(20) DEFAULT Irish all guests Irish unless specified otehrwise ); PRIMARY KEY (id number) Some Insertions INSERT INTO guests (name, nationality) VALUES ( Paddy, Irish ), ( Gunther, German ), ( Luigi, Italian ); INSERT INTO guests (name) VALUES ( Seamus ); INSERT INTO guests (name, nationality) VALUES (NULL, Irish ); ERROR!!! KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 13 / 1

Creating and Populating A Database cs1106 website houses two files used to create clones of students DB in your accounts students setup.sql: file containing CREATE statement students populate.sql: file containing a bunch of INSERT statements MySQL can process SQL commands taken from a file not just those type in; in HeidiSQL use the folder icon to the right of the blue execution button We will provide files for most of the sample DBs we use in this module KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 14 / 1

An Example A Simple Database Suppose we want to design a DB to hold information about some people Information about each person: Name Birth date Address Favourite foods KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 15 / 1

An Example A Simple Database Suppose we want to design a DB to hold information about some people Information about each person: Name Birth date Address Favourite foods First stab at a DB design: Column Type name VARCHAR(?) gender CHAR(1) birth date DATE address VARCHAR(?) favourite foods????? KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 15 / 1

An Example A Simple Database Suppose we want to design a DB to hold information about some people Information about each person: First stab at a DB design: Column Type Name name VARCHAR(?) Birth date gender CHAR(1) Address birth date DATE Favourite foods address VARCHAR(?) favourite foods????? Some imperfections with this Best to have unique label for each person in case of duplicate names; introduce ID numbers Names are really composite objects; split into first and last names; same with addresses Need to choose sensible values for VARCHAR widths KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 15 / 1

An Example A Second Stab Column Type person id CHAR(6) first name VARCHAR(20) last name VARCHAR(20) gender CHAR(1) birth date DATE street VARCHAR(30) town VARCHAR(30) county VARCHAR(30) favourite foods????? What to do about favourite foods? VARCHAR difficult to access individual food items Separate columns (fav1, fav2,..), but how many? Better to use second separate table to capture this relationship (persons to food types) KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 16 / 1

An Example The favourite foods Table persons person id first name last name...... 112356489 Ciara Callaghan 112986347 Declan Duffy..... favourite foods person id food.. 112356489 Ice cream 112356489 Chocolate 112986347 Pizza 112986347 Beer 112986347 Crisps This models the fact that person 112986347 (aka Declan Duffy) likes pizza, beer and crisps The link between the two tables is the person id; within the favourite foods table the person id is a foreign key that references the persons table... KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 17 / 1

An Example Our Complete Design CREATE TABLE persons ( person id CHAR(6), first name VARCHAR(20), last name VARCHAR(20), gender CHAR(1), birth date DATE, street VARCHAR(30), town VARCHAR(30), county VARCHAR(30), CREATE TABLE favourite foods ( person id CHAR(6), food VARCHAR(20), PRIMARY KEY (person id, food) ); Note: two-attribute key ); PRIMARY KEY (person id) MySQL enforces key-distinctness property for tables, e.g. disallow insertion of duplicate person id values into persons KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 18 / 1

An Example Working With Our New DB Can pose queries at either table using SQL tools we ve learnt SELECT FROM persons WHERE first name = Ciara ; SELECT FROM favourite foods WHERE person id = 112986347 ; What about queries like the following? List names of all persons who like pizza KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 19 / 1

An Example What We Have Covered So Far Setting up a simple database (CREATE) Adding content to the database (INSERT, UPDATE) Posing (simple) queries to extract information from database KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 20 / 1

An Example Notes and Acknowledgements The favourite foods example is taken from Learning SQL by Alan Beaulieu (O Reilly, 2009). If you are looking for a nice, compact and affordable introduction to SQL, this is a good choice. KH (29/09/17) Lecture 5: SQL s Data Definition Language 2017-2018 21 / 1