Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description...

14
21/04/2017 1 Language SQL SQL Script Reference: W3School - http://www.w3schools.com/sql/default.asp SQL - Create Datadase The CREATE DATABASE statement is used to create a database. CREATE DATABASE dbname;

Transcript of Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description...

Page 1: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

1

Language SQLSQL Script

Reference: W3School - http://www.w3schools.com/sql/default.asp

SQL - Create Datadase� The CREATE DATABASE statement is used to create a database.

� CREATE DATABASE dbname;

Page 2: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

2

SQL - CREATE TABLE Statement� The SQL CREATE TABLE Statement

� The CREATE TABLE statement is used to create a table in a database.

� Tables are organized into rows and columns; and each table must have a name

� CREATE TABLE table_name(

column_name1 data_type(size),

column_name2 data_type(size),

column_name3 data_type(size)

);

SQL - DATATYPESData type Access SQLServer Oracle MySQL PostgreSQL

boolean Yes/No Bit Byte N/A Boolean

integerNumber (integer)

Int NumberIntInteger

IntInteger

floatNumber (single)

FloatReal

Number Float Numeric

currency Currency Money N/A N/A Money

string (fixed) N/A Char Char Char Char

string

(variable)

Text (<256)Memo (65k+)

VarcharVarcharVarchar2

Varchar Varchar

binary objectOLE ObjectMemo

Binary (fixed up to 8K)Varbinary(<8K)Image (<2GB)

LongRaw

BlobText

BinaryVarbinary

Page 3: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

3

MySQL Data Types - Text types

Data type Description

CHAR(size)Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters

VARCHAR(size)

Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type

TINYTEXT Holds a string with a maximum length of 255 characters

TEXT Holds a string with a maximum length of 65,535 characters

BLOBFor BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters

MySQL Data Types - Text types

Data type Description

MEDIUMBLOBFor BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data

LONGTEXTHolds a string with a maximum length of 4,294,967,295 characters

LONGBLOBFor BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data

ENUM(x,y,z,etc.)

Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted.Note: The values are sorted in the order you enter them.You enter the possible values in this format: ENUM('X','Y','Z')

SETSimilar to ENUM except that SET may contain up to 64 list items and can store more than one choice

Page 4: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

4

MySQL Data Types - Number types

Data type Description

TINYINT(size)-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis

SMALLINT(size)-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis

MEDIUMINT(size)-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis

INT(size)-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis

MySQL Data Types - Number types

Data type Description

FLOAT(size,d)

A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

DOUBLE(size,d)

A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

DECIMAL(size,d)

A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

FLOAT(size,d)

A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

Page 5: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

5

MySQL Data Types – Date Types

Data type Description

DATE()A date. Format: YYYY-MM-DDNote: The supported range is from '1000-01-01' to '9999-12-31'

DATETIME()*A date and time combination. Format: YYYY-MM-DD HH:MI:SSNote: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'

TIMESTAMP()

*A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MI:SSNote: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC

TIME()A time. Format: HH:MI:SSNote: The supported range is from '-838:59:59' to '838:59:59'

MySQL Data Types – Date Types

Data type Description

TIME()A time. Format: HH:MI:SSNote: The supported range is from '-838:59:59' to '838:59:59'

YEAR()A year in two-digit or four-digit format.Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069

Page 6: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

6

MySQL Data Types – Date Types

� MySQL comes with the following data types for storing a date or a date/time value in the database:

� DATE - format YYYY-MM-DD

� DATETIME - format: YYYY-MM-DD HH:MI:SS

� TIMESTAMP - format: YYYY-MM-DD HH:MI:SS

� YEAR - format YYYY or YY

MySQL Data Types – Date Types

Function Description

NOW() Returns the current date and time

CURDATE() Returns the current date

CURTIME() Returns the current time

DATE() Extracts the date part of a date or date/time expression

EXTRACT() Returns a single part of a date/time

DATE_ADD() Adds a specified time interval to a date

