0% found this document useful (0 votes)
5 views

MySQL

Mysql topic

Uploaded by

camsmith.gags
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

MySQL

Mysql topic

Uploaded by

camsmith.gags
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

What is a 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 type of
systems.

So now a days we use relational database management systems (RDBMS) to store and
manager 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.

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 (field name) 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 cannot 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.

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.
MySQL Data Types

Properly defining the fields in a table is important to the overall optimization of your
database. You should use only the type and size of field you really need to use; don't define a
field as 10 characters wide if you know you're only going to use 2 characters. These types of
fields (or columns) are also referred to as data types, after the type of data you will be storing in
those fields.

MySQL uses many different data types, broken into three categories: numeric, date and
time, and string types.

Numeric Data Types:

MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL
from a different database system, these definitions will look familiar to you. The following list
shows the common numeric data types and their descriptions.

• INT - A normal-sized integer that can be signed or unsigned. If signed, the allowable
range is from -2147483648 to 2147483647. If unsigned, the allowable range is from 0 to
4294967295. You can specify a width of up to 11 digits.
• TINYINT - A very small integer that can be signed or unsigned. If signed, the allowable
range is from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can
specify a width of up to 4 digits.
• SMALLINT - A small integer that can be signed or unsigned. If signed, the allowable range
is from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You can
specify a width of up to 5 digits.
• MEDIUMINT - A medium-sized integer that can be signed or unsigned. If signed, the
allowable range is from -8388608 to 8388607. If unsigned, the allowable range is from 0 to
16777215. You can specify a width of up to 9 digits.
• BIGINT - A large integer that can be signed or unsigned. If signed, the allowable range is
from -9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is
from 0 to 18446744073709551615. You can specify a width of up to 11 digits.
• FLOAT(M,D) - A floating-point number that cannot be unsigned. You can define the
display length (M) and the number of decimals (D). This is not required and will default to
10,2, where 2 is the number of decimals and 10 is the total number of digits (including
decimals). Decimal precision can go to 24 places for a FLOAT.
• DOUBLE(M,D) - A double precision floating-point number that cannot be unsigned. You
can define the display length (M) and the number of decimals (D). This is not required
and will default to 16,4, where 4 is the number of decimals. Decimal precision can go to
53 places for a DOUBLE. REAL is a synonym for DOUBLE.
• DECIMAL(M,D) - An unpacked floating-point number that cannot be unsigned. In
unpacked decimals, each decimal corresponds to one byte. Defining the display length
(M) and the number of decimals (D) is required. NUMERIC is a synonym for DECIMAL.

Date and Time Types:


The MySQL date and time datatypes are:
• 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.
String Types:
Although numeric and date types are fun, most data you'll store will be in string format. This
list describes the common string data types in MySQL.
• CHAR(M) - A fixed-length string between 1 and 255 characters in length (for example
CHAR(5)), right-padded with spaces to the specified length when stored. Defining a
length is not required, but the default is 1.
• VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for
example VARCHAR(25). You must define a length when creating a VARCHAR field.
• BLOB or TEXT - A field with a maximum length of 65535 characters. BLOBs are "Binary
Large Objects" and are used to store large amounts of binary data, such as images or
other types of files. Fields defined as TEXT also hold large amounts of data; the difference
between the two is that sorts and comparisons on stored data are case sensitive on
BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or
TEXT.
• TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum length of 255 characters.
You do not specify a length with TINYBLOB or TINYTEXT.
• MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a maximum length of
16777215 characters. You do not specify a length with MEDIUMBLOB or MEDIUMTEXT.
• LONGBLOB or LONGTEXT - A BLOB or TEXT column with a maximum length of 4294967295
characters. You do not specify a length with LONGBLOB or LONGTEXT.
• ENUM - An enumeration, which is a fancy term for list. When defining an ENUM, you are
creating a list of items from which the value must be selected (or it can be NULL). For
example, if you wanted your field to contain "A" or "B" or "C", you would define your
ENUM as ENUM ('A', 'B', 'C') and only those values (or NULL) could ever populate that
field.
Overview of User Interfaces

