+ All Categories
Home > Documents > Slide 1 of 77 Database, SQL, MySQL, CENG 449 Lecture 7.

Slide 1 of 77 Database, SQL, MySQL, CENG 449 Lecture 7.

Date post: 26-Dec-2015
Category:
Upload: alison-snow
View: 218 times
Download: 2 times
Share this document with a friend
Popular Tags:
77
Slide 1 of 77 Database, SQL, MySQL, CENG 449 Lecture 7
Transcript

CENG 449 Lecture 7 Slide 1 of 77

Database, SQL, MySQL,

CENG 449 Lecture 7 Slide 2 of 77

SQL stands for "Structured Query Language", and is just a definition of a computer language that can be used to access data stored in relational databases.

SQL is not itself a standalone computer application, but is rather part of many relational DB programs such as MySQL, Oracle, Sybase, Microsoft SQL Server, etc.

MySQL is an actual computer application you can download and install. It is the most popular open-source database management system. In addition to having an SQL interpreter, MySQL also has a database manager component, GUI database viewers, session monitoring tools, etc.

The difference between SQL and MySQL would be similar to the difference between C++ and the Visual C++ IDE; the first is just a language and the second is an actual tool that can be used to work in that language. Or similarly, the difference between HTML and Dreamweaver; HTML is just a web page standard, while Dreamweaver is a computer program that lets you create and edit and view web pages and web sites.

CENG 449 Lecture 7 Slide 3 of 77

SQL (Structured Query Language) is a standard. No actual software follows that standard to the last letter. Every software vendor has their own version (or dialect) of SQL, which may both skip some standard SQL features and offer features not present in standard SQL. Microsoft has Transact-SQL (or T-SQL), Oracle has PL/SQL, MySQL has MySQL, etc.

CENG 449 Lecture 7 Slide 4 of 77

"relational databases" and "database management" and all that is, they are just terms for one computer-efficient way to organize and retrieve _lots and lots_ of data that can be represented in a table. For example, a small mom-and-pop business may be able to keep their customer lists (with customer names, addresses, cities, zips, phone numbers, etc.) on paper, in a Word document table, or in an Excel spreadsheet and have that be manageable. However, if Amazon tried to do that with its millions (tens of millions, hundreds of millions?) of customers, paper would be unworkable and even Word and Excel keep their data in a structure that would take too long to look up a particular customer info. However, Amazon keeps their customer lists in a relational database, and the lookup would be amazingly fast, which is why your customized web page appears within seconds after you log in.

CENG 449 Lecture 7 Slide 5 of 77

Feature MySQL Series

Unions 4.0

Subqueries 4.1

R-trees 4.1 (for the MyISAM storage engine)

Stored procedures and functions 5.0

Views 5.0

Cursors 5.0

XA transactions 5.0

Triggers 5.0 and 5.1

Event scheduler 5.1 Introduced in 2008

Partitioning 5.1

Pluggable storage engine API 5.1

Plugin API 5.1

InnoDB Plugin 5.1

Row-based replication 5.1

Server log tables 5.1

CENG 449 Lecture 7 Slide 6 of 77

What is Database?A database is a separate application that stores a collection of data. Each database has one or more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.

Other kinds of data stores can be used, such as files on the file system or large hash tables in memory but data fetching and writing would not be so fast and easy with those types of systems.

So nowadays, we use relational database management systems (RDBMS) to store and manage huge volume of data. This is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as foreign keys.

A Relational DataBase Management System (RDBMS) is a software that:

Enables you to implement a database with tables, columns and indexes.Guarantees the Referential Integrity between rows of various tables.Updates the indexes automatically.Interprets an SQL query and combines information from various tables.

CENG 449 Lecture 7 Slide 7 of 77

RDBMS Terminology:• Before we proceed to explain MySQL database system, let's revise few

definitions related to database.• Database: A database is a collection of tables, with related data.• Table: A table is a matrix with data. A table in a database looks like a simple

spreadsheet.• Column: One column (data element) contains data of one and the same kind,

