MySQL: an application

Similar documents
Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

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

Data and Tables. Bok, Jong Soon

More MySQL ELEVEN Walkthrough examples Walkthrough 1: Bulk loading SESSION

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

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

Intro. Scheme Basics. scm> 5 5. scm>

SQL. Often times, in order for us to build the most functional website we can, we depend on a database to store information.

The M in LAMP: MySQL CSCI 470: Web Science Keith Vertanen Copyright 2014

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

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Text Input and Conditionals

Chapter 8 How to work with data types

Chapter 3 Introduction to relational databases and MySQL

MySQL Creating a Database Lecture 3

Shorthand for values: variables

More about Binary 9/6/2016

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

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

QUIZ. What is wrong with this code that uses default arguments?

The C++ Language. Arizona State University 1

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Basis Data Terapan. Yoannita

SQL: Data Definition Language

Basic SQL. Basic SQL. Basic SQL

Data Definition Language with mysql. By Kautsar

Programming and Database Fundamentals for Data Scientists

Week 3 Lecture 2. Types Constants and Variables

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

CIS 363 MySQL. Chapter 4 MySQL Connectors Chapter 5 Data Types Chapter 6 Identifiers

If Statements, For Loops, Functions

LOOPS. Repetition using the while statement

Getting started with Java

Should you know scanf and printf?

LBSC 690: Information Technology Lecture 05 Structured data and databases

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

Draft. Students Table. FName LName StudentID College Year. Justin Ennen Science Senior. Dan Bass Management Junior

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

The Top 20 Design Tips

ALTER TABLE Improvements in MARIADB Server. Marko Mäkelä Lead Developer InnoDB MariaDB Corporation

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Programming with Python

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

SQL stands for Structured Query Language. SQL is the lingua franca

Chapter 1 Getting Started

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Exact Numeric Data Types

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

How to Use JSON in MySQL Wrong

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

MySQL Workshop. Scott D. Anderson

You just told Matlab to create two strings of letters 'I have no idea what I m doing' and to name those strings str1 and str2.

Access Intermediate

PART I SQLAlchemy Core

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

Exercise: Inventing Language

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Creating the Data Layer

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

MIS2502: Data Analytics MySQL and SQL Workbench. Jing Gong

T H E I N T E R A C T I V E S H E L L

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

Lecture 5: SQL s Data Definition Language

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

MTAT Introduction to Databases

There are functions to handle strings, so we will see the notion of functions itself in little a detail later. (Refer Slide Time: 00:12)

Introduction to Java Unit 1. Using BlueJ to Write Programs

Variables, expressions and statements

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Control Structures in Java if-else and switch

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

user specifies what is wanted, not how to find it

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

Program Fundamentals

1.7 Limit of a Function

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Senturus Analytics Connector. User Guide Cognos to Power BI Senturus, Inc. Page 1

(Refer Slide Time: 00:23)

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

Tool/Web URL Features phpmyadmin. More on phpmyadmin under User Intefaces. MySQL Query Browser

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

MariaDB ColumnStore Python API Usage Documentation

Project Database Rules

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

Table of Contents Date(s) Title/Topic Page #s. Abstraction

Variables and Data Representation

The Big Python Guide

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

QUIZ. What are 3 differences between C and C++ const variables?

Variables and numeric types

Data Storage and Query Answering. Data Storage and Disk Structure (4)

Lab 4. Out: Friday, February 25th, 2005

Maciej Sobieraj. Lecture 1

Transcription:

Data Types and other stuff you should know in order to amaze and dazzle your friends at parties after you finally give up that dream of being a magician and stop making ridiculous balloon animals and begin to do something productive instead

MySQL: an application Just like you use Word to produce documents...... you use MySQL to produce databases.

MySQL: an application MySQL is a command-line tool. Only people having administrative privileges can create new databases. On your laptop, that s you. Your new database will be a completely empty shell no tables, no data, nothing. You ll need to define everything from that point onwards.

Creating a Database (step 1) CREATE DATABASE database_name DEFAULT CHARSET utf8; is command builds a new, empty database. We ve defined the default character set of the database as 8-bit Unicode, which is the new standard for cross-platform, internationalized text. From here on, any new table will automatically inherit the Unicode character set and we won t have to worry about it again. Check out Unicode here: http://unicode.org/