You have various options as to the user interface or client to MySQL that you choose to
use. The three most popular user interfaces are the command-line interface mysql (also known
as the MySQL monitor), MySQL Control Center (MySQLCC for short), and phpMyAdmin.

The MySQL monitor comes with your basic installation. It is a command-line interface. This
is always available as an option, it is simple to use, and it works on all platforms.

The MySQL Control Center (MySQLCC) is a graphical user interface. It is written using the
Qt windowing toolkit, which is cross-platform. At the time of writing, MySQLCC was available for
Unix and Windows, and it is planned to be available for OS X in the future.

phpMyAdmin is a Web-based interface for using MySQL. It is very popular with ISPs that
supply MySQL for use in developing Web applications.

If you have MySQL installed, you already have the MySQL monitor. MySQLCC is an official
MySQL product, but depending on which MySQL version you have, it may be a separate
download. You can get it from

Introduction to the MySQL Monitor

 We will now cover the basic use of the MySQL monitor.


 Just as a reminder, you can connect to MySQL using

mysql -u username -p
 After you're logged in, you can see what databases exist on the system by using the
SHOW command:

show databases;

Notice that the command has a semicolon at the end of the line. Most commands you
type in the monitor need to be terminated with a semicolon; otherwise, MySQL will not execute
them.
This allows you to split complex commands over multiple lines for readability. You can
also type \g (backslash g) instead of the semicolon, but most people use the semicolon.
 You can select a database from this list and type this:
use databasename;
 (Substitute the name of the database you want to use.)
 You can get information on a particular table by typing

describe tablename;
Identifiers in MySQL

An identifier is simply the name of an alias, a database, a table, a column, or an index. It


is how you uniquely identify that object. Before you can begin creating your own databases
and tables, we should discuss what identifiers are valid in MySQL.

Generally speaking, identifiers can contain any characters, with these exceptions:

 They can't contain quote characters, ACSII(0) and ASCII(255).


 Database names can contain any characters that are allowed in a directory name, but
not the characters that have special meaning in a directory name (/, \, and .) for
obvious reasons.
 Table names can contain any characters that are allowed in filenames, except for . and
/.

Creating a Database

 After design, the first step in creating a database is, logically enough, to tell MySQL that
we want to create a new database. We do this with the CREATE DATABASE SQL
statement, as follows:

create database student;

 You can check to see that this statement worked by executing the command

show databases;

 Before we can create any tables or do anything else with the employee database, we
need to tell MySQL that we want to work with our new database. We do this with the use
statement, as follows:

use student;

Creating Tables
 To create the tables in the employee database, we use the CREATE TABLE SQL
statement. The usual form of this statement is

create table table_name ( table definition ) [type=table_type];

Table Creation Example:


create table student(
studentID int not null auto_increment primary key,
Name varchar(30),
Year int(2),
Course varchar(10)
);

Deleting Databases, Tables, and Indexes

We can delete an entire database and all its contents with the following statement
drop database databasename;
You can delete a single table with the DROP TABLE statement, for example,
drop table assignment;
You can delete an index with the DROP INDEX statement, for example,
drop index part_name on employee;
As well as creating and deleting tables, we often need to be able to change the structure of an
existing table. We can do this with the ALTER TABLE statement. ALTER TABLE has many, many
variations we can use to alter table structure.
Altering Existing Table Structures

alter table student add Year int(2);


alter table student change column Year Address varchar(40);

Using INSERT
The INSERT SQL statement is used to insert rows into a table.

Using DELETE
The DELETE SQL statement allows us to delete rows from a table.

Using TRUNCATE
The TRUNCATE statement allows us to delete all the rows from a table. For example:
We can use the UPDATE SQL statement to change rows already stored in the database.

Using INSERT
The INSERT SQL statement is used to insert rows into a table.

insert into table_name values (val1, ‘val2’);