DATE_SUB() Subtracts a specified time interval from a date

DATEDIFF() Returns the number of days between two dates

DATE_FORMAT() Displays date/time data in different formats

Page 7: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

7

SQL PRIMARY KEY Constraint

� The PRIMARY KEY constraint uniquely identifies each record in a database table.

� Primary keys must contain UNIQUE values.

� A primary key column cannot contain NULL values.

� Most tables should have a primary key, and each table can have only ONE primary key

� CREATE TABLE table_name(column_PK_name1 int NOT NULL AUTO_INCREMENT,column_name2 data_type(size),column_name3 data_type(size),CONSTRAINT pk_name PRIMARY KEY (column_PK_name1))

SQL FOREIGN KEY Constraint

� A FOREIGN KEY in one table points to a PRIMARY KEY in another table

� The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

� The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.

� CREATE TABLE table_name(column_PK_name1 int NOT NULL AUTO_INCREMENT,column_name2 data_type(size),column_name3 data_type(size),CONSTRAINT pk_name PRIMARY KEY (column_PK_name1),CONSTRAINT fk_name FOREIGN KEY (column_name3)REFERENCES table_name2(column_table2))

Page 8: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

8

SQL Script - Exercise

� Write the script to create a New database with the name Building2;

� Using the Relational Diagram, write the script to create the tables

� User

� Building

� Apartment

� City

� Tenant

SQL Script - Exercise� CREATE DATABASE building2;

CREATE TABLE City (cityId Int NOT NULL AUTO_INCREMENT,cityName VARCHAR(30) NOT NULL,CONSTRAINT pk_cityId PRIMARY KEY (cityId));

CREATE TABLE Building (buildingId Int NOT NULL AUTO_INCREMENT,buildingAddress VARCHAR(45) NOT NULL,buildingZipCode VARCHAR(7) NOT NULL,buildingCityId INT,CONSTRAINT pk_buildingId PRIMARY KEY (buildingId),CONSTRAINT fk_buildingCityID FOREIGN KEY (buildingCityId) REFERENCES City(cityId));

CREATE TABLE Apartment (apartmentNumber Int NOT NULL,apartmentBuildingId Int NOT NULL,apartmentNumberRooms DOUBLE,apartmentPrice DOUBLE,CONSTRAINT pk_apartment PRIMARY KEY (apartmentNumber, apartmentBuildingId),CONSTRAINT fk_apartmentBuildingId FOREIGN KEY (apartmentBuildingId) REFERENCES Building(BuildingId));

Page 9: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

9

SQL Script - Exercise

CREATE TABLE user (userId Int NOT NULL AUTO_INCREMENT,username VARCHAR(50) NOT NULL,password VARCHAR (255) NOT NULL,name VARCHAR(45),birthday DATETIME,userCityId INT,CONSTRAINT pk_userId PRIMARY KEY (userId),CONSTRAINT fk_userCityID FOREIGN KEY (userCityId) REFERENCES city(cityId));

CREATE TABLE tenant (tenantId Int NOT NULL AUTO_INCREMENT,tenantName VARCHAR(45) NOT NULL,tenantPhone VARCHAR (20),CONSTRAINT pk_tenantId PRIMARY KEY (tenantId));

SQL UNIQUE Constraint

� The UNIQUE constraint uniquely identifies each record in a database table.

� The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.

� A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.

� CREATE TABLE table_name(column_PK_name1 int NOT NULL AUTO_INCREMENT,column_name2 data_type(size),column_name3 data_type(size),CONSTRAINT pk_name PRIMARY KEY (column_PK_name1),CONSTRAINT unique_name UNIQUE (column_name2))

Page 10: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

10

SQL DEFAULT Constraint

� The DEFAULT constraint is used to insert a default value into a column.

� The default value will be added to all new records, if no other value is specified