Creating a Database (step 2) USE database_name; is command tells MySQL that any new tables created should belong to the new database. is is the equivalent in a word processor of doing File > New... a new document is created and your word processor begins using it. Any text you type will belong to that new document.

Defining Tables & Columns id first last email phone 1 Bob Jones jonesy@ blah.ca 555-1234 When I create my table, I need to tell MySQL which columns I want the table to have: CREATE TABLE member ( id, first, last, email, phone ); But I need to give MySQL very specific information about what kinds of data go into these columns, so I ll have to learn something about data types.

Defining Tables & Columns id first last email phone 1 Bob Jones jonesy@ blah.ca 555-1234 This looks suspiciously like a number. These look suspiciously like sequences of letters. And I m not quite sure what this would be.

Numbers vs. Characters If I perform the selection in MySQL, I get the following... : mysql> SELECT 555-1234; +----------+ 555-1234 +----------+ -679 +----------+ 1 row in set (0.02 sec)... which teaches me several things: 1) I can use MySQL as a calculator; 2) A phone number looks like a number, but it isn t. It s really an ordered sequence of characters that cannot be reduced or simplified, more commonly called a string.

MySQL Data Types Numbers Text Date / Time Complex NULL We need to tell MySQL whether it has a decimal point or not and how big the number might be. We need to tell MySQL either how many characters it might contain or just to treat it as a big chunk of text. We need to tell MySQL whether it s a date, a time, both, or just a part (like a year). Typically lists of some kind; we need to tell MySQL whether one or multiple values of the list will be stored. Not a value, but the absence of a value.

MySQL Data Types Numeric String Date / Time Complex NULL integer # s without decimals: (tinyint, smallint, mediumint, int, bigint); float (float, double, decimal) char, text and blob in various sizes (tiny, medium, long); varchar variable character (most common) date, datetime, time, timestamp, year enum (field value is one of a specific list); set (field values can be multiple values from a specific list) Not a value, but the absence of a value.

Signed -300-200 -100 0 100 200 300 Unsigned -300-200 -100 0 100 200 300

MySQL Numeric Column Types tinyint smallint mediumint int bigint float double decimal signed: -128 to 127 unsigned: 0 to 255 signed: -32768 to 32767 unsigned: 0 to 65535 signed: -8388608 to 8388607 unsigned: 0 to 16777215 signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 signed: ± 9223372036854775808 unsigned: 0 to 18446744073709551615 can optionally specify bits of precision (default: 4 bytes single; 8 bytes double) 8 bytes number stored as a string; specify display width and number of decimals.

Counting Characters Character string columns are defined by specifying the maximum number of characters to be contained in the column. For example, if I know this is my longest string... : Edmonton, Alberta 1 5 10 15 17... then I know that I can specify 17 characters maximum for the column (note that I have to count spaces and punctuation too!). A definition of char(17) would suffice. I might have shorter strings, though, and so I can tell MySQL to compress space by defining the column as variable character: varchar(17).

Defining Tables & Columns id first last email phone 1 Bob Jones jonesy@ blah.ca 555-1234 This is an integer that will never be larger than 250. These are varying-length strings. I estimate the longest will be 35 characters. This is a string whose longest entry will be 12 characters.

Primary Keys A primary key is a special designation that describes how each row of the table will be uniquely identified. A primary key can contain one or more columns. Moreover: Primary keys must have unique values for each row. Primary keys must have a non-null value for the entire lifetime of that record. A primary key s value must never change during the lifetime of that record. I can have MySQL help me here. I can, for example: Define an integer column (unsigned may help) Force it to be NOT NULL Tell MySQL to make it auto_increment

Define a Table Now I m ready to define my member table. I need to tell MySQL the name of the table, plus the names and precise definitions of all the columns: CREATE TABLE member ( id tinyint unsigned NOT NULL auto_increment PRIMARY KEY, first varchar(25), last varchar(25), email varchar(35), phone varchar(12) ); The id field is a TINYINT, and it s unsigned, so it can store a number from 0 to 255.

Define a Table Now I m ready to define my member table. I need to tell MySQL the name of the table, plus the names and precise definitions of all the columns: CREATE TABLE member ( id tinyint unsigned NOT NULL auto_increment PRIMARY KEY, first varchar(25), last varchar(25), email varchar(35), phone varchar(12) ); The id field is a TINYINT, and it s unsigned, so it can store a number from 0 to 255. It s also the primary key, and I ve established all the necessary criteria.