insert into department values (42, 'Finance'), (128, 'Research and Development'), (NULL, 'Human
Resources'), (NULL, 'Marketing');

Viewing Records

We retrieve data from the database using the SELECT statement. We will cover SELECT
fairly exhaustively in the next few chapters. For the moment, we only need to know that typing

select * from tablename;


select * from student;

Using DELETE
The DELETE SQL statement allows us to delete rows from a table.
delete from table_name;

In this form, the delete statement will delete all the rows from the student table.
We can also limit which rows are deleted using a WHERE clause, for example,
delete from student where Year=‘3’;

Using TRUNCATE

The TRUNCATE statement allows us to delete all the rows from a table. For example:
TRUNCATE TABLE student;

This query would delete all the students from the student table. This is faster than a DELETE
statement because it works by dropping the table and re-creating it empty. One thing to bear in
mind is that TRUNCATE is not transaction safe.

Using UPDATE
We can use the UPDATE SQL statement to change rows already stored in the database.
update student set course=‘BSIT' where id=6651;
Querying MySQL

In this chapter, we will cover the SQL SELECT statement in some detail. This is probably the
most important statement in SQL. It is the statement we use to select rows from one or more
database table(s).

 The SELECT statement has the following general form:


SELECT columns
FROM tables
[WHERE conditions]
[GROUP BY group
[HAVING group_conditions]]
[ORDER BY sort_columns]
[LIMIT limits];

Simple Queries
An example of the simplest form of the SELECT statement is as follows:

select * from student;

Selecting Particular Columns


Instead of specifying *, we can list a set of columns we would like returned. This can be a
single column, a subset of table columns, or even the complete set of columns in any order that
suits us. You should specify the column names as a list of comma-separated values.
For example, the following query selects only the values in the id and name fields of the student
table:
select name, id from student;

Aliases
We have the ability to rename columns or expressions in a SELECT statement, and the
new name will be what is shown in the output. For example, we can use the following query:
 select name as studentName from student;
 Here, we have renamed the column name as studentName just within the context of this
query.

Using the WHERE Clause to Select Particular Rows


This is useful because we frequently want to select records from a table or tables that
match particular search criteria. This becomes more important when we need to retrieve a few
useful rows from a much larger table.
 We can accomplish this using the WHERE clause of the SELECT statement. A simple
example follows:
select id , name from employee where Address=‘Tug City’;

Removing Duplicates with DISTINCT


 You can use the keyword DISTINCT in your queries to specify that you do not want to see
duplicate results. For example, consider the following query:
select Address from employee;
select distinct job from employee;

 It is relatively easy to type the previous query by mistake when what you actually meant
was this:
select count(distinct job) from employee;

Using the GROUP BY Clause


 The next clause we will look at is the GROUP BY clause. This allows us to consider retrieved
rows in groups. This is really useful only when we use it in combination with functions that
operate over a group of rows.
 Consider the following query:
 select count(*), Address from student group by Address;
Selecting Particular Groups with HAVING
 The next clause in the SELECT statement is HAVING. A GROUP BY with a HAVING clause is
like a SELECT with a WHERE clause. For example:
select count(*), Address from student group by Address having count(*)=1;

Sorting Search Results with ORDER BY


 The next clause in the SELECT statement is ORDER BY. This clause allows us to sort the result
rows on one or more columns. The sort can be either ascending, denoted ASC, or
descending, denoted DESC. For example:
select * from student order by name asc;

Limiting Search Results with LIMIT


 The final clause of the SELECT statement we will look at in this chapter is LIMIT.
 The LIMIT clause is used to limit the number and range of rows that are returned from a
query. For example, consider the following query:
select * from student limit 5;

String Functions

 MySQL's string functions fall into two categories: the string processing functions and the
string comparison functions.
 String Comparison Functions
 In addition to offering the equality operator for comparing two strings, MySQL provides
various comparison functions we can also use:
 LIKE: Performs string wildcard matching.
 RLIKE: Performs regular expression matching.
 STRCMP: String comparison, just like the strcmp() function in C.
 MATCH: Performs full-text searching.

Using LIKE for Wildcard Matching


 Let's consider an example using LIKE:

select * from student where name like ‘%Tug%';

 The RLIKE function can be used to match on the basis of regular expressions.
 A regular expression is a pattern that describes the general shape of a string. There is a
special notation for describing the features we would like to see in matching strings.
 Now, let's look at an example of how to use these patterns with RLIKE. Consider the
following query:

select * from student where Address rlike 'an';

You might also like