chapter 1: databases - massachusetts college of liberal artsjedi.cs.mcla.edu/csci 243 database...

102
Database Development CSCI 243 1

Upload: trinhliem

Post on 07-Mar-2018

217 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Database Development

CSCI 243

1

Page 2: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

ContentsChapter 1: Databases......................................................................................................3

Database......................................................................................................................3Database Management System (DMS, or DBMS).......................................................3Database Server (DS)..................................................................................................3Structured Query Language (SQL)...............................................................................4Assignment 1................................................................................................................4

Chapter 2: Installing a Database Management System..................................................6Assignment 2................................................................................................................7Assignment 2 Part I (80 points)....................................................................................7Assignment 2 Part II.....................................................................................................9

Chapter 3: Creating a Table...........................................................................................10Creating a simple database........................................................................................10Some SQL Data Types...............................................................................................11SQL Commands: CREATE, USE, SHOW, and DESCRIBE.......................................12Example assignment and solution:.............................................................................15Assignment 3..............................................................................................................16

Chapter 4: Advanced table creation, and ERDs............................................................17Section 1 – Data types...............................................................................................17

Bit Types.................................................................................................................17Integer Types..........................................................................................................17Floating Point Types...............................................................................................18Character and String Types....................................................................................19Enumerations..........................................................................................................20Dates and Times.....................................................................................................21

Section 2 – Optional CREATE Constraints.................................................................22Section 3 – ERDs (Entity Relationship Diagrams)......................................................26Assignment 4..............................................................................................................27Summary 1.................................................................................................................28

Chapter 5: Adding and Retrieving Data........................................................................29Section 1 – Adding a Record, or Row.........................................................................29

Entering a complete row.........................................................................................30Entering a partial row..............................................................................................30

2

Page 3: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Section 2 – Retrieving Data........................................................................................32Assignment 5..............................................................................................................33

Chapter 6: Adding and Retrieving Data Continued......................................................35WHERE Clauses........................................................................................................39The LIKE Operator.....................................................................................................42Using the WHERE Clause with DELETE....................................................................43Assignment Example:.................................................................................................44Example Solution:.......................................................................................................45Assignment 6..............................................................................................................46

Chapter 7: Retrieving Data Continued, Changing a Record, and Changing a Table Structure.........................................................................................................................47

Section I: Fancy Retrieval..........................................................................................48The AND Operator..................................................................................................50The OR Operator....................................................................................................51Order Of Operations...............................................................................................51The NOT Operator..................................................................................................51ORDER BY.............................................................................................................52LIMIT.......................................................................................................................53

Section II: Changing a Record (UPDATE).................................................................53Section III: Changing a Table (ALTER).....................................................................53

CHANGE.................................................................................................................54MODIFY..................................................................................................................54ADD........................................................................................................................54DROP......................................................................................................................54

Assignment 7..............................................................................................................56Chapter 8: Multiple Tables............................................................................................58

Section I: A New Design............................................................................................58Section II: Entity or Attribute......................................................................................60Section III: Creating a Database with Multiple Tables...............................................63Assignment 8..............................................................................................................65

Chapter 9: Complex Relationships...............................................................................67Section I: A more realistic database..........................................................................67Creating a many-to-many relationship using a connecting table................................69Section II: Final Exam................................................................................................71

3

Page 4: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

4

Page 5: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Chapter 1: DatabasesThere is no additional textbook required for this course. However, there are many great books that explain databases and SQL. Feel free to buy one. Choose one that suits your learning style. I like books, and I own several database/SQL texts. I like the feel of paper, and I like to keep my finger in one page while I jump to another chapter. I’m old. Some of you might prefer to scroll while you read. That’s totally cool too. You can find good information at Wikipedia, W3Schools, and elsewhere on the Web. Please start by reading what I send you.

DatabaseA database holds information. Information could be kept in a text file, or a spreadsheet, or it could be stored by software specifically designed to optimize storage and searches. In any event, a database refers to some files that store information.

https://en.wikipedia.org/wiki/Database“A database is an organized collection of data.”

Database Management System (DMS, or DBMS)This is software that stores information, allows you to add information, allows you to change information, and allows you to retrieve information. A DMS manages the data files, and includes software that stores, changes, and retrieves data very efficiently. The main DMS products available today are Oracle, Microsoft Access, and MySQL.

https://en.wikipedia.org/wiki/Category:Database_management_systems“A database management system (DBMS) is a computer program (or more typically, a suite of them) designed to manage a database.”

Database Server (DS)This is software that allows you to access a DMS, and offers network connectivity.

https://en.wikipedia.org/wiki/Database_server“A database server is a computer program that provides database services to other computer programs or computers.”

Most database products (like MySQL, or MariaDB) combine a database, DMS, and a DS all in one package. However, it is important that you understand the difference and separation between the database (information), database management system

5

Page 6: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

(software that manages information), and database server (software that lets you connect).

Structured Query Language (SQL)Some people pronounce it “es-que-el”, and others just say “sequel”. Either way, it has become the standard language for interfacing with a database. All modern database management systems use it. But, there are different “flavors” of SQL. Various companies offer slightly different features and options. But, all of these variations are quite similar. We’ll focus our attention on those parts that are common. For a specific job, you might need to worry about the intricacies of one of the variations.

To get started, we need to have a DMS available to us. I suggest you install MariaDB on your computer. It’s totally free. If you are using one of our lab computers, it is already installed. If you want to use your own computer, you may Google MariaDB to find the latest version, or visit https://downloads.mariadb.org.

Assuming you have a database product installed on your computer, you can open it from your Start menu. Click on MySQL Client (MariaDB). You will be asked to enter a password. If you are using one of our lab computers, the password is “”root”. If you are using your own computer, use the password you picked when you installed the MariaDB software.

Assignment 1Write a one-page paper about databases. Please don’t make it longer. Please don’t give me fluff. I expect you to spend a few hours looking around on the web so that you can learn something, and then type up a short paper that makes a point. I’ll give you some ideas to get you started.

You could investigate:

The history of databases. When were they first used? How did they change?What is the difference between SQL and MySQL?Who created MySQL, who owns it now, and how does MariaDB fit in?What is the difference between Oracle and MySQL?Is Microsoft Access a database, DBMS, DS, or more… or less?What does “open source” mean, and how does it relate to databases and MySQL?What is this GNU thing all about, and how does it relate to databases?What are people or companies using databases for?How do databases affect you on a daily basis?How is your privacy affected by databases?Does Facebook use a database, and how does that affect you?Could Amazon exist without using a database?Do television networks use databases?

6

Page 7: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Who is storing, sharing, and using information about you, and what does that have to do with databases?

Those are just a few suggestions. Feel free to pick your own topic. Don’t just copy and paste stuff. Put it in your own words. Tell me something interesting. Teach me.

Chapter 2: Installing a Database Management SystemYou might want to put a DMS on your own computer so you can work at home. If you don’t want to do that, you can use our computers.

If you do want to install Database software, I’ll tell you what I did.

First, I went to: https://downloads.mariadb.org/(I found that my Googling “MariaDB Download”).

Next, I clicked on the button that says “Download 10.0.21 Stable Now!”

Once I moved to the Downloads page, I clicked on mariadb-10.0.21-winx64.msi.

The .msi extension means that the file is a MicroSoft Installer.If you aren’t using a 64-bit windows machine, you might make a different choice.

My computer started downloading the file, and I could see the progress in the lower left part of my browser. I waited until all 83.4 MB were downloaded.

Once the download was complete, I clicked on the arrow just to the right of the download bar. I chose “Show in folder”. Then I copied the downloaded file from that folder, and pasted it into my Downloads folder. I like to keep files like this handy.

Next, I double-clicked on the file “mariadb-10.0.21-winx64”, and clicked the “Run” button. (Next, Accept, Next, Next, yada yada yoda)

You’ll have to choose a password. I suggest you choose something easy to remember, like “pass”. Obviously, if you were building software for a company, you’d pick something harder to guess.

(Next, Next, Next, Install, Yes, Finish)

Now, you can click on your Start menu, and go to All Programs. You should see something like “MariaDB 10.0 (x64)”. Click on that, and you have some options.

Choose MySQL Client (MariaDB 10.0 (x64)).

This should open a command window, and it will ask you for a password.

7

Page 8: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Enter Password:

Use the password you picked when installing your DMS.

8

Page 9: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Assignment 2

Your DMS can hold lots of databases. Each database is a collection of tables. The tables store data. Each database is independent, so you can have lots of different projects all on one computer.

There are lots of ways to add information to a DMS. For now, we’re going to consider two of them: Typing code straight into the command prompt, and running a premade script. There are also lots of shortcuts you can use, but if you want to be a database guru (and pass this course), you’ll need to know how to control things from the highest level. It’s super useful to be able to have full control of things through a simple command prompt.

Assignment 2 Part I (80 points)

Type the following commands into the command prompt, and write down the response. Note that each line must end with a semicolon (;).

1.ashow databases;This command shows all databases currently in the DMS. You’ll already have 4 by default.

1.bcreate database socks;This command creates a new database.

1.cshow databases;Since you just created a new database, you should have 5 now.

1.duse socks;This command moves you into a particular database. All subsequent commands will refer only to the database you are currently using (socks).

1.ecreate table inventory (type text, size int);This command creates a new table. This table holds two things for each entry; the type of sock, and the size of the sock.

9

Page 10: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

1.fshow tables;This command shows the names of all of the tables in the database you are currently using.

1.gdescribe inventory;This command shows the structure of a given table. In this case, it shows us the structure of the inventory table.

1.hinsert into inventory values ("Crew", 1);

1.iinsert into inventory values ("Knee", 3);

1.jinsert into inventory values ("Ankle", 2);The above three commands add information to the database.

1.kselect * from inventory;This command gets information from the database. The * means get everything. You should see all three types of socks when you run this.

I haven’t explained what all of these commands do, or how to use them. I just wanted to get you started. I’ll cover all of these commands later in the semester. For now, just type them in, and tell me what you see.

10

Page 11: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Assignment 2 Part II

Sometimes it is useful to type a bunch of commands into a file, and run them all at once. This is particularly useful if you want to be able to recreate a database. For example, you might be working on a database for a company, and you’re building it on your own computer. Once you work out all the bugs, you’d like to install your work in one shot. That’s fancy, and a big time saver.

For our second part, we’ll run a script that removes the “socks” database (if and only if it already exists), and creates a new and better “socks” database. It will also add a bunch of data and, finally, show everything in the table.

One more interesting note: It’s kind of popular to type official SQL commands in all UPPERCASE, and to type stuff that we pick in lowercase. That’s what all the cool kids are doing. Let’s submit to peer pressure just this one time. I’m going to follow that convention below, and we’ll be doing that from now on.

Copy the text below, and save it as a .txt file (in Textpad, choose All Files), and name it “socks.sql”.