� CREATE TABLE table_name(column_PK_name1 int NOT NULL AUTO_INCREMENT,column_name2 data_type(size) DEFAULT ‘TEST',column_name3 data_type(size),CONSTRAINT pk_name PRIMARY KEY (column_PK_name1));

� The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():

� column_name2 date DEFAULT GETDATE();

The ALTER TABLE Statement

� The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

� ALTER TABLE table_nameADD column_name datatype;

� ALTER TABLE table_nameDROP COLUMN column_name;

SQL Server / MS Access

� ALTER TABLE table_nameMODIFY COLUMN column_name column_name datatype

Or My SQL / Oracle (prior version 10G)

� ALTER TABLE table_nameCHANGE COLUMN column_name column_name datatype

Page 11: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

11

The ALTER TABLE Statement

� PRIMARY KEY

� ALTER TABLE table_nameADD CONSTRAINT pk_name PRIMARY KEY (column_name);

� ALTER TABLE table_nameDROP PRIMARY KEY;

� FOREIGN KEY

� ALTER TABLE table_nameADD CONSTRAINT fk_nameFOREIGN KEY (column_name) REFERENCES table_name2 (column_name2);

� ALTER TABLE OrdersDROP FOREIGN KEY fk_name;

SQL DEFAULT Constraint

� DEFAULT

� ALTER TABLE table_nameALTER column_name SET DEFAULT ‘TEST‘;

� ALTER TABLE table_nameALTER column_name DROP DEFAULT

� UNIQUE

� ALTER TABLE table_nameADD CONSTRAINT uc_name UNIQUE (column_name)

� ALTER TABLE table_nameDROP INDEX uc_name

Page 12: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

12

SQL DROP TABLE, TRUNCATE TABLE And DROP DATABASE

� The DROP TABLE statement is used to delete a table.

� DROP TABLE table_name;

� The DROP DATABASE statement is used to delete a database.

� DROP DATABASE database_name;

� The TRUNCATE TABLE statement is used to delete the data inside the table, and not the table itself.

� TRUNCATE TABLE table_name;

SQL Script - Exercise

1. Add a Default (01-01-1980) date for the column Birthday at the table User;

2. Insert 3 new users into the table user;

3. Empty the table user;

4. Insert 3 news cities at the table city;

5. Delete the foreign key city from the table user and building;

6. Empty the table city;

7. Add again the foreign key city to the tables user and building;

8. The filed username at the table user should be unique;

Page 13: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

13

Exercises1. ALTER TABLE user CHANGE COLUMN birthday birthday DATETIME DEFAULT

'1980-01-01‘;

2. INSERT INTO city (cityName) VALUES (‘Montreal');

INSERT INTO user (username, password, name, birthday, userCityId) VALUES ('[email protected]', 'test', 'Paul', '2000-01-01', '1');INSERT INTO user (username, password, name, birthday, userCityId) VALUES ('[email protected]', 'test', 'Simon', '2000-01-01', ‘1');INSERT INTO user (username, password, name, birthday, userCityId) VALUES ('[email protected]', 'test', 'Peter', '2000-01-01', '1');

3. TRUNCATE TABLE user;

4. INSERT INTO city (cityName) VALUES (‘Quebec'); INSERT INTO city (cityName) VALUES ('Laval');INSERT INTO city (cityName) VALUES ('Trois Rivière');

Exercises5. ALTER TABLE userDROP FOREIGN KEY fk_userCityID;

ALTER TABLE buildingDROP FOREIGN KEY fk_buildingCityID;

6. TRUNCATE TABLE city;

7. ALTER TABLE buildingADD CONSTRAINT fk_buildingCityID FOREIGN KEY (buildingCityId) REFERENCES City(cityId);

ALTER TABLE userADD CONSTRAINT fk_userCityID FOREIGN KEY (userCityId) REFERENCES city(cityId);

8. ALTER TABLE userADD CONSTRAINT un_username UNIQUE (username);

Page 14: Language SQL - markitosanches.com · 21/04/2017 3 MySQL Data Types-Texttypes Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special

21/04/2017

14