Define a Table Now I m ready to define my member table. I need to tell MySQL the name of the table, plus the names and precise definitions of all the columns: CREATE TABLE member ( id tinyint unsigned NOT NULL auto_increment PRIMARY KEY, first varchar(25), last varchar(25), email varchar(35), phone varchar(12) ); The id field is a TINYINT, and it s unsigned, so it can store a number from 0 to 255. It s also the primary key, and I ve established all the necessary criteria. My other fields are varchars, ranging from 12 to 35 characters long.

More Table Definitions Here s my sighting table. Note that two of these fields are foreign keys that is, person and bird contain values that are primary keys in their original tables, but here they are simply references to records in those tables. MySQL has support for foreign keys, but we ll simplify this for now. person bird date 1 1 2011-09-28 Foreign keys! I ll define them with the same qualities they have in their original tables. A date. I ll just use the date data type.

More Table Definitions person bird date 1 1 2011-09-28 CREATE TABLE sighting ( person tinyint unsigned NOT NULL, bird tinyint unsigned NOT NULL, date date ); Foreign keys; make them unsigned tinyint s same as the other table.

More Table Definitions person bird date 1 1 2011-09-28 CREATE TABLE sighting ( person tinyint unsigned NOT NULL, bird tinyint unsigned NOT NULL, date date ); Foreign keys; make them unsigned tinyint s same as the other table. It would make no sense to have no person or no bird in a sighting record, so I ll have MySQL help me here.

More Table Definitions person bird date 1 1 2011-09-28 CREATE TABLE sighting ( person tinyint unsigned NOT NULL, bird tinyint unsigned NOT NULL, date date ); Foreign keys; make them unsigned tinyint s same as the other table. Just a regular date column. I ve decided not to store the time. It would make no sense to have no person or no bird in a sighting record, so I ll have MySQL help me here.

INSERT revisited

Insert Redux Technique 1 As we ve seen, INSERT creates a brand new row in the table and fills the columns with the data you provide. The more you know about your data types, the more prepared you ll be to make sure INSERT works properly. The general technique is first to list the columns into which the data goes, and then list the data: INSERT INTO sighting (person, bird, date) VALUES (1, 2, 2011-09-30 ); Notice that: 1. I need to list the table into which the data will be inserted. 2. I need to put quotation marks around any string value: 2011-09-30 3. I do not need to put quotation marks around numbers. 4. Both the column list and the values list go inside parentheses: ( ) 5. The data order matches the column order as listed here.

Insert Redux Technique 1 However, as long as I list the columns and as long as I list my data values correspondingly, I can insert values in any order I wish. I do not need to follow the column order of the table itself. For example: mysql> INSERT INTO sighting (bird, date, person) VALUES (2, '2011-10-10', 4); Query OK, 1 row affected (0.00 sec) But if I make a mistake in either my column count or my data count, MySQL will generate an error and will not insert data: mysql> INSERT INTO sighting (person, bird, date) VALUES (1); ERROR 1136: Column count doesn't match value count at row 1 Using this technique, I can even skip certain columns if I want. In that case, those columns will either contain a default value (if I defined one in my CREATE TABLE statement) or else they will contain NULL.

Insert Redux Technique 2 Here s another technique. If you re feeling really bold, you can omit the column list. Notice, though, that I need to have a piece of data for each column and they need to be specified in the same order as in the table: INSERT INTO sightings VALUES (1, 2, 2011-09-30 ); If I get the number of data items wrong, I ll get an error: mysql> INSERT INTO sighting VALUES (1, 3); ERROR 1136: Column count doesn't match value count at row 1 And if I get the columns wrong without specifying them, I have a total mess: mysql> INSERT INTO sighting VALUES ('2011-09-28', 1, 3); Because that query actually inserts these values: 255, 1, 2000-00-03

Insert Redux Technique 2 Why would this query... INSERT INTO sighting VALUES ('2011-09-28', 1, 3);... inserted into this table... CREATE TABLE sighting ( person tinyint unsigned NOT NULL, bird tinyint unsigned NOT NULL, date date );... produce these values? 255, 1, 2000-00-03 The string gets converted to a number but maxes out the tinyint at 255, 1 goes in untouched, and 3 gets interpreted as year 0, month 0, day 3.