DROP DATABASE IF EXISTS socks;CREATE DATABASE socks;USE socks;CREATE TABLE inventory (type TEXT, size INT, color TEXT, instock INT);INSERT INTO inventory VALUES ("Crew", 1, "White", 8);INSERT INTO inventory VALUES ("Crew", 5, "Gray", 6);INSERT INTO inventory VALUES ("Ankle", 3, "White", 12);INSERT INTO inventory VALUES ("Knee", 6, "Red", 3);INSERT INTO inventory VALUES ("Ankle", 2, "Purple", 135);SELECT * FROM inventory;

I made a new folder on the C drive, and called it “database”. I put "socks.sql" in the database folder.

To run my script, I typed (into the SQL command console):SOURCE C:/database/socks.sql;

The SOURCE command tells the DMS to read something from a file, and run all of the commands in that file. The rest of the line tells the DMS where to find the file, and what its name is. If you didn’t save your file on the C drive in a folder called database, you’ll have to type in something different.

Write down the responses you see.

11

Page 12: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Chapter 3: Creating a Table

Creating a simple database

A very simple database is like a spreadsheet. It’s just one table.

Every table has columns and rows.

In database language, the columns are called fields. The rows are called records.

A record is a complete row in the database, and each field has a value. Also, each field has a data type. The entry that is inserted into that box needs to fit the data type allowed by that field.

Imagine (for some reason) we want to create a table that gathers information about people and their hat color, and we’ll also store an age. (This is probably the age of the person, but it could be the age of the hat. We’re software engineers. We don’t really care, as long as the customer is happy.)

So, Name, Age, HatColor…

Note that the table below (hatstuff) has three fields, and seven records.

Table:hatstuffname age hatcolorBilly Billysworth 18 blueRob Robinson 22 redAlex Alexton 14 greenSue Sueman 38 redJill Jillinstein 20 aquaMary Marigold 53 purpleSam Samson 31 yellow

The top (highlighted) row isn’t really part of the table data. We call this Meta Data.

The other rows contain data. You can imagine that this table could contain thousands of rows. How do we create a table that can store information like this?

The first step is to choose a data type for each field (column). In this example, the first field (name) is a string of characters. The second field (age) is an integer. The third field (hatcolor) is another sting of characters.

12

Page 13: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Some SQL Data Types

SQL has many defined data types. The ones shown below are very useful. There are more. This list will do for now.

TINYINT – One Byte (-128 to 127)

SMALLINT – Two Bytes (-32,768 to 32,767)

INT – Four Bytes ( -2 Billion to 2 Billion)

BIGINT – Eight Bytes ( -1019 to 1019)

DOUBLE – Eight Bytes (Floating point -10300 to 10300)

DATE – Stores dates in the format (YYYY-MM-DD)

TIMESTAMP – Stores date and time in the format (YYYY-MM-DD HH:MM:SS)

TINYTEXT – A string that holds up to 255 characters

TEXT – A string that holds up to 65,000 characters

LONGTEXT – A string that holds over 4 billion characters

It is the job of a database designer to choose appropriate data types for each field. You should always choose a type that is guaranteed to hold any value that might be put into the database, and not to choose a type that is unnecessarily large.

Back to our example:

name, age, hatcolor

A name or hat color should never exceed 255 characters, and an age will not exceed 127 years. As medical science develops, and if we come up with very long color names, you can challenge the above, but for now, I think this is a solid assumption.

13

Page 14: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

name – TINYTEXT (up to 255 characters)

age – TINYINT (up to 127)

hatcolor – TINYTEXT (up to 255 characters)

If you chose TEXT for the name data type, I would wonder who has a name that is longer than 255 characters. If you chose BIGINT for the age data type, I think you’re overly optimistic. If you chose DOUBLE or TIMESTAMP for the hatcolor data type, you need to go to sleep now.

SQL Commands: CREATE, USE, SHOW, DROP, DELETE, and TRUNCATE

The CREATE command has two uses. It can be used to create a database, or to create a table within a database. First, we’ll use it to create a database.

CREATE DATABASE hats;

The SHOW command, also, has two uses. It can show all of the databases in our system, or show the columns in a table. For now, let’s use it to make sure we created the database.

SHOW DATABASES;

USEThe USE command allows you to choose one of the databases in your Database Management System. You can choose a database, or switch to a new database at any time, even from within the database you are currently using. Now that we’ve created the hats database, let’s go in there.

USE hats;

14

Page 15: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

CREATENow, we can use CREATE for its second purpose, to create a table.

CREATE TABLE hatstuff (name TINYTEXT, age TINYINT, hatcolor TINYTEXT);

The syntax of the above is very important. Let’s talk about that.

CREATE TABLE tablename ();

You can choose any name for the tablename. Inside the parentheses, you must, for each field, enter a name and a data type. Put a comma between fields.

Since we want three fields, we need to type a name and datatype for each of the three.

name TINYTEXT

age TINYINT

hatcolor TINYTEXT

And we use a comma to separate them. Now, does this line of code make sense?

CREATE TABLE hatstuff (name TINYTEXT, age TINYINT, hatcolor TINYTEXT);

SHOWThe second use of the SHOW command works when we are in a database.

SHOW TABLES;

This command lists all tables in the current database.

Also, you can view the structure of a table to make sure it has the field names, data types, and other attributes you want by using the SHOW COLUMNS FROM command.

SHOW COLUMNS FROM hatstuff;

There are also two shorter versions for convenience.

DESCRIBE hatstuff;

DESC hatstuff;

15

Page 16: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

They do exactly the same thing as SHOW COLUMNS FROM.

You should see a nice little picture of your table structure, just like the one below.

MariaDB [hats]> DESCRIBE hatstuff;+----------+------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+----------+------------+------+-----+---------+-------+| name | tinytext | YES | | NULL | || age | tinyint(4) | YES | | NULL | || hatcolor | tinytext | YES | | NULL | |+----------+------------+------+-----+---------+-------+3 rows in set (0.11 sec)

16

How did I copy and paste stuff from the database console into this Word document?

With the console open, click on the little icon in the upper left. You’ll see a drop-down menu. Point at Edit, and you’ll see a sub menu. Choose Mark.

Now, you can click and drag to select a rectangle. It will be highlighted.

Next, click on the little icon in the upper left again. Point at Edit, and choose Copy. That puts your selected text on the system clipboard. Switch to a Word document, or whatever you use to create documents, and when you choose paste, you’ll see everything you selected from your database console.

Page 17: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

DROPAt some point, you might decide that you need to wipe out your database, and start over. You can use the DROP DATABASE command for this. It removes all information and tables in the database, and removes the database.

Syntax:

DROP DATABASE database;

Example:

DROP DATABASE hats;

You might also want to remove a table from your database, and recreate it from scratch. You can use the DROP TABLE command for this. It removes all data and the entire data structure. You must be using a database to drop a table within that database.

Syntax:

DROP TABLE tablename;

Example:

DROP TABLE hatstuff;

DELETEOn the other hand, you might want to keep your table, but remove all of the data in it. There are two ways to do this. You could use the DELETE command. You can do some fancy things with this, like deleting only some rows, and we’ll talk about that later. For now, you can delete all records in a table with one simple line. Note that DELETE does not remove the table. It just removes the data in the table. The table will still exist.

Syntax:

DELETE FROM TABLE tablename;

Example:

DELETE FROM TABLE hatstuff;

17

Page 18: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

TRUNCATEThere is another way to remove all records from a table that is much faster if you have a large table. You can use the TRUNCATE command. This command actually stores the table’s structure, drops the table, and then recreates the table with no records in it. It’s faster because it does not delete records one row at a time. It just wipes out everything, and then recreates the table.

Syntax:

TRUNCATE TABLE tablename;

Example:

TRUNCATE TABLE hatstuff;

18

Page 19: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Example assignment and solution: Create a database and table that holds a person’s name, age, and hat color. Choose appropriate data types. Paste the database console output into a document as you: create the database, check to see that the database exists, move into the database, create the table, check to see that the table exists, and check the structure of the table.

MariaDB [(none)]> CREATE DATABASE hats;Query OK, 1 row affected (0.09 sec)

MariaDB [(none)]> SHOW DATABASES;+--------------------+| Database |+--------------------+| hats || information_schema || mysql || performance_schema || socks || test |+--------------------+6 rows in set (0.14 sec)

MariaDB [(none)]> USE hats;Database changedMariaDB [hats]> CREATE TABLE hatstuff (name TINYTEXT, age TINYINT, hatcolor TINYTEXT);Query OK, 0 rows affected (0.62 sec)

MariaDB [hats]> SHOW TABLES;+----------------+| Tables_in_hats |+----------------+| hatstuff |+----------------+1 row in set (0.05 sec)

MariaDB [hats]> DESCRIBE hatstuff;+----------+------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+----------+------------+------+-----+---------+-------+| name | tinytext | YES | | NULL | || age | tinyint(4) | YES | | NULL | || hatcolor | tinytext | YES | | NULL | |+----------+------------+------+-----+---------+-------+3 rows in set (0.11 sec)

19

Page 20: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Assignment 31. Create a database and table that holds a cat’s name, color, and length(in inches). Choose appropriate data types. Paste the database console output into a document as you: create the database, check to see that the database exists, move into the database, create the table, check to see that the table exists, and check the structure of the table.

Make a database called “CatDB”, and a table called “cat”.

2. Create a database and table that holds information about fish. Each fish has an owner, age (in days), color, and length (in cm). Choose appropriate data types. Paste the database console output into a document as you: create the database, check to see that the database exists, move into the database, create the table, check to see that the table exists, and check the structure of the table.

Make a database called “ FishDB”, and a table called “fish”.

20

Page 21: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Chapter 4: Advanced table creation, and ERDs

Section 1 – Data types

Some data types have arguments. That means you can fine tune your table by including a value or values in parentheses. The argument might not be required. If it is not required, and you don’t include the argument, a default value will be used.

Some data types have optional attributes. They only need to be included if you want to use them. Optional attributes are shown in square brackets ([]).

Bit Types

BIT(N)

The BIT type can be used to store a number of bits from 1 to 64, depending on the argument, N. The argument, N, is not required. If left out, the default value is 1.

Example:

CREATE TABLE data (boolean BIT, nibble BIT(4), byte BIT(8));

MariaDB [test]> DESC data;+---------+--------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+---------+--------+------+-----+---------+-------+| boolean | bit(1) | YES | | NULL | || nibble | bit(4) | YES | | NULL | || byte | bit(8) | YES | | NULL | |+---------+--------+------+-----+---------+-------+

Integer Types

TINYINT [UNSIGNED]

The TINYINT data type stores integers using one byte (8 bits). By default, this will be a signed integer. It can store values from -127 to +128. If the optional UNSIGNED attribute is used, it will store only positive numbers from 0 to 255.

21

Page 22: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Example:

CREATE TABLE car (temperature TINYINT, age TINYINT UNSIGNED);

MariaDB [test]> DESC car;+-------------+---------------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------------+---------------------+------+-----+---------+-------+| temperature | tinyint(4) | YES | | NULL | || age | tinyint(3) unsigned | YES | | NULL | |+-------------+---------------------+------+-----+---------+-------+

SMALLINT [UNSIGNED]

The SMALLINT data type stores integers using two bytes. By default, this will be a signed integer. It can store values from -32,768 to +32,767. If the optional UNSIGNED attribute is used, it can store numbers from 0 to 65,535.

INT [UNSIGNED]

The INT data type stores integers using four bytes. By default, this will be a signed integer. It can store values from about -2 billion to +2 billion. If the optional UNSIGNED attribute is used, it can store numbers from 0 to about 4 billion.

BIGINT [UNSIGNED]

The BIGINT data type stores integers using eight bytes. By default, this will be a signed integer. Signed or unsigned, it can hold more numbers than grains of sand on the Earth. (About 1020)

Floating Point Types

These types are used for numbers that are not integers. That is, they have digits beyond the decimal point. All of these types are signed.

FLOAT

22

Page 23: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

The FLOAT data type stores signed floating point numbers using 32 bits. It can store numbers ranging from about -1038 to +1038, with 24 decimal digits.DOUBLE

The DOUBLE data type stores signed floating point numbers using 64 bits. It can store numbers ranging from about -10308 to +10308, with 53 decimal digits.

DECIMAL

The DECIMAL data type stores signed floating point numbers as a text string. It’s not useful for math. It’s probably not what you want. The NUMERIC data type is a synonym for DECIMAL.

Character and String Types

CHAR(M)

The CHAR data type is used to store characters. The M argument sets the number of characters that can be stored in the field. It is not required. If left out, the default length is 1 character. When something is added to the database, it will take up M characters, with extra spaces added if necessary.

VARCHAR(M)

The VARCHAR data type is a fancy version of the CHAR type. The M argument is required. It sets the maximum number of characters to be stored. It only uses enough memory to store each entry.

You will find many opinions about which is best, and when. For this course, either is fine. The CHAR type is often faster. The VARCHAR type uses memory more efficiently. Given a particular database product, you might also run into NVARCHAR, and VARCHAR2. I suggest you don’t spend a lot of time worrying about it, unless you’re into that.

TEXT vs. BLOB

The following types each have two versions. For now, all you should care about is the TEXT version. However, for every TEXT, there is a corresponding BLOB. For example, TINYTEXT is almost exactly the same as TINYBLOB. The only difference is that BLOB searches and sorts are case sensitive. TEXT searches and sorts are not. BLOB stands for Binary Large Object, and you can store images or other large groups of data in a blob. For many purposes, you’d be better off to store images and data in a file, and put only a link to that file in your database. For now, let’s focus on TEXT types.

23

Page 24: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

TINYTEXT (TINYBLOB)

The TINYTEXT data type holds up to 255 characters.

TEXT (BLOB)

The TEXT data type holds up to 65,535 characters.

MEDIUMTEXT (MEDIUMBLOB)

The MEDIUMTEXT data type holds up to 16,777,215 characters.

LONGTEXT (LONGBLOB)

The LONGTEXT data type can hold over 4 billion characters.

Enumerations

An enumeration is a list of acceptable values. If you create a table with an enumerated field, you are saying that the entry must be one of those acceptable values.

ENUM(‘a’, ‘b’, ‘c’,…)

The ENUM data type holds one value from a predefined list. These values are normally strings, and should be surrounded by apostrophes. The list could also contain integers surrounded by quotation marks, but that can cause some squirrelly results. I don’t suggest doing that.

Example:

CREATE TABLE color (choice ENUM('red', 'green', 'blue'));

MariaDB [test]> desc color;+--------+----------------------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+--------+----------------------------+------+-----+---------+-------+

24

Page 25: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

| choice | enum('red','green','blue') | YES | | NULL | |+--------+----------------------------+------+-----+---------+-------+

Dates and Times

DATE

A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th, 1973 would be stored as 1973-12-30.

DATETIME

A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.

TIMESTAMP

A timestamp between midnight, January 1, 1970 and sometime in 2037. This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).

TIME

Stores the time in HH:MM:SS format.

YEAR(M)

Stores a year in 2-digit or 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is specified as 4, YEAR can be 1901 to 2155. The default length is 4.

25

Page 26: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Section 2 – Optional CREATE Constraints

For each field you create in a CREATE statement, there are some optional constraints that you might want to use.

NOT NULL

You might want to enter a new row in a database, and leave some fields as “undecided for now”. If the NOT NULL attribute is used, you’re not allowed to leave it blank. Doing so will cause an error. This is your way of saying this field needs a value.

Let’s say our database holds user information. Each user has an email address and a phone number. Let’s assume that the email address is required to create the account, but the phone number can be entered later.

Example:

CREATE TABLE users (email TINYTEXT NOT NULL, phone CHAR(14));

MariaDB [test]> DESC users;+-------+----------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+----------+------+-----+---------+-------+| email | tinytext | NO | | NULL | || phone | char(14) | YES | | NULL | |+-------+----------+------+-----+---------+-------+

DEFAULT

Assuming the field hasn’t been defined as a NOT NULL field, you might want to define some default value. That means if nothing is entered, the default value is used. Put strings in apostrophes. Leave numbers alone. Oddly enough, you can’t specify a default value for any of the TEXT types. I don’t know why.

Example:

CREATE TABLE cats (color VARCHAR(15) DEFAULT 'black', age TINYINT DEFAULT 0);

MariaDB [test]> DESC cats;+-------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+-------------+------+-----+---------+-------+| color | varchar(15) | YES | | black | || age | tinyint(4) | YES | | 0 | |+-------+-------------+------+-----+---------+-------+

26

Page 27: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

UNIQUE

If you use the UNIQUE constraint, that means every entry in that column has to be different. Otherwise, you’ll get an error. That can be useful. If you want everyone to have a unique username, this is the thing to use.

Example:

CREATE TABLE phonelist (name VARCHAR(30), number CHAR(14) UNIQUE);

MariaDB [test]> DESC phonelist;+--------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+--------+-------------+------+-----+---------+-------+| name | varchar(30) | YES | | NULL | || number | char(14) | YES | UNI | NULL | |+--------+-------------+------+-----+---------+-------+

PRIMARY KEY

Every table should have a primary key. < Please read that again.

A primary key is the one thing that lets you find the row you’re looking for. The DMS sets up a hidden map table that makes searches faster. The primary key will be unique and it can’t be null. In other words, when you use this constraint…

PRIMARY KEY

You are using…

PRIMARY KEY UNIQUE NOT NULL

Also, a table can have only one primary key. It is possible to define a primary key that is comprised of multiple fields. Let’s not worry about that now.

Also, you can’t use huge fields for a primary key. You should use integer types, or character (CHAR or VARCHAR) types. Don’t use TEXT, FLOAT, etc.

Given a problem to solve, whether it is a homework problem, exam problem, or a job assignment, it is your job to make sure that every table has a primary key. If one isn’t already there, you need to add one.

27

Page 28: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

AUTO_INCREMENTThis is a very useful feature. It is mainly used to generate unique id’s. You can specify an integer field as AUTO_INCREMENT provided that it is indexed (for example, it is the primary key), and it does not have a default value. It also must be designated as a NOT NULL field. You may only have one AUTO_INCREMENT field in a table. When a value of NULL is given, The DMS will automatically enter 1 for the first record, and increment from there.

Example:

CREATE TABLE carpet (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,color CHAR(20),price float);

INSERT INTO carpet VALUES (NULL, 'Red', 5.95);INSERT INTO carpet VALUES (NULL, 'Blue', 4.59);INSERT INTO carpet VALUES (NULL, 'Burgundy', 6.25);

SELECT * FROM carpet;

+----+----------+-------+| id | color | price |+----+----------+-------+| 1 | Red | 5.95 || 2 | Blue | 4.59 || 3 | Burgundy | 6.25 |+----+----------+-------+

28

Page 29: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Example:

Create a table that holds (for each user) an email address, a first name, a last name, and a six-digit product number.

In this case, several users might have the same first name. They might have the same last name. They might be ordering the same product. But, email addresses are unique. The email address would make a good primary key.

This is a long line of SQL code, so we’ll split it up over several lines.

CREATE TABLE orders(email VARCHAR(50) PRIMARY KEY,firstname VARCHAR(20),lastname VARCHAR(20),product INT);

MariaDB [test]> DESC orders;+-----------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-----------+-------------+------+-----+---------+-------+| email | varchar(50) | NO | PRI | NULL | || firstname | varchar(20) | YES | | NULL | || lastname | varchar(20) | YES | | NULL | || product | int(11) | YES | | NULL | |+-----------+-------------+------+-----+---------+-------+

Example:

Create a table that holds the name of a horse, and his or her age.

In this case, we might have two or more horses with the same name. We might have two or more horses with the same age. We’ll need to add a new field that our employer (or professor) didn’t ask for. Every table should have a primary key. If it isn’t there, make a new field.

CREATE TABLE horses(name TINYTEXT,age TINYINT UNSIGNED,id INT PRIMARY KEY);

MariaDB [test]> DESC horses;+-------+---------------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+---------------------+------+-----+---------+-------+| name | tinytext | YES | | NULL | || age | tinyint(3) unsigned | YES | | NULL | || id | int(11) | NO | PRI | NULL | |+-------+---------------------+------+-----+---------+-------+

29

Page 30: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

So far, our examples have been a bit silly, and not at all realistic. Let’s put it all together, and make a table that is almost useful.

Example:

You’re working in a restaurant, and you need to make a table to hold all the soups your restaurant offers. The table must store the name of the soup (which is unique and required), the name of the chef who created it (that isn’t optional), a description of the soup (optional), and the price for a bowl (that’s optional, but it’s $8.00 unless otherwise stated). Recipe notes and the first day it was made are both optional.

CREATE TABLE soup(soup_id INT PRIMARY KEY,soup_name VARCHAR(20) UNIQUE NOT NULL,soup_creator VARCHAR(30) NOT NULL,soup_description TEXT,soup_price FLOAT DEFAULT 8.00,soup_recipe_notes TEXT,soup_creation_date DATE);

MariaDB [test]> DESC soup;+--------------------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+--------------------+-------------+------+-----+---------+-------+| soup_id | int(11) | NO | PRI | NULL | || soup_name | varchar(20) | NO | UNI | NULL | || soup_creator | varchar(30) | NO | | NULL | || soup_description | text | YES | | NULL | || soup_price | float | YES | | 8 | || soup_recipe_notes | text | YES | | NULL | || soup_creation_date | date | YES | | NULL | |+--------------------+-------------+------+-----+---------+-------+