for example the column postcode.• Row: A row (= tuple, entry or record) is a group of related data, for example the

data of one subscription.• Redundancy: Storing data twice, redundantly to make the system faster.• Primary Key: A primary key is unique. A key value can not occur twice in one

table. With a key, you can find at most one row.• Foreign Key: A foreign key is the linking pin between two tables.• Compound Key: A compound key (composite key) is a key that consists of

multiple columns, because one column is not sufficiently unique.• Index: An index in a database resembles an index at the back of a book.• Referential Integrity: Referential Integrity makes sure that a foreign key value

always points to an existing row.

CENG 449 Lecture 7 Slide 8 of 77

MySQL Database:• MySQL is a fast, easy-to-use RDBMS being used for many small and big

businesses. MySQL is developed, marketed, and supported by MySQL AB, which is a Swedish company. MySQL is becoming so popular because of many good reasons:

• MySQL is released under an open-source license. So you have nothing to pay to use it.

• MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages.

• MySQL uses a standard form of the well-known SQL data language.• MySQL works on many operating systems and with many languages including

PHP, PERL, C, C++, JAVA, etc.• MySQL works very quickly and works well even with large data sets.• MySQL is very friendly to PHP, the most appreciated language for web

development.• MySQL supports large databases, up to 50 million rows or more in a table. The

default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB).

• MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL software to fit their own specific environments.

CENG 449 Lecture 7 Slide 9 of 77

• MySQL is a database management system.• A database is a structured collection of data. It may

be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL Server. Since computers are very good at handling large amounts of data, database management systems play a central role in computing, as standalone utilities, or as parts of other applications.

CENG 449 Lecture 7 Slide 10 of 77

• MySQL databases are relational.• A relational database stores data in separate tables

rather than putting all the data in one big storeroom. The database structures are organized into physical files optimized for speed. The logical model, with objects such as databases, tables, views, rows, and columns, offers a flexible programming environment. You set up rules governing the relationships between different data fields, such as one-to-one, one-to-many, unique, required or optional, and “pointers” between different tables. The database enforces these rules, so that with a well-designed database, your application never sees inconsistent, duplicate, orphan, out-of-date, or missing data.

CENG 449 Lecture 7 Slide 11 of 77

• MySQL software is Open Source.• Open Source means that it is possible for anyone to

use and modify the software. Anybody can download the MySQL software from the Internet and use it without paying anything. If you wish, you may study the source code and change it to suit your needs.

CENG 449 Lecture 7 Slide 12 of 77

• The MySQL Database Server is very fast, reliable, scalable, and easy to use.

• If that is what you are looking for, you should give it a try. MySQL Server can run comfortably on a desktop or laptop, alongside your other applications, web servers, and so on, requiring little or no attention. If you dedicate an entire machine to MySQL, you can adjust the settings to take advantage of all the memory, CPU power, and I/O capacity available. MySQL can also scale up to clusters of machines, networked together.

CENG 449 Lecture 7 Slide 13 of 77

The Main Features of MySQL

Written in C and C++.• Tested with a broad range of different compilers.• Works on many different platforms.

CENG 449 Lecture 7 Slide 14 of 77

History of MySQLMySQL is named after co-founder MontyWidenius's daughter, My.

The name of the MySQL Dolphin (our logo) is “Sakila,” which was chosen from a huge list of names suggested by users in our “Name the Dolphin” contest. The winning name was submitted by Ambrose Twebaze, an Open Source software developer from Swaziland, Africa. According to Ambrose, the feminine name Sakila has its roots in SiSwati, the local language of Swaziland. Sakila is also the name of a town in Arusha, Tanzania, near Ambrose's country of origin, Uganda.

CENG 449 Lecture 7 Slide 15 of 77

CENG 449 Lecture 7 Slide 16 of 77

Connecting to and Disconnecting from the ServerTo connect to the server, you will usually need to provide a MySQL user name when you invoke mysql and, most likely, a password. If the server runs on a machine other than the one where you log in, you will also need to specify a host name.