Zero-Filled Dates Missing dates are often the bane of a database person s life. As we ve seen, MySQL uses a standardized date of this format: YYYY-MM-DD However, if one or more of those parts are missing, you are allowed to fill them with zeroes. MySQL considers even the bizarre-looking date 0000-00-00 to be legal. So, for example: 0000-09-04 September 4th of an unknown year 2012-06-00 Sometime in June 2012 2009-00-23 The 23rd of an unknown month in 2009 NB: This is not a standard practice in the XML community, so if you re moving documents into a database, you might need to make some decisions about how your project should handle missing dates.

Inserting Primary Keys Remember how we defined our primary key in the member table? id tinyint unsigned NOT NULL auto_increment PRIMARY KEY, That says the column is an unsigned integer that gets automatically incremented every time a new row gets inserted. Technically, then, I don t want to insert any value at all into the id field I want to let MySQL handle it for me: INSERT INTO member (id, first, last) VALUES (NULL, Deb, Jones ); Since, by definition, the column cannot be NULL, MySQL will calculate the next auto_increment number, and insert that value into the field. I don t need to do any work. (Caution: not all primary keys are defined as auto_increment integers, so inserting NULL into a primary key field isn t an automatic answer! But when it works, it s coool.)

Inserting Primary Keys INSERT INTO member (id, first, last) VALUES (NULL, Deb, Jones ); MySQL will find the latest ID inserted, add one, and use that number for the new record s primary key, which you can discover with the last_insert_id() function: mysql> select last_insert_id(); +------------------+ last_insert_id() +------------------+ 10 +------------------+ 1 row in set (0.22 sec)

Inserting Strings w/ Quotes In a query, every string value needs to be surrounded by quotation marks. But that means a string that itself has a quotation mark or an apostrophe presents a problem. Inserting this string, for example... I don t like peas.... will generate this bizarre behaviour: mysql> INSERT INTO delme VALUES ('I don't like peas.'); '> I need to type a closing quotation mark and then can cancel my query with \c: mysql> INSERT INTO delme VALUES ('I don't like peas.'); '> '\c mysql>

Inserting Strings w/ Quotes In a query, every string value needs to be surrounded by quotation marks. But that means a string that itself has a quotation mark or an apostrophe presents a problem. Inserting this string, There for example are 3 quotation... marks; MySQL is waiting for a fourth. I don t like peas. It thinks there s an... will generate this bizarre behaviour: unterminated string value. mysql> INSERT INTO delme VALUES ('I don't like peas.'); '> I need to type a closing quotation mark and then can cancel my query with \c: mysql> INSERT INTO delme VALUES ('I don't like peas.'); '> '\c mysql>

Inserting Strings w/ Quotes I have two options available to me when inserting a string containing apostrophes or quotations: 1. Wrap the string in double quotation marks: mysql> INSERT INTO delme VALUES ( I don't like peas. ); 2. Escape the single quotation mark by putting a slash before it. That tells MySQL that the quotation mark does not end the string: mysql> INSERT INTO delme VALUES ('I don\'t like peas.'); Either one is acceptable. You ll see both quite often in your database career.

Inserting Default Values Let s say I define a table this way: CREATE TABLE delme ( num int default 7, str varchar(10) default "yoip!" ); num str default: 7 default: yoip! What happens when I start to insert values?

Inserting Default Values First insert: INSERT INTO delme VALUES (1, crikey! ); num str 1 crikey!

Inserting Default Values Second insert: INSERT INTO delme (num) VALUES (2); num str 1 crikey! 2 yoip! Column value unspecified; gets default value yoip!

Inserting Default Values Third insert: INSERT INTO delme (str) VALUES ( Hello! ); num str 1 crikey! 2 yoip! 7 Hello! Column value unspecified; gets default value 7

Example of a Default Value id first last email phone guide insert into delme (str) values ( Hello! ); 1 Bob Jones jonesy@ blah.ca 555-1234 no CREATE TABLE member ( id tinyint unsigned NOT NULL auto_increment PRIMARY KEY, first varchar(25), last varchar(25), email varchar(35), phone varchar(12), guide varchar(3) default no );

Define Your Tables Using your database designs, begin defining the data types of the columns. When you re ready, create a new database on your laptop (CREATE DATABASE) and then begin creating the tables (CREATE TABLE).