By the way, it doesn’t matter what order you put optional constraints in when you write your CREATE statements.

The name goes first, then the data type, then the optional constraints, in any order.

30

Page 31: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Section 3 – ERDs (Entity Relationship Diagrams)

An Entity Relationship Diagram (ERD) shows how tables are connected. So far, we’ve been using only one table, so this might not seem useful. However, things get very complicated when you’re storing lots of data.

What does an ERD look like for just one table?

It’s pretty simple, and it’s worth big points on your first exam.

Draw a box. Put the name of the table on top. Underneath, for each field, list the name of the field, the data type for that field, and any interesting constraints.

Let’s put the example above into an ERD.

You’re working in a restaurant, and you need to make a table to hold all the soups your restaurant offers. The table must store the name of the soup (which is unique and required), the name of the chef who created it (that isn’t optional), a description of the soup (optional), and the price for a bowl (that’s optional, but it’s $8.00 unless otherwise stated). Recipe notes and the first day it was made are both optional.

31

soup

soup_id INT PRIMARY KEY

soup_name VARCHAR(20) UNIQUE, NOT NULL

soup_creator VARCHAR(30) NOT NULL

soup_description TEXT

soup_price FLOAT DEFAULT 8.00

soup_recipe_notes TEXT

soup_creation_date DATE

Page 32: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Assignment 4

1. Draw an ERD that represents a person. Each person should have a social security number (the primary key), a first and last name (both required), and a favorite color (which is an optional attribute). Make sure you add a primary key if one isn’t obvious.

2. Write the SQL code to make the table described above.

3. Draw an ERD that represents a car. Each car should have a color (required), a year (required), and an attribute that defines the maximum number of passengers (which is optional). Make sure you add a primary key if one isn’t obvious.

4. Write the SQL code to make the table described above.

5. Draw an ERD that represents a potato. Each potato should have a name, which is an optional attribute, a brand (required), and a favorite color (which is an optional attribute). Make sure you add a primary key if one isn’t obvious.

6. Write the SQL code to make the table described above.

32

Page 33: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

For your first exam, you are not allowed to use any books, notes, computers, tablets, phones, calculators, friends, slide rules, ear buds, magic horses, abaci, anything that starts with an i, or anything else that I forgot to mention.

You are allowed to bring: one sheet of paper with anything you want to put on it, and the writing utensil of your choice. While you are putting together that one sheet of paper, you might want to consider the summary below.

If it makes complete sense to you, that’s good. If it is confusing, you might want to scroll up, and read it all again. I hope this summary helps.

Summary 1

Data Types:

BIT(N) N = number of bits 1 to 64. Default = 1 bitTINYINT [UNSIGNED] -127 to +128 or 0 to 255.SMALLINT [UNSIGNED] -32,768 to +32,767 or 0 to 65,535INT [UNSIGNED] -2 billion to +2 billion or 0 to about 4 billionBIGINT [UNSIGNED] More than you’ll ever needFLOAT -1038 to +1038

DOUBLE -10308 to +10308

CHAR(M) Stores M charactersVARCHAR(M) Stores up to M charactersTINYTEXT 255 charactersTEXT 65,535 charactersMEDIUMTEXT 16,777,215 charactersLONGTEXT over 4 billion charactersENUM(‘a’, ‘b’, ‘c’,…) List of stringsDATE YYYY-MM-DD formatDATETIME YYYY-MM-DD HH:MM:SS formatTIMESTAMP YYYYMMDDHHMMSS formatTIME HH:MM:SS formatYEAR(M) year in 2-digit or 4-digit format

Commands:

SOURCE filename.sql Runs the code in the fileUSE databasename Selects an existing databaseCREATE DATABASE databasenameCREATE TABLE tablename (fieldname datatype [NOT NULL] [DEFAULT value] [UNIQUE] [PRIMARY KEY], …)SHOW DATABASESSHOW TABLESDESCRIBE tablename DESC tablename

33

Page 34: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Chapter 5: Adding and Retrieving DataCreating a table is cool, but it isn’t very useful unless we can put new stuff (new records) into it, and pull stuff out of it.

Section 1 – Adding a Record, or Row

We can add data into a table by using the SQL INSERT command. There are three ways to use it. We can add a complete row, or we can just put in values for some of the fields, and let the rest be null (nothing), or a default value. Either way, we’ll create a new row (or record) in our table. Let’s use a specific example.

We can add data to a table by using the INSERT command. There are three ways to use it.

INSERT INTO tablename VALUES (val1, val2, val3…);

INSERT INTO tablename (field1, field2,…) VALUES (val1, val2,…);

INSERT INTO tablename SET field1 = val1, field2 = val2,…;

The first variation is handy for a small table. You need to enter a value for every field. You may enter null, if that is allowed. The values must be entered in the order in which they were defined when the table was created.

The second variation is useful if you only want to enter values for some fields, and leave the rest as null, or default values. You’ll need to first list all field names for which you want to enter values, and then enter values, in the same order, for those fields.

The third variation is also useful when you are entering values for some fields, but you want to let others be null or default values. It is also the most readable, and the easiest to maintain and edit. It makes the allocation of values very obvious. You may enter data in any order, since you must specify a field name for each value. Notice that the SET keyword is used only once.

Example:

INSERT INTO horse SET id = 6, name = 'Racer';

34

Page 35: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Create a database and table for a single entity called “horse”. Each horse has a name, a weight (in pounds), an owner, and a best time (In seconds).

Since two horses might have the same name, we’ll add an ID to serve as our primary key. The problem description didn’t tell us to do that. We chose to. We also need to choose a name for the database. We’ll call the database horserace, and call the table horse.

35

horse

id INT PRIMARY KEY

name VARCHAR(20) NOT NULL

weight FLOAT

owner VARCHAR(30)

time SMALLINT DEFAULT 50

Page 36: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

CREATE DATABASE horserace;USE horserace;CREATE TABLE horse (id INT PRIMARY KEY, name VARCHAR(20) NOT NULL, weight FLOAT, owner VARCHAR(30), time SMALLINT DEFAULT 50);

Now that we have a table, we can start adding some records (or rows).

Entering a complete row

The syntax for the INSERT command is:

INSERT INTO tablename VALUES (val1, val2, val3…);

All text type values (CHAR, VARCHAR, TEXT, etc.) must be surrounded by apostrophes. Numerical values (INT, SMALLINT, BIGINT, FLOAT, etc.) are not surrounded by anything.

Let’s put a new row into our table.

INSERT INTO horse VALUES (1, 'Lady Luck', 958.5, 'Mike', 93);

Note that text values are surrounded by apostrophes. Numerical values are not.Let’s add a few more records.

INSERT INTO horse VALUES (2, 'Bad Boy', 1028.3, 'Bob', 98);INSERT INTO horse VALUES (3, 'Stomper', 1072.7, 'Sue', 91);INSERT INTO horse VALUES (4, 'Mr. Steel', 917.4, 'Joan', 103);

Entering a partial row

If we want to, we can enter values for some fields, and let the omitted fields be null or default values. If we do that, we need to specify the fields for which we will enter values. We must put something in for any field we declared as NOT NULL.

In our example, id is a primary key, so we need to put a value in that field (the primary key always needs a value). Also, we said that the name can’t be null, so we need to put in a value for that. We can leave the rest out, and our DMS will automatically put in a null (0), or a default value if we picked one when we created the table.

The syntax for the INSERT command is:

INSERT INTO tablename (field1, field2,…) VALUES (val1, val2,…);

36

Page 37: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

For example, let’s add a new horse. We’ll make sure we have a value for id and name. They are required. We’ll leave everything else blank.

INSERT INTO horse (id, name) VALUES (5, 'Jedi Master');

Since we did not specify a value for weight or owner, they will be blank. We also did not specify a value for time. But, we picked 50 as a default value when we created the table, so 50 will be inserted.

Note that we could use this form of the INSERT statement to enter values into every field. It isn’t as convenient as the first variation.

If we look at our table (We’ll see how to do that below), we have:

+----+-------------+--------+-------+------+| id | name | weight | owner | time |+----+-------------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 || 2 | Bad Boy | 1028.3 | Bob | 98 || 3 | Stomper | 1072.7 | Sue | 91 || 4 | Mr. Steel | 917.4 | Joan | 103 || 5 | Jedi Master | NULL | NULL | 50 |+----+-------------+--------+-------+------+

INSERT INTO tablename SET field1 = val1, field2 = val2,…;

37

Page 38: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Section 2 – Retrieving Data

We pull data out of a database using the SELECT command. Here’s the syntax.

SELECT field1, field2… FROM tablename;

For example, we could use the following statement to retrieve the names and times from our horse example above.

SELECT name, time FROM horse;

This gives us the following:

+-------------+------+| name | time |+-------------+------+| Lady Luck | 93 || Bad Boy | 98 || Stomper | 91 || Mr. Steel | 103 || Jedi Master | 50 |+-------------+------+

Instead of listing field names, we can use an asterisk (*) to list the whole table.

Show everything in the horse table

SELECT * FROM horse;

+----+-------------+--------+-------+------+| id | name | weight | owner | time |+----+-------------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 || 2 | Bad Boy | 1028.3 | Bob | 98 || 3 | Stomper | 1072.7 | Sue | 91 || 4 | Mr. Steel | 917.4 | Joan | 103 || 5 | Jedi Master | NULL | NULL | 50 |+----+-------------+--------+-------+------+

38

Page 39: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Select statements can get more interesting. You can add a WHERE clause. The argument to a WHERE clause is a Boolean expression.

SELECT * FROM horse WHERE time > 92;

+----+-----------+--------+-------+------+| id | name | weight | owner | time |+----+-----------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 || 2 | Bad Boy | 1028.3 | Bob | 98 || 4 | Mr. Steel | 917.4 | Joan | 103 |+----+-----------+--------+-------+------+

The WHERE clause can contain the Boolean AND and OR operators.

SELECT * FROM horse WHERE weight > 950 AND time < 100;

+----+-----------+--------+-------+------+| id | name | weight | owner | time |+----+-----------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 || 2 | Bad Boy | 1028.3 | Bob | 98 || 3 | Stomper | 1072.7 | Sue | 91 |+----+-----------+--------+-------+------+

SELECT * FROM horse WHERE time < 90 OR time > 100;

+----+-------------+--------+-------+------+| id | name | weight | owner | time |+----+-------------+--------+-------+------+| 4 | Mr. Steel | 917.4 | Joan | 103 || 5 | Jedi Master | NULL | NULL | 50 |+----+-------------+--------+-------+------+

39

Page 40: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Assignment 51. Draw an ERD that represents a person. Each person should have a social security number (the primary key), a first name (required), a last name (required), and a thumb length in millimeters (which is an optional attribute). (10 points)

2. Write the SQL code to create a database to hold the person table. (5 points)

3. Write the SQL code to move into the database above. (5 points)