Contact your administrator to find out what connection parameters you should use to connect (that is, what host, user name, and password to use). Once you know the proper parameters, you should be able to connect like as in the next slide

CENG 449 Lecture 7 Slide 17 of 77

• shell> mysql -h host -u user –p Enter password: ********

host and user represent the host name where your MySQL server is running and the user name of your MySQL account. Substitute appropriate values for your setup. The ******** represents your password; enter it when mysql displays the Enter password: prompt.

If that works, you should see some introductory information followed by a mysql> prompt:

CENG 449 Lecture 7 Slide 18 of 77

shell> mysql -h host -u user –p Enter password: ********

Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 25338 to server version: 5.0.96-standard Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql>

The mysql> prompt tells you that mysql is ready for you to enter commands.

CENG 449 Lecture 7 Slide 19 of 77

After you have connected successfully, you can disconnect any time by typing QUIT (or \q) at themysql> prompt:

mysql> QUITByeOn Unix, you can also disconnect by pressing Control+D.

CENG 449 Lecture 7 Slide 20 of 77

Entering QueriesMake sure that you are connected to the server, as discussed in the previous section. Doing so does not in itself select any database to work with, but that is okay. At this point, it is more important to find out a little about how to issue queries than to jump right in creating tables, loading data into them, and retrieving data from them.

CENG 449 Lecture 7 Slide 21 of 77

Here is a simple command that asks the server to tell you its version number and the current date. Type it in as shown here following the mysql> prompt and press Enter:

mysql> SELECT VERSION(), CURRENT_DATE;

+----------------+------------------+| VERSION() | CURRENT_DATE |+----------------+-----------------+| 5.0.7-beta-Max | 2005-07-11 |+----------------+----------------+1 row in set (0.01 sec)mysql>

CENG 449 Lecture 7 Slide 22 of 77

A command normally consists of an SQL statement followed by a semicolon. (There are some exceptions where a semicolon may be omitted. QUIT, mentioned earlier, is one of them. We'll get to others later.)

When you issue a command, mysql sends it to the server for execution and displays the results, then prints another mysql> prompt to indicate that it is ready for another command.

mysql displays query output in tabular form (rows and columns).

CENG 449 Lecture 7 Slide 23 of 77

Keywords may be entered in any lettercase. The following queries are equivalent:

mysql> SELECT VERSION(), CURRENT_DATE;mysql> select version(), current_date;mysql> SeLeCt vErSiOn(), current_DATE;

CENG 449 Lecture 7 Slide 24 of 77

Here is another query. It demonstrates that you can use mysql as a simple calculator:

mysql> SELECT SIN(PI()/4), (4+1)*5;+------------------+------------------+| SIN(PI()/4) | (4+1)*5 |+------------------+-------------------+| 0.70710678118655 | 25 |+------------------+-------------------+1 row in set (0.02 sec)

CENG 449 Lecture 7 Slide 25 of 77

Creating and Using a Database

Use the SHOW statement to find out what databases currently exist on the server:

mysql> SHOW DATABASES;+--------------+| Database |+--------------+| mysql || test || tmp |+--------------+

If the test database exists, try to access it:

mysql> USE testDatabase changed

CENG 449 Lecture 7 Slide 26 of 77

Otherwise, you need to create it yourself:

mysql> CREATE DATABASE menagerie;

Creating a database does not select it for use; you must do that explicitly. To make menagerie the current database, use this command:

mysql> USE menagerieDatabase changed

CENG 449 Lecture 7 Slide 27 of 77

Creating the database is the easy part, but at this point it is empty, as SHOW TABLES tells you:

mysql> SHOW TABLES;Empty set (0.00 sec)

CENG 449 Lecture 7 Slide 28 of 77

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste

Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Emparedados y helados

Ana Trujillo Avda. de la Constitución 2222

México D.F. 05021 Mexico

3 Antonio Moreno Taquería

Antonio Moreno Mataderos 2312

México D.F. 05023 Mexico

4 Around the Horn

Thomas Hardy 120 Hanover Sq.

London WA1 1DP UK

5 Berglunds snabbköp

Christina Berglund

Berguvsvägen 8

Luleå S-958 22 Sweden

Database TablesA database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is a selection from the "Customers" table: The table above contains five records (one for each customer) and seven columns CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country).