4. Write the SQL code to create the person table. (5 points)

5. Write the SQL code to display all tables in the current database. (5 points)

6. Write the SQL code to show the format of the person table. (5 points)

7. Write the SQL code to add a new row with a ssn of 011-27-0123, a first name of Phil, a last name of Phillips, and a thumb length of 39 mm. (5 points)

8. Write the SQL code to add a new row with a ssn of 102-38-8453, a first name of Sue, and a last name of Suebert. (5 points)

9. Write the SQL code to show everything in the person table. (5 points)

10. Draw an ERD that represents an apple. Each apple should have a color (required), a diameter in feet (required), and a sell-by date (which is optional, in a YYYY-MM-DD format). (10 points)

11. Write the SQL code to display all databases in the system. (5 points)

12. Write the SQL code to create a database to store your apples. (5 points)

13. Write the SQL code to create the apple table. (5 points)

14. Write the SQL code to add a new apple that is red, has a diameter of 0.12 feet, and should be sold by January 12, 1959. (5 points)

15. Write the SQL code to add a new apple that is green, has a diameter of 0.18 feet, and should be sold by 10-18-2015. (5 points)

16. Write the SQL code to add a new apple that is yellow, has a diameter of 0.21 feet, and should be sold by December 24, 2014. (5 points)

17. Write the SQL code to show only the color of all apples in the apples table. (5 points)

18. Write the SQL code to show everything about all bad apples in the table. (5 points)

40

Page 41: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Chapter 6: Adding and Retrieving Data Continued

Select statements can get more interesting. You can add a WHERE clause.

WHERE ClausesSELECT statements can get more interesting. You can add a WHERE clause. This clause filters the results of a database query so that only some records are displayed.

Syntax:

SELECT field1, field2… FROM tablename WHERE condition;

Or, if you want to see all fields in the chosen records,

SELECT * FROM tablename WHERE condition;

A condition is something that is true or false for any particular record. Let’s use our horse table as an example.

SELECT * FROM horse;

+----+-------------+--------+-------+------+| id | name | weight | owner | time |+----+-------------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 || 2 | Bad Boy | 1028.3 | Bob | 98 || 3 | Stomper | 1072.7 | Sue | 91 || 4 | Mr. Steel | 917.4 | Joan | 103 || 5 | Jedi Master | NULL | NULL | 0 |+----+-------------+--------+-------+------+

41

Page 42: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

If we add a WHERE clause, we can display only the records for which the time is greater than 92.

SELECT * FROM horse WHERE time > 92;

+----+-----------+--------+-------+------+| id | name | weight | owner | time |+----+-----------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 || 2 | Bad Boy | 1028.3 | Bob | 98 || 4 | Mr. Steel | 917.4 | Joan | 103 |+----+-----------+--------+-------+------+

Or, we can select the horse name and time, for which the time is less than or equal to 93.

SELECT name, time FROM horse WHERE time <= 93;

+-------------+------+| name | time |+-------------+------+| Lady Luck | 93 || Stomper | 91 || Jedi Master | 0 |+-------------+------+

Or, we can select all records for which the time is exactly 93.

SELECT * FROM horse WHERE time = 93;

+----+-----------+--------+-------+------+| id | name | weight | owner | time |+----+-----------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 |+----+-----------+--------+-------+------+

42

Page 43: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Relational Operators for WHERE Clauses

Equals =Is not equal to != or <>Is greater than >Is Less than <Is greater or equal >=Is less or equal <=

WHERE Clauses Involving String Types

These relational operators work with all numerical types, but they also work with string types. We can list all records for which the owner is Bob.

SELECT * FROM horse WHERE owner = 'Bob';

+----+---------+--------+-------+------+| id | name | weight | owner | time |+----+---------+--------+-------+------+| 2 | Bad Boy | 1028.3 | Bob | 98 |+----+---------+--------+-------+------+

We can even use less than (<), greater than (>) etc, to filter results alphabetically.

For example, we could display all records that have a horse name less than 'M'. This would show horses with names that are alphabetically before 'M'.

SELECT * FROM horse WHERE name < 'M';

+----+-------------+--------+-------+------+| id | name | weight | owner | time |+----+-------------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 || 2 | Bad Boy | 1028.3 | Bob | 98 || 5 | Jedi Master | NULL | NULL | 0 |+----+-------------+--------+-------+------+

43

Page 44: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

The LIKE OperatorThis operator only works on string types. It is used when you want to retrieve records that contain a string that is similar in some way to a search parameter. You can use the percent symbol (%) as a wild card. The percent symbol represents zero or more characters.

Example:

This SELECT statement displays records for all horses that have a name that starts with 'L'.

SELECT * FROM horse WHERE name LIKE 'L%';

+----+-----------+--------+-------+------+| id | name | weight | owner | time |+----+-----------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 |+----+-----------+--------+-------+------+

This SELECT statement displays records for all horses that have a name that contains an 'a'

44

Page 45: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

SELECT * FROM horse WHERE name LIKE '%a%';

+----+-------------+--------+-------+------+| id | name | weight | owner | time |+----+-------------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 || 2 | Bad Boy | 1028.3 | Bob | 98 || 5 | Jedi Master | NULL | NULL | 0 || 6 | Racer | NULL | NULL | 0 |+----+-------------+--------+-------+------+

You can also use an underscore (_) to represent exactly one character. The following displays the records for all horses that have an 'a' as the second letter in their name.

SELECT * FROM horse WHERE name LIKE '_a%';

+----+-----------+--------+-------+------+| id | name | weight | owner | time |+----+-----------+--------+-------+------+| 1 | Lady Luck | 958.5 | Mike | 93 || 2 | Bad Boy | 1028.3 | Bob | 98 || 6 | Racer | NULL | NULL | 0 |+----+-----------+--------+-------+------+

Using the WHERE Clause with DELETE

This is the real use of the DELETE command. You can use the WHERE clause with DELETE in the same way you use it with SELECT.

DELETE FROM horse WHERE time < 50;

Warning!!! DELETE is a powerful command. It is normally used to remove only some of the records in a table. If you forget your WHERE clause, you will wipe out the entire table!

45

Page 46: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Assignment Example:

For this next assignment, I want you to email me a SQL script. This is just a text file that has a .sql extension.

Create a database that keeps track of cats. Call the database “cats”.Remove the database from the system.Create a database that keeps track of cats. Call the database “cats”.

Make a table called cat. Every cat has an id (up to 255 cats), a name (up to 255 characters), and a number of whiskers (as many as 20).

Throw away that table. It’s no good. Let’s start over.

Make a table called cat. Every cat has an id, which is the primary key. Make the id automatic. The database should hold at least one million cats. Each cat has a name, and the names must be unique, and the name is required. The name might have up to 30 characters. Every cat also has a weight in pounds. That’s not an int. The cat might weigh 2.3 pounds. If a weight is unknown, the database should automatically assume 3.1 lbs.

Display the structure of the cat table 3 different ways.

Add some cats.Tiffany, 3.4 lbsSvenson, 2.1 lbsPika, 4.2 lbsSonar, 2.8 lbsMr. Olson, weight unknown

Display all cats heavier than 3 pounds.Display all cats that have “son” in their name.Display all cats who aren’t named Tiffany.Remove all cats that have “son” in their name.Display only the names of the cats left in the table.

46

Page 47: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Example Solution:

Save this file as catdb.sql

CREATE DATABASE cats;DROP DATABASE cats;CREATE DATABASE cats;USE cats;CREATE TABLE cat (id TINYINT, name TEXT, whiskers TINYINT);DROP TABLE cat;CREATE TABLE cat (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,name VARCHAR(30) UNIQUE, weight FLOAT);SHOW COLUMNS FROM cat;DESCRIBE cat;DESC cat;INSERT INTO cat VALUES (NULL, 'Tiffany', 3.4);INSERT INTO cat (name, weight) VALUES ('Svenson', 2.1);INSERT INTO cat SET name = 'Pika', weight = 4.2;INSERT INTO cat VALUES (NULL, 'Sonar', 2.8);INSERT INTO cat SET name = 'Mr. Olson';SELECT * FROM cat WHERE weight > 3.0;SELECT * FROM cat WHERE name LIKE '%son%';SELECT * FROM cat WHERE name != 'Tiffany';DELETE FROM cat WHERE name LIKE '%son%';SELECT name FROM cat;

Open your database, and type:SOURCE fileNameIncludingPath;

On my computer:

MariaDB>SOURCE C:/Mike/CreateCatDB.sql;

47

Page 48: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Assignment 6

Send me a script that does exactly this. Call it housedb.sql, and email it to me.

Create a database that keeps track of hoses. Call the database “hoses”.Remove the database from the system.Create a database that keeps track of houses. Call the database “houses”.

Make a table called house. Every house has color. This should be a string type. How many characters do you really need to store a color?

Add a new house to the table that is red.Add a new house to the table that is blue.

Throw away that table. It’s no good. Let’s start over.

Make a table called house. Every house has an id, which is the primary key. Make the id automatic. The database should hold at most 20,000 houses. Each house has an owner. The owner is required, and must be unique. Assume the owner’s name will have 35 or fewer characters. Each house has a number of rooms. Each house has an address. Each house has an assessment value. If unknown, the value is $100,000.00.

Display the structure of the house table only once.

Add some houses to the table.

Homer Simpson 8 rooms 742 Evergreen Terrace, NK $101,000Barack Obama 132 rooms 1600 Pennsylvania Ave, DC $292 millionOwen Skywalker 12 rooms Tatooine $50,000Jack O’Neill 7 rooms 86 Pine St. Colorado Springs, CO$78,526Bilbo Baggins 22 rooms Bag End, The Hill $78,000

Display the complete records for houses having more than 10 rooms.Display only owners who have an O in their name.Display the complete records for all houses worth more than $100,000.Remove all records having an owner with a B in their name.Display only the addresses of the houses left in the table.Remove all records from the table without removing the table.

48

Page 49: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Chapter 7: Retrieving Data Continued, Changing a Record, and Changing a Table Structure.

The following should have been included in the Week 3 notes:

When using the DROP command, to avoid errors, we can tell our DMS to remove a database or table only if it has already been created. We do this by adding an "IF EXISTS" clause.

Syntax:

DROP DATABASE IF EXISTS database;

If the database exists, it will be removed. If the database does not exist, the command will be ignored (aside from a warning).

The "IF EXISTS" clause can also be used when dropping (removing) tables within a database.

Example:

CREATE DATABASE plant;DROP DATABASE IF EXISTS palnt;DROP DATABASE IF EXISTS plant;CREATE DATABASE plant;USE plant;CREATE TABLE berries (height INT);DROP TABLE IF EXISTS berrys;DROP TABLE IF EXISTS berries;CREATE TABLE berries (height TINYINT);

This is particularly useful in a script that you might want to run many times while you are working out the details.

49

Page 50: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