CENG 449 Lecture 7 Slide 29 of 77

Use a CREATE TABLE statement to specify the layout of your table:

mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);

Once you have created a table, SHOW TABLES should produce some output:

mysql> SHOW TABLES;+-----------------------------+| Tables in menagerie |+-----------------------------+| pet |+-----------------------------+

The created table is shown in the following slide

CENG 449 Lecture 7 Slide 30 of 77

name owner species sex birth death

Table name is “pet”

CENG 449 Lecture 7 Slide 31 of 77

To verify that your table was created the way you expected, use a DESCRIBE statement:

mysql> DESCRIBE pet;+------------+----------------+-------+------+---------+-------+| Field | Type | Null | Key | Default| Extra|+------------+----------------+-------+------+---------+-------+| name | varchar(20) | YES | | NULL | || owner | varchar(20) | YES | | NULL | || species | varchar(20) | YES | | NULL | || sex | char(1) | YES | | NULL | || birth | date | YES | | NULL | || death | date | YES | | NULL | |+------------+----------------+------+-------+----------+------+

CENG 449 Lecture 7 Slide 32 of 77

SQL PRIMARY KEY ConstraintThe PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values.

A primary key column cannot contain NULL values.

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

CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),PRIMARY KEY (P_Id))

CENG 449 Lecture 7 Slide 33 of 77

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 2

4 24562 1

SQL FOREIGN KEY ConstraintA FOREIGN KEY in one table points to a PRIMARY KEY in another table.Let's illustrate the foreign key with an example. Look at the following two tables:The "Persons" table:The "Orders" table:Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.

CENG 449 Lecture 7 Slide 34 of 77

The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:

MySQL:CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,PRIMARY KEY (O_Id),FOREIGN KEY (P_Id) REFERENCES Persons(P_Id))

CENG 449 Lecture 7 Slide 35 of 77

You could add a new record using an INSERT statement like this:

mysql> INSERT INTO pet VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL);

String and date values are specified as quoted strings here. Also, with INSERT, you can insert NULL directly to represent a missing value.

After the above command the table is seen as in the next slide

CENG 449 Lecture 7 Slide 36 of 77

name owner species sex birth death

Fluffy Harold cat f 1993-02-04  

Assume that we repeat similar command and fill the table as follows

CENG 449 Lecture 7 Slide 37 of 77

name owner species sex birth death

Fluffy Harold cat f 1993-02-04  

Claws Gwen cat m 1994-03-17  

Buffy Harold dog f 1989-05-13  

Fang Benny dog m 1990-08-27  

Bowser Diane dog m 1979-08-31 1995-07-29

Chirpy Gwen bird f 1998-09-11  

Whistler Gwen bird   1997-12-09  

Slim Benny snake m 1996-04-29  

CENG 449 Lecture 7 Slide 38 of 77

Retrieving Information from a TableThe SELECT statement is used to pull information from a table. The general form of the statement is:

SELECT what_to_selectFROM which_tableWHERE conditions_to_satisfy;

what_to_select indicates what you want to see. This can be a list of columns, or * to indicate “all columns.”

which_table indicates the table from which you want to retrieve data.

The WHERE clause is optional. If it is present, conditions_to_satisfy specifies one or more conditions that rows must satisfy to qualify for retrieval.

CENG 449 Lecture 7 Slide 39 of 77

Selecting All DataThe simplest form of SELECT retrieves everything from a table:

CENG 449 Lecture 7 Slide 40 of 77

Selecting Particular Rows

CENG 449 Lecture 7 Slide 41 of 77

You can specify conditions on any column, not just name. For example, if you want to know which animals were born during or after 1998, test the birth column:

CENG 449 Lecture 7 Slide 42 of 77