There is also an opposite clause you might use: "IF NOT EXISTS"

This is handy when you are creating something, but you don’t want to re-create it if it’s already there.

CREATE DATABASE IF NOT EXISTS tree;USE tree;CREATE TABLE IF NOT EXISTS pine (height DOUBLE, needles TINYINT);

Notice that you can run this twice, and you won’t get any errors.

Finally, by using both clauses, we can make a script that will not result in any errors, even if we make changes to it, and run it multiple times.

tree.sql

CREATE DATABASE IF NOT EXISTS tree;USE tree;DROP TABLE IF EXISTS pine;CREATE TABLE pine (height DOUBLE, needles TINYINT, owner TINYTEXT);

Section I: Fancy Retrieval

Boolean OperatorsFor this section, let’s create a new database and table to hold information about ducks. The table holds an id for each duck, a weight for each duck (in pounds), a color (a text type, red, white, or blue), and an age in months.

50

Page 51: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

ddb.sql

CREATE DATABASE IF NOT EXISTS duckdatabase;USE duckdatabase;DROP TABLE IF EXISTS ducks;CREATE TABLE ducks(id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,name VARCHAR(10) UNIQUE,weight DOUBLE,color CHAR(15) DEFAULT 'red',age TINYINT);INSERT INTO ducks VALUES (NULL, 'Harry', 0.9, 'red', 14);INSERT INTO ducks VALUES (NULL, 'Stan', 1.8, 'red', 18);INSERT INTO ducks VALUES (NULL, 'Shelly', 2.1, 'blue', 24);INSERT INTO ducks VALUES (NULL, 'Chelsea', 1.3, 'red', 11);INSERT INTO ducks VALUES (NULL, 'Barry', 0.8, 'red', 16);INSERT INTO ducks VALUES (NULL, 'Andy', 1.9, 'white', 21);INSERT INTO ducks VALUES (NULL, 'Lisa', 3.1, 'blue', 8);INSERT INTO ducks VALUES (NULL, 'Ellen', 2.4, 'white', 10);INSERT INTO ducks VALUES (NULL, 'Bill', 0.7, 'red', 22);INSERT INTO ducks VALUES (NULL, 'Vera', 2.2, 'blue', 9);INSERT INTO ducks VALUES (NULL, 'Betty', 1.0, 'white', 25);INSERT INTO ducks VALUES (NULL, 'Greta', 2.5, 'blue', 14);INSERT INTO ducks VALUES (NULL, 'Larry', 0.9, 'red', 12);

This script will create the following table:

+----+---------+--------+-------+------+| id | name | weight | color | age |+----+---------+--------+-------+------+| 1 | Harry | 0.9 | red | 14 || 2 | Stan | 1.8 | red | 18 || 3 | Shelly | 2.1 | blue | 24 || 4 | Chelsea | 1.3 | red | 11 || 5 | Barry | 0.8 | red | 16 || 6 | Andy | 1.9 | white | 21 || 7 | Lisa | 3.1 | blue | 8 || 8 | Ellen | 2.4 | white | 10 || 9 | Bill | 0.7 | red | 22 || 10 | Vera | 2.2 | blue | 9 || 11 | Betty | 1 | white | 25 || 12 | Greta | 2.5 | blue | 14 || 13 | Larry | 0.9 | red | 12 |+----+---------+--------+-------+------+

51

Page 52: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Now, suppose we want to list only the ducks that have a weight less than 2 pounds.

SELECT * FROM ducks WHERE weight < 2.0;

+----+---------+--------+-------+------+| id | name | weight | color | age |+----+---------+--------+-------+------+| 1 | Harry | 0.9 | red | 14 || 2 | Stan | 1.8 | red | 18 || 4 | Chelsea | 1.3 | red | 11 || 5 | Barry | 0.8 | red | 16 || 6 | Andy | 1.9 | white | 21 || 9 | Bill | 0.7 | red | 22 || 11 | Betty | 1 | white | 25 || 13 | Larry | 0.9 | red | 12 |+----+---------+--------+-------+------+

We’ve done that before. But, what if we want to list only the ducks that have a weight between one and two pounds? What if we want to list all of the ducks that are not in their prime (less than one year old, or more than two years old)? Can we list all ducks that are not red? This is where the Boolean operators (AND, OR, and NOT) are very useful.

The AND OperatorWhen two criteria are AND’ed together, the resulting search shows only rows where both criteria are true.

SELECT * FROM ducks WHERE weight > 1.0 AND weight < 2.0;

+----+---------+--------+-------+------+| id | name | weight | color | age |+----+---------+--------+-------+------+| 2 | Stan | 1.8 | red | 18 || 4 | Chelsea | 1.3 | red | 11 || 6 | Andy | 1.9 | white | 21 |+----+---------+--------+-------+------+

SQL will also recognize && as an AND operator.

SELECT * FROM ducks WHERE weight > 1.0 && weight < 2.0;

52

Page 53: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

The OR OperatorWhen two criteria are OR’ed together, the resulting search shows all rows where either one is true.

SELECT * FROM ducks WHERE age < 12 OR age > 24;

+----+---------+--------+-------+------+| id | name | weight | color | age |+----+---------+--------+-------+------+| 4 | Chelsea | 1.3 | red | 11 || 7 | Lisa | 3.1 | blue | 8 || 8 | Ellen | 2.4 | white | 10 || 10 | Vera | 2.2 | blue | 9 || 11 | Betty | 1 | white | 25 |+----+---------+--------+-------+------+

SQL will also recognize || as an OR operator.

SELECT * FROM ducks WHERE age < 12 || age > 24;

Order Of OperationsKeep in mind that AND operators are always evaluated before OR operators. You can force a specific order by using parentheses. If in doubt, use parentheses.

The NOT OperatorYou can list records that do not satisfy a constraint by using the NOT operator.

SELECT * FROM ducks WHERE NOT(color = 'red');

+----+--------+--------+-------+------+| id | name | weight | color | age |+----+--------+--------+-------+------+| 3 | Shelly | 2.1 | blue | 24 || 6 | Andy | 1.9 | white | 21 || 7 | Lisa | 3.1 | blue | 8 || 8 | Ellen | 2.4 | white | 10 || 10 | Vera | 2.2 | blue | 9 || 11 | Betty | 1 | white | 25 || 12 | Greta | 2.5 | blue | 14 |+----+--------+--------+-------+------+I suggest that you always use parentheses when employing the NOT operator. The use of Boolean operators can be tricky.

53

Page 54: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

ORDER BYThis clause sorts your results. You can choose a field to sort by.

SELECT * FROM ducks ORDER BY age;

+----+---------+--------+-------+------+| id | name | weight | color | age |+----+---------+--------+-------+------+| 7 | Lisa | 3.1 | blue | 8 || 10 | Vera | 2.2 | blue | 9 || 8 | Ellen | 2.4 | white | 10 || 4 | Chelsea | 1.3 | red | 11 || 13 | Larry | 0.9 | red | 12 || 12 | Greta | 2.5 | blue | 14 || 1 | Harry | 0.9 | red | 14 || 5 | Barry | 0.8 | red | 16 || 2 | Stan | 1.8 | red | 18 || 6 | Andy | 1.9 | white | 21 || 9 | Bill | 0.7 | red | 22 || 3 | Shelly | 2.1 | blue | 24 || 11 | Betty | 1 | white | 25 |+----+---------+--------+-------+------+

By default, the records will be shown in ascending order. You could make that explicit with the ASC qualifier.

SELECT * FROM ducks ORDER BY age ASC;

Or, you can list rows in a descending order.

SELECT * FROM ducks ORDER BY age DESC;

54

Page 55: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

LIMITYou can add a LIMIT clause to request a maximum number of results.

SELECT * FROM ducks LIMIT 5;

Or

SELECT * FROM ducks WHERE color = 'red' LIMIT 3;

This is obviously useful if you want to show the 50 most recent posts on a website.

SELECT * FROM posts ORDER BY time LIMIT 50;

But, it can also come in handy if you want to remove the 10 least recent posts.

DELETE FROM posts ORDER BY time DESC LIMIT 10;

LIMIT works for SELECT, DELETE, and UPDATE. Add it to your toolbox.

Section II: Changing a Record (UPDATE)

The UPDATE command is used to change data in an existing record (row). For example, in our ducks table, Andy the duck has a weight of 1.9 pounds. What if he gained some weight? How do we change an existing record? We use the UPDATE command.

UPDATE ducks SET weight = 2.2 WHERE name = 'Andy';

Of course, things can get complicated. You can change more than one field at a time. You should separate field assignments with a comma.

UPDATE ducks SET weight = 2.5, age = 23 WHERE name = 'Andy';

You can change as many things as you like. You only need one SET statement before your changes. The WHERE clause can be as complicated as you like.

Section III: Changing a Table (ALTER)What do you do if you want to change an existing table, and still keep all of the data it contains? The answer is: Use the ALTER command.

55

Page 56: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

You can use ALTER with, CHANGE, MODIFY, ADD, or DROP.

(You can also use ALTER to add a primary key, or index, or remove a key.)

CHANGEThe CHANGE clause allows you to rename a field. You also need to specify a type, and any other clauses or constraints that you want. Let’s say we want to rename the color field in our ducks database to duck_color, and we want to make the default color blue.

ALTER TABLE ducks CHANGE color duck_color CHAR(10) DEFAULT 'blue';

To use CHANGE, you must specify the old field name, the new field name, and the type. You must also specify (or re-specify) any constraints.

MODIFYThe MODIFY command allows you to give a field a new type and constraints, without changing the name. For example, we could make the weight a FLOAT. Note that when using CHANGE or MODIFY, the existing data will stay intact provided that the new data type can hold it.

ALTER TABLE ducks MODIFY weight FLOAT;

ADDYou can add a new column to an existing table using the ADD command. Let’s assume we want all of our ducks to have a home state.

ALTER TABLE ducks ADD state CHAR(2);

DROPFinally, maybe we don’t care how old our ducks are. We can remove a field (column) completely by using the DROP command.

ALTER TABLE ducks DROP age;

56

Page 57: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

SELECT * FROM ducks;+----+---------+--------+------------+-------+| id | name | weight | duck_color | state |+----+---------+--------+------------+-------+| 1 | Harry | 0.9 | red | NULL || 2 | Stan | 1.8 | red | NULL || 3 | Shelly | 2.1 | blue | NULL || 4 | Chelsea | 1.3 | red | NULL || 5 | Barry | 0.8 | red | NULL || 6 | Andy | 2.5 | white | NULL || 7 | Lisa | 3.1 | blue | NULL || 8 | Ellen | 2.4 | white | NULL || 9 | Bill | 0.7 | red | NULL || 10 | Vera | 2.2 | blue | NULL || 11 | Betty | 1 | white | NULL || 12 | Greta | 2.5 | blue | NULL || 13 | Larry | 0.9 | red | NULL |+----+---------+--------+------------+-------+