You can combine conditions, for example, to locate female dogs:

CENG 449 Lecture 7 Slide 43 of 77

The preceding query uses the AND logical operator. There is also an OR operator:

CENG 449 Lecture 7 Slide 44 of 77

AND and OR may be intermixed, although AND has higher precedence than OR. If you use both operators, it is a good idea to use parentheses to indicate explicitly how conditions should be grouped:

CENG 449 Lecture 7 Slide 45 of 77

Selecting Particular Columns

If you do not want to see entire rows from your table, just name the columns in which you are interested, separated by commas. For example, if you want to know when your animals were born, select the name and birth columns:

CENG 449 Lecture 7 Slide 46 of 77

To find out who owns pets, use this query:

CENG 449 Lecture 7 Slide 47 of 77

Notice that the query simply retrieves the owner column from each record, and some of them appear more than once. To minimize the output, retrieve each unique output record just once by adding the keyword DISTINCT:

CENG 449 Lecture 7 Slide 48 of 77

You can use a WHERE clause to combine row selection with column selection. For example, to get birth dates for dogs and cats only, use this query:

CENG 449 Lecture 7 Slide 49 of 77

Sorting Rows• You may have noticed in the preceding examples that the result rows are displayed in no particular

order. It is often easier to examine query output when the rows are sorted in some meaningful way. To sort a result, use an ORDER BY clause.

• Here are animal birthdays, sorted by date:

CENG 449 Lecture 7 Slide 50 of 77

The default sort order is ascending, with smallest values first. To sort in reverse (descending) order, add the DESC keyword to the name of the column you are sorting by:

CENG 449 Lecture 7 Slide 51 of 77

You can sort on multiple columns, and you can sort different columns in different directions. For example, to sort by type of animal in ascending order, then by birth date within animal type in descending order (youngest animals first), use the following query:

CENG 449 Lecture 7 Slide 52 of 77

Pattern Matching

To find names beginning with “b”:

CENG 449 Lecture 7 Slide 53 of 77

To find names ending with “fy”:

CENG 449 Lecture 7 Slide 54 of 77

To find names containing a “w”:

CENG 449 Lecture 7 Slide 55 of 77

To find names containing exactly five characters, use five instances of the “_” pattern character:

CENG 449 Lecture 7 Slide 56 of 77

To find names beginning with “b”, use “^” to match the beginning of the name:

CENG 449 Lecture 7 Slide 57 of 77

To find names ending with “fy”, use “$” to match the end of the name:

CENG 449 Lecture 7 Slide 58 of 77

To find names containing a “w”, use this query:

CENG 449 Lecture 7 Slide 59 of 77

Counting RowsDatabases are often used to answer the question, “How often does a certain type of data occur in a table?” For example, you might want to know how many pets you have, or how many pets each owner has, or you might want to perform various kinds of census operations on your animals.

Counting the total number of animals you have is the same question as “How many rows are in the pet table?” because there is one record per pet. COUNT(*) counts the number of rows, so the query to count your animals looks like this:

CENG 449 Lecture 7 Slide 60 of 77

Earlier, you retrieved the names of the people who owned pets. You can use COUNT() if you want to find out how many pets each owner has:

CENG 449 Lecture 7 Slide 61 of 77

Number of animals per species:

CENG 449 Lecture 7 Slide 62 of 77

Number of animals per sex:

CENG 449 Lecture 7 Slide 63 of 77

Number of animals per combination of species and sex:

CENG 449 Lecture 7 Slide 64 of 77

You need not retrieve an entire table when you use COUNT(). For example, the previous query, when performed just on dogs and cats, looks like this:

CENG 449 Lecture 7 Slide 65 of 77

Some more SQL commands will be studies for the following table

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste

Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Emparedados y helados

Ana Trujillo Avda. de la Constitución 2222

México D.F. 05021 Mexico

3 Antonio Moreno Taquería

Antonio Moreno Mataderos 2312

México D.F. 05023 Mexico

4 Around the Horn

Thomas Hardy 120 Hanover Sq.

London WA1 1DP UK

5 Berglunds snabbköp

Christina Berglund

Berguvsvägen 8

Luleå S-958 22 Sweden

CENG 449 Lecture 7 Slide 66 of 77

The SQL UPDATE Statement:

The UPDATE statement is used to update existing records in a table.

SQL UPDATE Syntax:

UPDATE table_name SET column1=value1,column2=value2, WHERE some_column=some_value;

Example:UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg‘ WHERE CustomerName='Alfreds Futterkiste';

CENG 449 Lecture 7 Slide 67 of 77

SQL DELETE StatementThe DELETE statement is used to delete records in a table.

SQL DELETE SyntaxDELETE FROM table_nameWHERE some_column=some_value;

Example:DELETE FROM CustomersWHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders';

CENG 449 Lecture 7 Slide 68 of 77

SQL DROP INDEX, DROP TABLE, and DROP DATABASE

Indexes, tables, and databases can easily be deleted/removed with the DROP statement.

DROP TABLE table_name

CENG 449 Lecture 7 Slide 69 of 77

SQL DROP INDEX, DROP TABLE, and DROP DATABASE

Indexes, tables, and databases can easily be deleted/removed with the DROP statement.

DROP TABLE table_nameDROP DATABASE database_name

What if we only want to delete the data inside the table, and not the table itself?

Then, use the TRUNCATE TABLE statement:

TRUNCATE TABLE table_name

CENG 449 Lecture 7 Slide 70 of 77

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

To add a column in a table, use the following syntax:

ALTER TABLE table_name ADD column_name datatype

To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):

ALTER TABLE table_name DROP COLUMN column_name

CENG 449 Lecture 7 Slide 71 of 77

EXAMPLES:

Now we want to add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons ADD DateOfBirth date

Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons ALTER COLUMN DateOfBirth year

Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-digit or four-digit format.

Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons DROP COLUMN DateOfBirth

CENG 449 Lecture 7 Slide 72 of 77

AUTO INCREMENT a FieldVery often we would like the value of the primary key field to be created automatically every time a new record is inserted.

We would like to create an auto-increment field in a table.

CREATE TABLE Persons(ID int NOT NULL AUTO_INCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),PRIMARY KEY (ID))

CENG 449 Lecture 7 Slide 73 of 77

MySQL Data Types• In MySQL there are three main types : text,

number, and Date/Time types.• Text types:

CENG 449 Lecture 7 Slide 74 of 77

Data type DescriptionCHAR(size) Holds a fixed length string (can contain letters, numbers, and special

characters). The fixed size is specified in parenthesis. Can store up to 255 characters

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

TINYTEXT Holds a string with a maximum length of 255 characters

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

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

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

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

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

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

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

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

CENG 449 Lecture 7 Slide 75 of 77

Data type DescriptionTINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits

may be specified in parenthesis

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

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

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

BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis

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

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

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

Number types:

CENG 449 Lecture 7 Slide 76 of 77

SQL Functions

SQL Aggregate FunctionsSQL aggregate functions return a single value, calculated from values in a column.Useful aggregate functions:

AVG() - Returns the average valueCOUNT() - Returns the number of rowsFIRST() - Returns the first valueLAST() - Returns the last valueMAX() - Returns the largest valueMIN() - Returns the smallest valueSUM() - Returns the sum

SQL Scalar functionsSQL scalar functions return a single value, based on the input value.

Useful scalar functions:

UCASE() - Converts a field to upper caseLCASE() - Converts a field to lower caseMID() - Extract characters from a text fieldLEN() - Returns the length of a text fieldROUND() - Rounds a numeric field to the number of decimals specifiedNOW() - Returns the current system date and timeFORMAT() - Formats how a field is to be displayed

CENG 449 Lecture 7 Slide 77 of 77

The AVG() FunctionThe AVG() function returns the average value of a numeric column.

SQL AVG() Syntax

SELECT AVG(column_name) FROM table_name

SELECT AVG(daily_typing_pages) FROM employee_tbl;


Recommended