Notice that using the ALTER command does not remove any data. It just changes the table structure, unless we remove (drop) an entire column.

57

Page 58: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Assignment 7Write a SQL script that will do the following. Run it, and make sure it works. If it crashes on me, you’ll get a zero. If it works, you’ll get a 100.

1. Create a database (called beverages) that has one table (called drink).

Each drink has an id (Unique and automatic), a name, a caffeine content between 0 and 1, a price, and a rating (an integer 1-5). The script should create the database and table, and enter the following drinks.

id name caffeine price rating

1 Starbucks Coffee 0.8 1.99 3

2 Daves Iced Tea 0.5 1.49 4

3 Marks Cider 0.0 1.29 5

4 Jimmys Hot Tea 0.3 2.39 4

5 Mikes Spicy Cola 0.9 4.79 1

6 Ians Enigma 0.1 0.29 5

7 Janes Addiction 0.6 8.98 3

2. Print (SELECT) the whole table so I can see it.

3. Show me all of the drinks that have a caffeine content greater than 0.2 but less than 0.7. (Another SELECT, use AND)

4. Show me all the drinks that have a caffeine rating less than 0.4 and the drinks that cost less than $2.00 in the same table. (Use OR)

5. Show me the drinks that do NOT have an “o” on their name. (Use LIKE and NOT)

6. Show me all of the drinks that have a rating greater than or equal to 4 in order of price, lowest to highest. (ORDER BY)

7. Show drinks, priced from highest to lowest, but only the first four. (ORDER BY and LIMIT)

58

Page 59: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

8. Rename “Mikes Spicy Cola” to “Mikes Awesomeness Pepstravoganza with a Twist”, and change the price to $11.82. Show just that one record. (UPDATE, SELECT, and gosh darn it, CHAR(20) isn’t big enough! Start over.)

9. Turn all ratings of 5 into ratings of 10. (UPDATE, and do it all with only one statement).

10. Change the “rating” column to an “awesome” column. (ALTER)

11. Add a column for pizazz (1 to 10). (ALTER)

12. Remove the caffeine field. (ALTER)

13. Print the structure of the table (SHOW, DESCRIBE, or DESC).

14. Print the entire table.

59

Page 60: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Chapter 8: Multiple Tables.

Database Section I: A New Design…

Let’s look at a table that holds information about people and the pets they have.

petpeople

id first m last tel state pet_type

name

1 Mal F Reynolds

802-694-3829 VT dog Fido

2 River G Tam 413-662-8536 MA cat Fluffy3 Mal F Reynold

s802-694-3829 VT cat Snowball

4 Jayne

B Cobb 413-689-2104 MA fish Vera

5 River G Tam 413-662-8536 MA cat Smokey6 River G Tam 413-662-8536 MA dog Spot7 Jayn

eB Cobb 413-689-2104 MA cat Snuggles

8 River G Tam 413-662-8536 MA fish Blackey9 River G Tam 413-662-8536 MA dog Spike10 Mal F Reynold

s802-694-3829 VT cat Tiger

11 Jayne

B Cobb 413-689-2104 MA cat Oreo

12 River G Tam 413-662-8536 MA dog Sparky

Each person has an id, a first name, a middle initial, a last name, a telephone number, and a state. Each pet has a type (dog, cat, or fish), and a name. With 12 rows and 8 columns, we have 96 fields to store.

You might notice that the table above stores the same information in multiple places. In a small table, this redundancy isn’t a big deal. However, if we were storing information about thousands, or millions, or billions of people, our database would be very inefficient. We would be wasting a lot of disk space, and searches would a lot of time.

60

Page 61: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

These days, if we click on a link, and have to wait 10 seconds to see our search results, we get impatient. With a database structure like the one above, we might have to wait 100 seconds, or even 1000 seconds. No one is going to wait for one and a half minutes, and they certainly won’t wait for 15 minutes! We’d assume the web page is broken, and move on. How can we make our database more efficient?

We could store all of our information in one table, like the table above. This is called a “flat file database”. People stopped using those decades ago. Now, everyone uses “relational databases”. A relational database has multiple tables, and the tables are related to each other by using keys.

Here’s another way we could store the same information.

person pet

id first m last tel state1 Mal F Reynolds 802-694-3829 VT2 River G Tam 413-662-8536 MA3 Jayne B Cobb 413-689-2104 MA

Now, we have two tables. The first has 18 fields, and the second has 36. That’s a total of only 54 fields instead of 96. That isn’t a big deal with such a small amount of information, but in a real application the difference is extremely important.

The id in the first table (person), is a primary key. The id in the second table (pet), is called a foreign key. Notice that it is not unique. It is used to create the relationship between the two tables. Given any person in the “person” table, we can find their pets by using their id in the “pet” table.

61

id pet_type

name

1 dog Fido2 cat Fluffy1 cat Snowball3 fish Vera2 cat Smokey1 dog Spot3 cat Snuggles2 fish Blackey2 dog Spike1 cat Tiger3 cat Oreo2 dog Sparky

Page 62: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Now, we can draw a useful Entity Relationship Diagram (ERD). We draw a box for each table showing the fields, and connect them with a line. In this case, we want to depict a “one-to-many” relationship. One person can have many pets. We connect a single line to the person table. The line connected to the pet table, is split. This is often called a crow’s foot. It is the notation we use to show that many objects on the right table might be associated with one object on the left table.

One person may have many pets. Each pet has only one person. You are welcome to disagree with that statement on a philosophical level, but the point is that this is how we are modeling this particular database. It’s just an example. (It’s not a statement concerning the fairness of humans having ownership of non-humans, nor does it imply that a pet can only care for one person.)

One person has many (0 or more) pets. This is a one-to-many relationship.

This raises an interesting question. When we are storing data in a database, how do we know how many tables to make? Put another way, which things are fields in a table, and which things should be represented by their own table?

Section II: Entity or AttributeAn entity gets its own table. An attribute is just a field in an existing table. So, how do we decide if a piece of data is an entity (table), or an attribute (field in a table)?

Here are a few guidelines:

There are actually nine rules (forms) of database normalization. You are not required to know them all. You are welcome to research the finer points if you want to. The following guidelines are all you need for most database designs.

62

person

id INTfirst CHAR(20)m CHAR(1)last CHAR(20)tel CHAR(12)state CHAR(2)

pets

id INTpet_type CHAR(10)name CHAR(15)

Page 63: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Guideline 1. If the item in question has multiple instances, that is, if there are more than one things that could be placed in the field, it is probably best to make a separate table. In the example above, each person might have several pets. We don’t know how many pets each person will have. It makes sense to make a separate table just for pets. Otherwise, we violate the first normal form (1NF).

Guideline 2. If the item in question has related data specific to it, it should be modeled as a separate entity (table). In the example above, a pet also has a pet name. It makes sense to make a separate table just for pets. Otherwise, we violate the second normal form (2NF)

Guideline 3. If a field is often left empty, it might be best to make a separate table.

Let’s look at a few examples.

Example 1. Let’s make a database structure that stores people and phone numbers.If we really want to store only one phone number for each person, one table will do. On the other hand, if we want to store multiple phone numbers for each person, we should make a separate table for phone numbers.

Here is a poor design:

id first last Number1 Number2 Number31 Bob Bobson 413-662-66032 Jane Janski 802-364-5342 617-552-7463 802-364-65373 Sam Samson

According to guideline 1 (and 1NF), we should make a separate table just for phone numbers. In addition, we have a lot of empty fields. According to guideline 3, we should make a separate table.

Here’s a better solution.

person phone

63

Page 64: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

ERD: One person has many phone numbers

Example 2. Let’s make a database structure that stores hats. Each hat has a type (string), a size (int), and a manufacturer (string).

hatid type size manufacturer1 Beret 11 Greens Berets2 Bowler 12 Sues hat shop3 Fedora 9 Habers Dasher4 Baseball 5 Red Socks Tops5 Top 16 Abes Place

Should we give the manufacturer a separate table? No. But, what if each manufacturer has related data that might be repeated?

hat

id type size manufacturer manufacturers_address1 Beret 11 Greens Berets 12 Green St2 Cap 6 Greens Berets 12 Green St

64

person

id INTfirst CHAR(15)last CHAR(20)

phone

id INTtype CHAR(10)number CHAR(12)

id type number2 home 802-364-53421 cell 413-662-66302 work 617-552-74632 cell 802-364-6537

id first last1 Bob Bobson2 Jane Janski3 Sam Samson

Page 65: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

3 Bowler 12 Sues Hat Shop 5th Ave4 Cap 10 Sues Hat Shop 5th Ave5 Fedora 9 Habers Dasher 101 Hat Rd6 Baseball 5 Red Socks Tops 4 Yawkey Way7 Fedora 7 Red Socks Tops 4 Yawkey Way8 Top 16 Abes Place KC Farm

In this case, each manufacturer has an address. It makes sense to have a hat table, and a separate table for each manufacturer because (according to Guideline 2), each manufacturer has some related information.

ERD: One manufacturer has many hats

It is important to understand that the creation of additional tables comes with a price. The id must be stored twice, and since the database structure is more complicated, the database will be harder to update, query, and maintain. For a small business with 12 accounts, it might be simpler to ignore the guidelines I’ve suggested, and to ignore the rules of normalization. On the other hand, if you are creating a database structure for a bank, or a major website, you’ll want to follow these rules to make your design as efficient as possible. For this course, design efficient databases. In real life (IRL), use your own judgement.

Section III: Creating a Database with Multiple TablesLet’s go back to our example in Section I. An assignment or exam question might be worded:

1. Draw an ERD that represents people and pets. Each person might zero or more pets. Each pet belongs to only one person. Each person has a first name (required), a

65

hat

id INTtype CHAR(15)size TINYINT

manufacturer

id INTname CHAR(20)address CHAR(30)

Page 66: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

middle initial (optional), a last name (required), a telephone number (optional), and a state abbreviation (required). Each pet has a type (required) and a name (required).

2. Write the SQL code to build the database and tables. Add primary and foreign keys where appropriate.

3. Write the SQL code to add the following people:

Mal F. Reynolds 802-694-3829 VTRiver G. Tam 413-662-8536 MAJayne B. Cobb 413-689-2104 MA

66

Page 67: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

4. Write the SQL code to add the following pets for people (including the data above).

Mal dog FidoRiver cat FluffyMal cat Snowball

5. Show the data in all tables.

First, we need to infer that we’re talking about a one-to-many relationship, whether that is explicit or implied.

On a real job, your customer might not know anything about database design. You’ll be expected to choose a fitting structure. In this example, it’s pretty obvious.

Next, we need to notice that the main table does not have a primary key. We’ll add one. Finally, we need to put a foreign key in the second table.

1.

67

person

id INTfirst CHAR(20)m CHAR(1)last CHAR(20)tel CHAR(12)state CHAR(2)

pet

id INTtype CHAR(10)name CHAR(15)

Page 68: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

2-5.

DROP DATABASE IF EXISTS petpeople;

CREATE DATABASE petpeople;

USE petpeople;

CREATE TABLE person (id INT PRIMARY KEY AUTO_INCREMENT, first CHAR(20) NOT NULL,m CHAR(1),last CHAR(20) NOT NULL,tel CHAR(12),state CHAR(2) NOT NULL);

CREATE TABLE pet (id INT NOT NULL,type CHAR(10) NOT NULL,name CHAR(15) NOT NULL);

INSERT INTO person VALUES (NULL, 'Mal', 'F', 'Reynolds', '802-694-3829', 'VT');INSERT INTO person VALUES (NULL, 'River', 'G', 'Tam', '413-662-8536', 'MA');INSERT INTO person VALUES (NULL, 'Jayne', 'B', 'Cobb', '413-689-2104', 'MA');

INSERT INTO pet VALUES (1, 'dog', 'Fido');INSERT INTO pet VALUES (2, 'cat', 'Fluffy');INSERT INTO pet VALUES (1, 'cat', 'Snowball');

SELECT * FROM person;SELECT * FROM pet;

Assignment 81. Draw an ERD that represents ships and crew members. Each ship might have several crew members. Each crew member belongs to only one ship. Every ship has a name (required), a color (optional), and a weight (required). Each crew member has a rank (such as Captain, Quarter Master, Cook, or Gunner) (required), a first name (optional), and a last name (required).

2. Write the SQL code to build the database and tables. Add primary and foreign keys where appropriate.

3. Enter the following data appropriately.

The Mayflower is brown, weighs 2000 pounds, and is commanded by Chris Columbus. The Quarter Master is John Smith. The Cook is Sam Cook, and the Gunner’s last name is Gunmann.

The Enterprise is white, it weighs 35,000 pounds, and it’s Captain is Jean-Luc Picard. The Gunner’s last name is Worf. The cooks are called Guinan (last name only), and Gordon Ramsay. William Riker serves as the Quarter Master.

The Pheonix was commanded by Zefram Cochrane. It weighed 3500 pounds. It had no crew.

68

Page 69: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

The Prometheus had 3 cooks; Daniel Jackson, Samantha Carter, and Jack O’Neill. It weighed 24,850 lbs, The Gunner was simply called Tealc, and the captain was George Hammond.

The Millennium Falcon has a gunner named Chewie. The cook is also Chewie. It weighs 200,000 pounds and it’s silver. The Captain is Han Solo. Let’s say that Luke Skywalker is the Quarter Master.

Serenity Weighs 282,500 pounds. It is commanded by Malcolm Reynolds. Derrial Book makes the food, and Jayne Cobb and Zoe Washburne shoot at people. Zoe is also the second in command, so let’s call her the Quarter Master. It’s pretty much a silver-ish color.

Draw an ERD for number one, and write a single script for two and three. Email them to me, or put them in my mailbox. Make sure the code works.

Good Luck & Have Fun

69

Page 70: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Chapter 9: Complex Relationships.

Section I: A more realistic database

Let’s look at a table that holds information about people and their items in an on-line game.

coolcraft

id name character level itemname itemlevel itembonus value1 Sam Simon Dr. Awesome 22 Dagger 8 +2 Attack 10G2 Pat Potts Broc 11 Hat 2 None 1G1 Sam Simon Dr. Awesome 22 Hero Sword 15 +10 Dam 80G3 Timmie Tam Vlad 16 Dagger 8 +2 Attack 10G3 Timmie Tam Vlad 16 Cape 5 +1 Speed 8G1 Sam Simon Dr. Awesome 22 Hat 2 None 1G2 Pat Potts Broc 11 Gloves 7 +1 Attack 4G1 Sam Simon Dr. Awesome 22 Cool Shoes 10 +3 Speed 5G3 Timmie Tam Vlad 16 Bees Belt 18 +5 Attack 50G2 Pat Potts Broc 11 Cool Shoes 10 +3 Speed 5G1 Sam Simon Dr. Awesome 22 Cape 5 +1 Speed 8G2 Pat Potts Broc 11 Dagger 8 +2 Attack 10G3 Timmie Tam Vlad 16 Hat 2 None 1G1 Sam Simon Dr. Awesome 22 Bees Belt 18 +5 Attack 50G3 Timmie Tam Vlad 16 Gloves 7 +1 Attack 4G2 Pat Potts Broc 11 Cape 5 +1 Speed 8G1 Sam Simon Dr. Awesome 22 Gloves 7 +1 Attack 4G

ERD

Obviously, we are storing the same values multiple times. This database is not following the rules we talked about earlier. We could make a one-to-many relationship. We could have one table for users, and another for items.

70

coolcraft

id BIGINT PRIMARY KEYname CHAR(20) NOT NULL, UNIQUEcharacter CHAR(20) NOT NULLlevel TINYINTitemname CHAR(20) NOT NULL, UNIQUEitemlevel TINYINTitembonus CHAR(10)value TINYINT

Page 71: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

user item

id name character level1 Sam Simon Dr. Awesome 222 Pat Potts Broc 113 Timmie Tam Vlad 16

ERD

This is better, but we still have redundant information in the second table. A situation like this calls for a many-to-many relationship. This is done by creating one table for users, one table for items, and a third table that connects them.

A situation like this calls for a many-to-many relationship. It requires a connecting table. I know this is redundant. It’s so important that I said it twice.

71

user

id BIGINT PRIMARY KEYname CHAR(20) NOT NULL, UNIQUEcharacter CHAR(20) NOT NULLlevel TINYINT

item

id INT FOREIGN KEYitemname CHAR(20) NOT NULL, UNIQUEitemlevel TINYINTitembonus CHAR(10)value TINYINT

id name level bonus value1 Dagger 8 +2 Attack 10G2 Hat 2 None 1G1 Hero Sword 15 +10 Dam 80G3 Dagger 8 +2 Attack 10G3 Cape 5 +1 Speed 8G1 Hat 2 None 1G2 Gloves 7 +1 Attack 4G1 Cool Shoes 10 +3 Speed 5G3 Bees Belt 18 +5 Attack 50G2 Cool Shoes 10 +3 Speed 5G1 Cape 5 +1 Speed 8G2 Dagger 8 +2 Attack 10G3 Hat 2 None 1G1 Bees Belt 18 +5 Attack 50G3 Gloves 7 +1 Attack 4G2 Cape 5 +1 Speed 8G1 Gloves 7 +1 Attack 4G

Page 72: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Creating a many-to-many relationship using a connecting table

user inventory Item

id name character level1 Sam Simon Dr. Awesome 222 Pat Potts Broc 113 Timmie Tam Vlad 16

user item

1 12 21 33 13 41 22 51 63 72 61 42 13 21 73 52 41 5

id name level bonus value1 Dagger 8 +2 Attack 102 Hat 2 None 13 Hero Sword 15 +10 Dam 804 Cape 5 +1 Speed 85 Gloves 7 +1 Attack 46 Cool Shoes 10 +3 Speed 57 Bees Belt 18 +5 Attack 50

One user might have many items. One item might belong to many users.

ERD

Is this all a bunch of fluff that I’ve put together to impress you? That’s a fair question. Let’s look at some numbers.

Let’s assume we have an on-line game with 2 million users. The game has 500 items. Each user, on average, has 20 items. Those are realistic numbers. If you don’t agree, pick numbers that you like, and run your own analysis.

Flat-file Database:

72

user

id BIGINT PRIMARY KEYname CHAR(20) NOT NULL, UNIQUEcharacter CHAR(20) NOT NULLlevel TINYINT

item

id SMALLINT PRIMARY KEYitemname CHAR(20) NOT NULL, UNIQUEitemlevel TINYINTitembonus CHAR(10)value TINYINT

inventory

user BIGINTitem SMALLINT

Page 73: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

We’ll have 2,000,000 users, 20 rows for each, and 8 columns in each row.

2,000,000 x 20 x 8 = 320,000,000 320 million fields!Relational Database:

users: 2,000,000 users, and 4 fields each.items: 500 items, and 5 fields each.inventory: 2,000,000 users with 20 items, 2 fields.

2,000,000 x 4 +500 x 5 +2,000,000 x 20 x 2

That’s only about 88 million fields.

So, the flat file database has about four times the fields. But we haven’t really considered storage, because some of these fields take more space than others. Let’s do a more detailed analysis.

Flat-file Database:

We’ll have 2,000,000 users, 20 rows for each.

id BIGINT 8 Bytesname CHAR(20) 20 Bytescharacter CHAR(20) 20 Byteslevel TINYINT 1 Byteitemname CHAR(20) 20 Bytesitemlevel TINYINT 1 Byteitembonus CHAR(10) 10 Bytesvalue TINYINT 1 Byte

Each row uses 81 Bytes.

40,000,000 rows x 81 Bytes = 3.24 Billion Bytes

Relational Database:

user: 49 Bytes per rowItem: 34 Bytes per rowInventory: 10 Bytes per row

Totals:user: 2,000,000 rows x 49 Bytes = 98,000,000 Bytesitem: 500 rows x 34 Bytes = 17,000 Bytesinventory: 20,000,000 rows x 10 Bytes = 200,000,000 Bytes

289,017,000 Bytes ≈ 2.89 Million Bytes73

Page 74: Chapter 1: Databases - Massachusetts College of Liberal Artsjedi.cs.mcla.edu/CSCI 243 Database Textbook.docx  · Web viewSome people pronounce it “es-que-el”, and others just

Flat File Database – More than 3 Billion BytesRelational Database – Less than 300 Million Bytes.Using the same hard drive, we can store more than 10 times as much information using a relational database. In addition, the searches will be much faster. It’s worth the extra effort.

Real databases are even more complicated. The database systems for Facebook, Amazon, WoW, LoL, Google, Twitter, Instagram, Photobucket, etc, probably have 20 to 50 tables, and they’re all related. However, they can all be broken down using the concepts you’ve learned in this course.

Section II: Final Exam

Hints:

When you are asked to draw an ERD, you need to make a choice. Does the question call for a single entity (one table), a one-to-many relationship (two tables), or a many-to-many relationship (three tables)? It is essential that you are able to choose a model that fits the requirements. If you don’t choose correctly, you’ll probably lose points on the questions that follow.

You are expected to choose appropriate data types.

You are expected to add fields that are not given in the system description. That means, if a table needs a key, add it.

You are expected to know the following commands, and appropriate variations:

CREATE, INSERT, DROP, DELETE, SELECT, ALTER, MODIFY

You should know how to apply constraints and clauses.

WHERE, AND, OR, NOT, LIKE, UNIQUE, PRIMARY KEY, NOT NULL

If you have a good understanding of these key words and concepts, you are ready. Otherwise, you should look over the class notes.

74