Top Banner

of 56

BASIC_MYSQL.docx

Jun 04, 2018

Download

Documents

pavankalluri
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/14/2019 BASIC_MYSQL.docx

    1/56

  • 8/14/2019 BASIC_MYSQL.docx

    2/56

    In my database server, the output is :

    +--------------------+| Database |+--------------------+| information_schema |

    | classicmodels || mysql |+--------------------+8 rows in set (0.00 sec)

    Selecting database to work with

    Before working with database you must tell MySQL which database you want to work with.MySQL provides you USE statement to help you to do so.

    1USE database_name;

    You can select oursample databaseby using the USE statement as follows:

    1USE classicmodels;

    From now on all actions you are performing will affect current database such as querying data,create new table or stored procedure.

    Removing Database

    Removing database means you delete the database physically. All the data and related objectsinside the database are permanently deleted and cannot be undone. So it is very important toexecute this query with cares. To delete a database you can use DROP DATABASE statement,which is a standard SQL statement as well.

    1DROPDATABASE[IF EXISTS] database_name;

    You need to specify database name after the DROP DATABASE statement. Like CREATEDATABASE statement, IF EXIST is an optional part to prevent you from removing databasewhich does not exist in database catalog.

    If you want to practice with DROP DATABASE statement, you can first create a new temporarydatabase, make sure that it is created and remove it. The sequence of SQL query to execute is asfollows:

    1CREATEDATABASEIF NOTEXISTS temp_database;

    http://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    3/56

    2SHOW DATABASES;

    3DROPDATABASEIF EXISTS temp_database;

    In this tutorial, you've learned how to create a new database, drop an existing database, select thedatabase you want to work with and list all databases in database catalog.

    Understanding MySQL Table Types

    Summary:In this tutorial, you will learn various table types in MySQL. It is essential to knowwhat kind of table types or storage engine you use for your database to maximize the

    performance of your application.

    MySQL supports various of table types or storage engines to allow you to optimize your

    database. The table types are available in MySQL are:

    ISAM MyISAM InnoDB BerkeleyDB (BDB) MERGE HEAP

    The most important feature to make all the table types above distinction is transaction-safe or not. Only

    InnoDB and BDB tables are transaction safe and only MyISAM tables supportfull-text indexing and

    searching feature.MyISAM is also the default table type when you create table without declaring which

    storage engine to use. Here are some major features of each table types:

    ISAM

    ISAM had been deprecated and removed from version 5.x. All of it functionality entire replaceby MyISAM. ISAM table has a hard size 4GB and is not portable.

    MyISAM

    MyISAM table type is default when you create table. MyISAM table work very fast but not

    transaction-safe. The size of MyISAM table depends on the operating system and the data fileare portable from system to system. With MyISAM table type, you can have 64 keys per tableand maximum key length of 1024 bytes.

    InnoDB

    Different from MyISAM table type, InnoDB table are transaction safe and supports row-levellocking. Foreign keys are supported in InnoDB tables. The data file of InnoDB table can be

    http://www.mysqltutorial.org/mysql-full-text-search.aspxhttp://www.mysqltutorial.org/mysql-full-text-search.aspxhttp://www.mysqltutorial.org/mysql-full-text-search.aspxhttp://www.mysqltutorial.org/mysql-full-text-search.aspxhttp://www.mysqltutorial.org/mysql-full-text-search.aspxhttp://www.mysqltutorial.org/mysql-full-text-search.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    4/56

    stored in more than one file so the size of table depends on the disk space. Like the MyISAMtable type, data file of InnoDB is portable from system to system. The disadvantage of InnoDBin comparison with MyISAM is it take more disk space.

    BDB

    BDB is similar to InnoDB in transaction safe. It supports page level locking but data file are notportable.

    MERGE

    Merge table type is added to treat multiple MyISAM tables as a single table so it remove the sizelimitation from MyISAM tables.

    HEAP

    Heap table is stored in memory so it is the fastest one. Because of storage mechanism, the datawill be lost when the power failure and sometime it can cause the server run out of memory.Heap tables do not support columns with AUTO_INCREMENT, BLOB and TEXTcharacteristics.

    MySQL Data Types

    Summary: In this tutorial, you will learn various MySQL data typesto use them effectively indatabase table design.

    Database table contains multiple columns with specific data types such as numeric or string.MySQL provides you many more specific data types than just "numeric" or "string". Each datatype in MySQL can be determined by the following characteristics:

    What kind of value it can represent. The space values take up and whether the values are fixed-length or variable-length. The values of a data type can be indexed. How MySQL compare values of that data types.

    Numeric Data Types

    You can find all SQL standard numeric types in MySQL including exact number data type andapproximate numeric data types including integer, fixed-point and floating point. In addtion,MySQL also supports BIT data type for storing bit field values. Numeric types can be signed or

  • 8/14/2019 BASIC_MYSQL.docx

    5/56

    unsigned except BIT type. The following table shows you the summary of numeric types inMySQL:

    Numeric Types Description

    TINYINT A very small integer

    SMALLINT A small integer

    MEDIUMINT A medium-sized integer

    INT A standard integer

    BIGINT A large integer

    DECIMAL A fixed-point number

    FLOAT A single-precision floating-point number

    DOUBLE A double-precision floating-point number

    BIT A bit field

    String Data Types

    In MySQL, string can hold anything from plain text to binary data such as images and files.

    String can be compared and searched based on pattern matching by using LIKE clause or regularexpression. The table below shows you the string data types in MySQL:

    String Types Description

    CHAR A fixed-length non-binary (character) string

    VARCHAR A variable-length non-binary string

    BINARY A fixed-length binary string

    VARBINARY A variable-length binary string

    TINYBLOB A very small BLOB (binary large object)

    BLOB A small BLOB

  • 8/14/2019 BASIC_MYSQL.docx

    6/56

    String Types Description

    MEDIUMBLOBA medium-sized BLOB

    LONGBLOB A large BLOB

    TINYTEXT A very small non-binary string

    TEXT A small non-binary string

    MEDIUMTEXT A medium-sized non-binary string

    LONGTEXT A large non-binary string

    ENUM An enumeration; each column value may be assigned one enumeration member

    SET A set; each column value may be assigned zero or more set members

    Date and Time Data Types

    MySQL provides types for date and time and combination of date and time. In addition,MySQL also provide timestamp data type for tracking last change on a record. If you just want tostore the year without date and month, you can use YEAR data type. Here is the table whichshowing MySQL date and type data types:

    Date and Time

    Types Description

    DATE A date value in 'CCYY-MM-DD' format

    TIME A time value in 'hh:mm:ss' format

    DATETIME A date and time value in 'CCYY-MM-DD hh:mm:ss' format

    TIMESTAMP A timestamp value in 'CCYY-MM-DD hh:mm:ss' format

    YEAR A year value in CCYY or YY format

    Spatial Data Types

    MySQL support many spatial data types as below table which contains various kind ofgeometrical and geographical values.

  • 8/14/2019 BASIC_MYSQL.docx

    7/56

    Spatial Data Types Description

    GEOMETRY A spatial value of any type

    POINT A point (a pair of X Y coordinates)

    LINESTRING A curve (one or more POINT values)

    POLYGON A polygon

    GEOMETRYCOLLECTIONA collection of GEOMETRY values

    MULTILINESTRING A collection of LINESTRING values

    MULTIPOINT A collection of POINT values

    MULTIPOLYGON A collection of POLYGON values

    Understanding MySQL TIMESTAMP

    Summary: The MySQL TI MESTAMPis a temporal data type that store combination of dateand time values. In this tutorial you will learn how MySQL TI MESTAMPvalues are stored inthe database and how to use automatic initialization and automatic update to create created on

    and last changed on column in a table.

    How MySQL TIMESTAMP stored in the databaseThe format of MySQL TIMESTAMP column is YYYY-MM-DD HH:MM:SS which is fixed at 19 characters.

    The MySQL TIMESTAMP are stored as four bytes number of second since the first day of UNIX time

    which is 1970-01-01 00:00:01. The upper end of range correspond to maximum four bytes value of

    UNIX time which is 2038-01-19 03:14:07. Therefore the TIMESTAMP column has a range of values from

    1970-01-01 00:00:01 to '2038-01-19 03:14:07'.

    The values of the MySQL TIMESTAMP columns depend on connections time zone. When insert values

    for MySQL TIMESTAMP columns, they are converted to Universal Coordinated Time (UTC) fromconnections time zone.When you select the value, the server converts it back from UTC to the

    connections time zone so you have the same value that you inserted. However if another client with

    different time zone connects to the server to select value from MySQL TIMESTAMP column, it will see

    the value adjusted to its time zone. MySQL allows you to change your own time zone when you connect

    to it so you can see this effect by using a single connection.

    Lets try in our sample database to see this effect.

  • 8/14/2019 BASIC_MYSQL.docx

    8/56

    1CREATETABLEtest_timestamp('t1' TIMESTAMP);

    2

    3SETtime_zone='+00:00';

    4

    5INSERTINTOtest_timestamp VALUES('2008-01-01 00:00:01');

    6

    7SELECTt1

    8FROMtest_timestamp;

    +---------------------+| t1 |+---------------------+| 2008-01-01 07:00:01 |+---------------------+1 row in set (0.00 sec)

    The SQL commands can be explained as follows:

    First we created a table called test_TIMESTAMP. Next we set our time zone to UTC. Then we insert a TIMESTAMP value into the table test_timestamp. Finally we select it to see the value we inserted.

    Now can set our time zone to a different time zone and see what value we get from database server:

    1SETtime_zone =+03:00;

    2

    3SELECTt1

    4FROMtest_timestamp;

    +---------------------+| t1 |+---------------------+| 2008-01-01 03:00:01 |+---------------------+1 row in set (0.00 sec)

    As you see, we get adjusted value to our new time zone.

  • 8/14/2019 BASIC_MYSQL.docx

    9/56

    INSERT and UPDATE TIMESTAMP column

    If you omit the MySQL TIMESTAMP columns value in the INSERT statement or you set it toNULL, it will be automatically set to current TIMESTAMP. This characteristic of MySQLTIMESTAMP is known as automatic initialization.

    In the table which has a MySQL TIMESTAMP column, if you change other columns value, theMySQL TIMESTAMP column will be automatic updated to the current TIMESTAMP. Thechange only accepted if you change its current value to different values in order to haveTIMESTAMP column updated. This characteristic of TIMESTAMP called automatic update.Note that only one column can be designated as a TIMESTAMP column which has automaticupdate.

    The MySQL TIMESTAMP columns are design in a table that you need to save the created dateand last change date for the records. By applying automatic initialization and automatic updateof MySQL TIMESTAMP column you can design the table as follows:

    1CREATETABLEtbl_name(

    2

    3 created_on TIMESTAMPDEFAULT0

    4 changed_on TIMESTAMPDEFAULTCURRENT_TIMESTAMP

    5);

    So when you insert a new record, just omit two TIMESTAMP columns or set them to NULL.The both created_onand changed_oncolumn will be inserted as the current TIMESTAMP.

    When you update, omit both TIMESTAMP columns, the changed_oncolumn's value will beautomatic updated if there is any change in other columns values.

    In this tutorial, you've learned how MySQLTIMESTAMP data stored in the MySQL databasetable and how to use its characteristics to design the created on and last changed on columns.

    Working with Database Table - Part ISummary:In this tutorial you will learn how to create, show and describe tables in MySQL.

    Database table or table in short is one of the most important objects of relational database. Howto create databases tables correctly is crucial when you work with any database system especiallyMySQL. In this tutorial, you will learn how to create a simple database table. You'll also learnhow to list all database tables of a specific database.

  • 8/14/2019 BASIC_MYSQL.docx

    10/56

    Creating Tables

    To create table we use the CREATE TABLEstatement. The typical form ofSQL CREATE TABLE statement is as follows:

    1CREATETABLE[IF NOTEXISTS] table_name(

    2 column_list

    3 ) type=table_type

    MySQL supports IF NOT EXISTS after CREATE TABLE statement to prevent you from error ofcreating table which already exists on the database server.

    table_nameis the name of table you would like to create. After that, you can define a set ofcolumns which is usually in this form: column_name data_type(size) [NOT] NULL.

    You can specify the storage engine type you prefer to use for the table. MySQL supports variousstorage engines such as InnoDB, MyISAM... If you don't explicit declare storage engine type,

    MySQL will use MyISAM by default.

    In our classicmodelssample database, to create employees table, we can use the CREATETABLE statement as follows:

    01CREATETABLEemployees (

    02 employeeNumber into(11) NOTNULL,

    03 lastName varchar(50) NOTNULL,

    04 firstName varchar(50) NOTNULL,

    05 extension varchar(10) NOTNULL,

    06 email varchar(100) NOTNULL,

    07 officeCode varchar(10) NOTNULL,

    08 reportsTo int(11) defaultNULL,

    09 jobTitle varchar(50) NOTNULL,

    10 PRIMARYKEY (employeeNumber)

    11 );

    First, you specify table name employeesafter CREATE TABLE statement.

  • 8/14/2019 BASIC_MYSQL.docx

    11/56

    Then you list the columns of the table with their attributes such as data type, size, NOT NULL.

    And finally you specify the primary key of the table, in this case the primary key isemployeeNumber.

    If the table has more than one primary key, you can seperate them by a comma. For example, thepaymentstable has two primary keys customerNumber and checkNumber. You can createpayments table by executing following query:

    1CREATETABLEpayments (

    2 customerNumber int(11) NOTNULL,

    3 checkNumber varchar(50) NOTNULL,

    4 paymentDate datetime NOTNULL,

    5 amount doubleNOTNULL,

    6 PRIMARYKEY (customerNumber,checkNumber)

    7 );

    It is important to note that by default MySQL uses MyISAM storage engine for the table itcreated.

    Showing and Describing Tables in a Database

    In order to show all tables in a database, you use SHOW TABLES statment. By executing theSHOW TABLES statement, MySQL will returns all tables' name of the current selected databasethat you're working with.

    1SHOW TABLES

    Here is the output of classicmodels database:

    +-------------------------+| Tables_in_classicmodels |+-------------------------+| customers || employees || offices || orderdetails || orders || payments || productlines |

  • 8/14/2019 BASIC_MYSQL.docx

    12/56

    | products |+-------------------------+8 rows in set (0.00 sec)

    In some cases, you need to see the table's metadata, you can use DESCRIBE statement asfollows:

    1DESCRIBE table_name;

    For instance, we can describe employees table like below query:

    1DESCRIBE employees;

    The output return from the database server:

    +----------------+--------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+----------------+--------------+------+-----+---------+-------+| employeeNumber | int(11) | NO | PRI | NULL | || lastName | varchar(50) | NO | | NULL | || firstName | varchar(50) | NO | | NULL | || extension | varchar(10) | NO | | NULL | || email | varchar(100) | NO | | NULL | || officeCode | varchar(10) | NO | | NULL | || reportsTo | int(11) | YES | | NULL | || jobTitle | varchar(50) | NO | | NULL | |+----------------+--------------+------+-----+---------+-------+8 rows in set (0.02 sec)

    MySQL ALTER Command

    MySQL ALTERcommand is very useful when you want to change a name of your table, anytable field or if you want to add or delete an existing column in a table.

    Lets begin with creation of a table called testalter_tbl

    root@host# mysql -u root -p password;Enter password:*******

    mysql> use TUTORIALS;Database changedmysql> create table testalter_tbl

    -> (-> i INT,-> c CHAR(1)-> );

    Query OK, 0 rows affected (0.05 sec)mysql> SHOW COLUMNS FROM testalter_tbl;

  • 8/14/2019 BASIC_MYSQL.docx

    13/56

    +-------+---------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+---------+------+-----+---------+-------+| i | int(11) | YES | | NULL | || c | char(1) | YES | | NULL | |+-------+---------+------+-----+---------+-------+

    2 rows in set (0.00 sec)

    Dropping, Adding, or Repositioning a Column:

    Suppose you want to drop an existing column ifrom above MySQL table then you will useDROPclause along with ALTERcommand as follows

    mysql> ALTER TABLE testalter_tbl DROP i;

    A DROPwill not work if the column is the only one left in the table.

    To add a column, use ADD and specify the column definition. The following statement restoresthe icolumn to testalter_tbl

    mysql> ALTER TABLE testalter_tbl ADD i INT;

    After issuing this statement, testalter will contain the same two columns that it had when youfirst created the table, but will not have quite the same structure. That's because new columns areadded to the end of the table by default. So even though ioriginally was the first column inmytbl, now it is the last one:

    mysql> SHOW COLUMNS FROM testalter_tbl;+-------+---------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+---------+------+-----+---------+-------+| c | char(1) | YES | | NULL | || i | int(11) | YES | | NULL | |+-------+---------+------+-----+---------+-------+2 rows in set (0.00 sec)

    To indicate that you want a column at a specific position within the table, either use FIRST tomake it the first column, or AFTER col_name to indicate that the new column should be placed

    after col_name. Try the following ALTER TABLE statements, using SHOW COLUMNS aftereach one to see what effect each one has:

    ALTER TABLE testalter_tbl DROP i;ALTER TABLE testalter_tbl ADD i INT FIRST;ALTER TABLE testalter_tbl DROP i;ALTER TABLE testalter_tbl ADD i INT AFTER c;

  • 8/14/2019 BASIC_MYSQL.docx

    14/56

    The FIRST and AFTER specifiers work only with the ADD clause. This means that if you wantto reposition an existing column within a table, you first must DROP it and then ADD it at thenew position.

    Changing a Column Definition or Name:

    To change a column's definition, use MODIFYor CHANGEclause along with ALTERcommand. For example, to change column cfrom CHAR(1) to CHAR(10), do this:

    mysql> ALTER TABLE testalter_tbl MODIFY c CHAR(10);

    With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the columnyou want to change, then specify the new definition, which includes the new name. Try outfollowing example:

    mysql> ALTER TABLE testalter_tbl CHANGE i j BIGINT;

    If you now use CHANGE to convert j from BIGINT back to INT without changing the columnname, the statement be as expected:

    mysql> ALTER TABLE testalter_tbl CHANGE j j INT;

    The Effect of ALTER TABLE on Null and Default Value Attributes:

    When you MODIFY or CHANGE a column, you can also specify whether or not the column can

    contain NULL values, and what its default value is. In fact, if you don't do this, MySQLautomatically assigns values for these attributes.

    Here is the example where NOT NULL column will have value 100 by default.

    mysql> ALTER TABLE testalter_tbl-> MODIFY j BIGINT NOT NULL DEFAULT 100;

    If you don't use above command then MySQL will fill up NULL values in all the columns.

    Changing a Column's Default Value:

    You can change a default value for any column using ALTER command. Try out followingexample.

    mysql> ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;mysql> SHOW COLUMNS FROM testalter_tbl;+-------+---------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |

  • 8/14/2019 BASIC_MYSQL.docx

    15/56

    +-------+---------+------+-----+---------+-------+| c | char(1) | YES | | NULL | || i | int(11) | YES | | 1000 | |+-------+---------+------+-----+---------+-------+2 rows in set (0.00 sec)

    You can remove default constraint from any column by using DROP clause along with ALTERcommand.

    mysql> ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;mysql> SHOW COLUMNS FROM testalter_tbl;+-------+---------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+---------+------+-----+---------+-------+| c | char(1) | YES | | NULL | || i | int(11) | YES | | NULL | |+-------+---------+------+-----+---------+-------+2 rows in set (0.00 sec)

    Changing a Table Type:

    You can use a table type by using TYPEclause alongwith ALTER command. Try out followingexample to change testalter_tbl to MYISAMtable type.

    To find out the current type of a table, use the SHOW TABLE STATUS statement.

    mysql> ALTER TABLE testalter_tbl TYPE = MYISAM;mysql> SHOW TABLE STATUS LIKE 'testalter_tbl'\G*************************** 1. row ****************

    Name: testalter_tblType: MyISAM

    Row_format: FixedRows: 0

    Avg_row_length: 0Data_length: 0

    Max_data_length: 25769803775Index_length: 1024

    Data_free: 0Auto_increment: NULL

    Create_time: 2007-06-03 08:04:36Update_time: 2007-06-03 08:04:36Check_time: NULL

    Create_options:Comment:

    1 row in set (0.00 sec)

  • 8/14/2019 BASIC_MYSQL.docx

    16/56

    Renaming a Table:

    To rename a table, use the RENAMEoption of the ALTER TABLE statement. Try outfollowing example to rename testalter_tbl to alter_tbl

    mysql> ALTER TABLE testalter_tbl RENAME TO alter_tbl;

    Deleting Tables

    To delete table from the database, you can use DROP TABLE statement:

    1DROP[TEMPORARY] TABLE[IF EXISTS] table_name [, table_name,...]

    TEMPORARY keyword is used for deleting temporary tables. MySQL allows you to dropmultiple tables at once by listing them and separated each by a comma. IF EXISTS is used toprevent you from deleting table which does not exist in the database.

    Empty Table's Data

    In some cases, you want to delete all table data in a fast way and reset all auto incrementcolumns. MySQL also provides you SQL TRUNCATE table statement to allow you to do so.The SQL TRUNCATE statement is as follows:

    1TRUNCATETABLEtable_name

    There are some points you should remember before using TRUNCATE TABLE statement:

    TRUNCATE TABLE statement drop table and recreate it therefore it is much faster than DELETETABLE statement. However it is not transaction-safe.

    The number of deleted rows is not returned like SQL DELETE TABLE statement. ON DELETE triggers are not invoked because TRUNCATE does not use DELETE statement.

    Changing Table Structure Using MySQL

    ALTER TABLESummary:In this tutorial you will learn how to use MySQL ALTER TABLEstatement tochange the structure of existing tables.

  • 8/14/2019 BASIC_MYSQL.docx

    17/56

    MySQL ALTER TABLE syntax

    MySQL ALTER TABLEstatement is used to change the structure of existing tables. You canuse MySQL ALTER TABLE to add or drop column, change column data type, add primary key,rename table and a lot more. The following illustrates the MySQL ALTER TABLE syntax:

    1ALTERTABLEtable_name action1[,action2,]

    Followed by the keyword ALTER TABLE is name of table that you want to make the changes.After the table name is the action you want apply to the table. An action can be anything fromadd a new column, add primary key. to rename table. MySQL allows you to do multipleactions at a time, separated by a comma.

    Lets create a new table for practicing MySQL ALTER TABLE statement. Were going to create

    a new table called tasks in our sample database classicmodelsas follows:

    1CREATE TABLE'tasks'(

    2 'task_id'INTNOTNULL,

    3 'subject'VARCHAR(45) NULL,

    4 'start_date'DATETIME NULL,

    5 'end_date'DATETIME NULL,

    6 'description'VARCHAR(200) NULL,

    7 PRIMARYKEY('task_id') ,

    8 UNIQUEINDEX'task_id_UNIQUE'('task_id'ASC) );

    Changing columns using MySQL ALTER TABLE statement

    Using MySQL ALTER TABLE to add auto-increment for a column

    Suppose we want the task id is increased by one automatically whenever we insert a new task. In

    order to accomplish this, we need to use the MySQL ALTER TABLE statement to change thecolumn task id to make it auto increment as follows:

    1ALTERTABLEtasks

    2CHANGE COLUMNtask_id task_id INT(11) NOTNULLAUTO_INCREMENT;

  • 8/14/2019 BASIC_MYSQL.docx

    18/56

  • 8/14/2019 BASIC_MYSQL.docx

    19/56

    In general, it is suggested that you should create index on columns you usually use in retrievalsuch as columns used in join and sorts.Note that all primary keys are in primary index ofdatabase table.

    Why not index every column? The most significant is that building and maintaining an indexes

    table take time and storage space on database. In addition, when insert/ update or remove datafrom table, the index has to be rebuilt and it decrease the performance when changing table data.

    Creating Indexes

    Usually you create index when creating table. Any column in creating table statement declaredas PRIMARY KEY, KEY, UNIQUE or INDEX will be indexed automatically by MySQL. Inaddition, you can add indexes to the tables which has data. The statement to create index inMySQL is as follows:

    1CREATE[UNIQUE|FULLTEXT|SPATIAL] INDEXindex_name

    2USING [BTREE | HASH | RTREE]

    3ONtable_name (column_name [(length)] [ASC| DESC],...)

    First you specify the index based on the table types or storage engine:

    UNIQUE means MySQL will create a constraint that all values in the index must be distinct.Duplicated NULL is allowed in all storage engine except BDB.

    FULLTEXT index is supported only by MyISAM storage engine and only accepted columns whichhave data type is CHAR,VARCHAR or TEXT.

    SPATIAL index supports spatial column and available in MyISAM storage engine. In addition, thecolumn value must not be NULL.

    Then you name the index using index types such as BTREE, HASH or RTREE also based onstorage engine. Here is the list:

    Storage Engine Allowable Index Types

    MyISAM BTREE, RTREE

    InnoDB BTREE

    MEMORY/HEAPHASH, BTREE

    NDB HASH

    Finally you declare which column on which table using the index.

  • 8/14/2019 BASIC_MYSQL.docx

    20/56

    In our sample database, you can create index to officeCode column on employees table to makethe join operation with office table faster. The SQL statement to create index is as follows:

    1CREATEINDEXofficeCode ONemployees(officeCode)

    Removing Indexes

    Besides creating index, you can also remove index by using DROP INDEX statement.Interestingly, DROP INDEX statement is also mapped to ALTER TABLE statement. Here is thesyntax:

    1DROPINDEXindex_name ONtable_name

    For example, if you want to drop index officeCode which we have added to the employees table,

    just execute following query:

    1DROPINDEXofficeCode ONemployees

    In this tutorial, you've learned how to manage database index of database table inMySQL including creating and removing index.

    Using MySQL SELECT Statement to Query

    DataSummary:In this tutorial, you will learn how toMySQL SELECTstatement to query data fromdatabase tables.

    MySQL SELECT Statement Syntax

    In order to retrieve data from MySQL database table you need to use MySQL SELECTstatement. The following illustrates MySQL SELECT statment syntax:

    1SELECTcolumn_name1,column_name2...

    2FROMtables

    3[WHEREconditions]

    4[GROUPBYgroup

  • 8/14/2019 BASIC_MYSQL.docx

    21/56

    5[HAVINGgroup_conditions]]

    6[ORDERBYsort_columns]

    7[LIMIT limits];

    The MySQL SELECT statement has many optional elements that you can use. The order ofFROM, WHERE, GROUP BY, HAVING, ORDER BY and LIMIT has to be in the sequenceabove.

    To select all columns in a table you can use asterisk (*) notation instead of listing all columnnames in the MySQL SELECT statement. For example, if you need to query all the columns inoffices table, you can use the following query:

    1SELECT* FROMemployees

    TheMySQL SELECTstatement also allows you to to view partial data of a table by listingcolumns' name after the SELECT keyword. This is calledprojection. For example if you need toview onlyfirst name, last name andjob titleof employee in the employeestable, you can use thefollowing query:

    1SELECTlastname,firstname,jobtitle

    2FROMemployees

  • 8/14/2019 BASIC_MYSQL.docx

    22/56

    WHERE Clause

    WHERE clause of the MySQL SELECT statement enables you to select particular rows whichmatch its conditions or search criteria. You use WHERE clause to filter the records based on acertain conditions. For example, you can find the president of company by using the followingquery:

    1SELECTfirstname,lastname,email

    2FROMemployees

    3WHEREjobtitle="president"

    DISTINCT

    With DISTINCT keyword, you can eliminate the duplicate records from the SELECT statement.

    For example, to find how manyjob titleof all employees in the employeestable, you useDISTINCT keyword in SELECT statement as follows:

    1SELECTDISTINCTjobTitle FROMemployees;

  • 8/14/2019 BASIC_MYSQL.docx

    23/56

    Sorting result with ORDER BY

    The ORDER BY clause allows you to sort the result set on one or more columns in ascending ordescending order. To sort the result set in ascending order you use ASC and in descending orderyou use DESC keywords. By default, the ORDER BY will sort the result set in ascending order.

    For example, to sort the name of employees by fi rst nameandjob ti tle, you can execute thefollowing query:

    1SELECTfirstname,lastname, jobtitle

    2FROMemployees

    3ORDERBYfirstname ASC,jobtitle DESC;

    In this tutorial, you've learned about basic MySQL SELECTstatement to retrieve data from onedatabase table. You'll learn more about each technique in details in later tutorials.

  • 8/14/2019 BASIC_MYSQL.docx

    24/56

    How to Use MySQL Distinct to Eliminate

    Duplicate Rows

    Summary: In this tutorial, you will learn how to use MySQL DI STINCT with SELECTstatement to eliminate duplicate records in the selected result set.

    Sometimes when retrieving data from database table, you get duplicate records which are notexpected. In order to remove those duplicate records, you need to use DISTINCT keyword alongwith SELECT statement. The syntax of SQL DISTINCT is as follows:

    1SELECTDISTINCTcolumns

    2FROMtable

    3WHEREwhere_conditions

    Let take a look a simple example of using DISTINCT to select unique last name from employeetable.

    1SELECTlastname

    2FROMemployees

    3ORDERBYlastname+-----------+| lastname |+-----------+| Bondur || Bondur || Bott |

    | Bow || Castillo || Firrelli || Firrelli || Fixter || Gerard || Hernandez || Jennings || Jones || Kato || King || Marsh || Murphy |

    | Nishi || Patterson || Patterson || Patterson || Thompson || Tseng || Vanauf |+-----------+23 rows in set (0.00 sec)

  • 8/14/2019 BASIC_MYSQL.docx

    25/56

    Because in the employeestable we have some employee records with the same last name so weget duplicate last names in the result set. Let apply DISTINCT keyword in the SELECTstatement to remove those duplicate last names.

    1SELECTDISTINCTlastname

    2FROMemployees3ORDERBYlastname+-----------+| lastname |+-----------+| Bondur || Bott || Bow || Castillo || Firrelli || Fixter || Gerard || Hernandez |

    | Jennings || Jones || Kato || King || Marsh || Murphy || Nishi || Patterson || Thompson || Tseng || Vanauf |+-----------+19 rows in set (0.00 sec)

    As you can see in the new result set, four duplicate records are eliminated from the list when weused DISTINCT.

    The DISTINCTkeyword can be applied with more than one column. In this case, thecombination of all columns are used to define the uniqueness of a record in the return result set.For example, to get all cities and states of customers in the customerstable, we can use thefollowing query:

    1SELECTDISTINCTcity, state2FROMcustomers

    How to Use MySQL Limit to Constrain

    Number of Returned Records

  • 8/14/2019 BASIC_MYSQL.docx

    26/56

    Summary: In this tutorial, you will learn how to use MySQL LIM ITclause to constrain number

    of returned records in SQL SELECT statement.

    Most of the times, when you work with master data tables which contain thousand to millions ofrecords and you don't want to write a query to get all the data from those tables because of

    application's performance and high traffic between database server and application server.MySQL supports a cool feature called LIMIT to allow you to constrain the returned records withSELECT statement. Let take a look at the MySQL LIMIT syntax:

    Let's say you have a database table with 10000 records and you want to get just first N records,you can use the following query:

    1SELECT* FROMtable

    2LIMIT N

    The MySQL LIMIT also allows you to get a range of records where you decide starting record

    number and how many records you want to retrieve. Here is the syntax of MySQL LIMIT toselect a range of records:

    1SELECTcolumns

    2FROMtable

    3LIMIT S, N

    In the query above, S is the starting record index. MySQL specifies that the first record startswith 0. N is the number of records you want to select.

    Let's practice MySQL LIMIT with several examples to have a better understanding.

    If you want to get the first five employees in the table employees, you can use the followingquery:

    1SELECTfirstname,lastname

    2FROMemployees

    3LIMIT 5+-----------+-----------+| firstname | lastname |+-----------+-----------+| Diane | Murphy |

    | Mary | Patterson || Jeff | Firrelli || William | Patterson || Gerard | Bondur |+-----------+-----------+5 rows in set (0.00 sec)

    Now if you want to get five employees from employee number 10 you can use MySQL LIMITwith offset as follows:

  • 8/14/2019 BASIC_MYSQL.docx

    27/56

    1SELECTfirstname,lastname

    2FROMemployees

    3LIMIT 10,5+-----------+-----------+| firstname | lastname |+-----------+-----------+| Foon Yue | Tseng || George | Vanauf || Loui | Bondur || Gerard | Hernandez || Pamela | Castillo |+-----------+-----------+5 rows in set (0.00 sec)

    Selecting Data with SQL IN

    Summary:In this tutorial, you will learn how to select a result set which their values match any

    one of a list of values by using SQL IN operator.

    SQL IN Operator Syntax

    The SQL IN operator allows you to select values that match any one of a list of values. Theusage of the SQL IN operator is listed as follows:

    1SELECTcolumn_list

    2FROMtable_name

    3WHEREcolumnIN("list_item1","list_item2")

    The column in WHERE clause does not need to be in column_list you selected, but it has to be acolumn in the table table_name.If the list has more than one value, each item has to be separatedby a comma.

    In addition, you can use NOT operator with SQL IN to get values which does not match anyvalue in a list of value.

    Lets practice with several examples of SQL IN.

    Suppose if you want to find out all offices which are located in US and France, you can performthe following query:

    1SELECTofficeCode, city, phone

  • 8/14/2019 BASIC_MYSQL.docx

    28/56

    2FROMoffices

    3WHEREcountry = 'USA' ORcountry = 'France'

    In this case, we can use SQL IN instead of the above query:

    1SELECTofficeCode, city, phone

    2FROMoffices

    3WHEREcountry IN('USA','France')

    Here is the output

    +------------+--------+-----------------+| officeCode | city | phone |+------------+--------+-----------------+| 2 | Boston | +1 215 837 0825 || 3 | NYC | +1 212 555 3000 || 4 | Paris | +33 14 723 5555 || 8 | Boston | +1 215 837 0825 |+------------+--------+-----------------+

    To get all countries which does are not located in USA and France, we can use NOT IN in thewhere clause as follows:

    1SELECTofficeCode, city, phone

    2FROMoffices

    3WHEREcountry NOTIN('USA','France')

    Here is the output of offices which does not in USA and France

    +------------+--------+------------------+| officeCode | city | phone |+------------+--------+------------------+| 5 | Tokyo | +81 33 224 5000 |

    | 6 | Sydney | +61 2 9264 2451 || 7 | London | +44 20 7877 2041 |+------------+--------+------------------+

    SQL IN is used most often in sub-query. For example, if you want to find out all orders in theorderstable which have total cost greater than $60000, we can use SQL IN with sub-query.

  • 8/14/2019 BASIC_MYSQL.docx

    29/56

    First to select all the orders which has total cost greater than $60000, you can retrieve it fromorderDetails table as follows:

    1SELECTorderNumber

    2FROM

    orderDetails

    3GROUPBYorderNumber

    4HAVINGSUM(quantityOrdered * priceEach) > 60000

    Second you use the sub-query with SQL IN as follows:

    1SELECTorderNumber,customerNumber,status,shippedDate

    2FROMorders

    3WHEREorderNumber IN(

    4SELECT orderNumber

    5FROM orderDetails

    6GROUPBY orderNumber

    7HAVING SUM(quantityOrdered * priceEach) > 60000)

    You get all the orders which have total cost greater than $60000

    +-------------+----------------+---------+---------------------+| orderNumber | customerNumber | status | shippedDate |+-------------+----------------+---------+---------------------+| 10165 | 148 | Shipped | 2003-12-26 00:00:00 || 10287 | 298 | Shipped | 2004-09-01 00:00:00 || 10310 | 259 | Shipped | 2004-10-18 00:00:00 |+-------------+----------------+---------+---------------------+

    Retrieving Data in a Range Using SQL

    BETWEEN

  • 8/14/2019 BASIC_MYSQL.docx

    30/56

    Summary:In this tutorial, you will learn how to retrieve data from database tables which itsvalue are in a range by using SQL BETWEENoperator.

    SQL BETWEEN Operator Syntax

    The SQL BETWEEN operator allows you to retrieve values within a specific range. theSQL between must be used in the WHERE clause of theSQL SELECT statement.The followingillustrates the SQL BETWEEN syntax:

    1SELECTcolumn_list

    2FROMtable_name

    3WHEREcolumn_1 BETWEENlower_range ANDupper_range

    MySQL returns all records in which the column_1 value is in the range of lower_rageandupper_rangeas well as the values lower_rage and upper_range. The query which is equivalent toSQL BETWEEN to get the same result is

    1SELECTcolumn_list

    2FROMtable_name

    3WHEREcolumn_1 >= lower_range ANDcolumn_1

  • 8/14/2019 BASIC_MYSQL.docx

    31/56

    | S24_3856 | 1956 Porsche 356A Coupe | 98.3 || S12_1108 | 2001 Ferrari Enzo | 95.59 || S12_1099 | 1968 Ford Mustang | 95.34 || S18_1984 | 1995 Honda Civic | 93.89 || S18_4027 | 1970 Triumph Spitfire | 91.92 || S10_4698 | 2003 Harley-Davidson Eagle Drag Bike | 91.02 |+-------------+--------------------------------------+----------+

    The output contains all products in the range of 90$ and 100$, and if there is a product with buyprice 90$ or 100$, it will be included in the output too.

    In order to find all records which are not in a range we use NOT BETWEEN. To find allproducts that buy price outside the range of 20 and 100, we can operate following query:

    1SELECTproductCode,ProductName,buyPrice

    2FROMproducts

    3WHEREbuyPrice NOTBETWEEN20 AND100

    +-------------+-------------------------------------+----------+| productCode | ProductName | buyPrice |+-------------+-------------------------------------+----------+| S10_4962 | 1962 LanciaA Delta 16V | 103.42 || S18_2238 | 1998 Chrysler Plymouth Prowler | 101.51 || S24_2972 | 1982 Lamborghini Diablo | 16.24 || S24_2840 | 1958 Chevy Corvette Limited Edition | 15.91 |+-------------+-------------------------------------+----------+

    The query above is equivalent to the following query

    1SELECTproductCode,ProductName,buyPrice

    2FROMproducts

    3WHEREbuyPrice < 20 ORbuyPrice > 100

    4ORDERBYbuyPrice DESC

    In this tutorial, you've learned how to use SQL BETWEEN to select data from database tables ina range.

    How to Use MySQL LIKE to Select Data

    Based on Patterns Matching

  • 8/14/2019 BASIC_MYSQL.docx

    32/56

    Summary:MySQL provides LIKE operator in SQL standard. The MySQL LI KEoperator iscommonly used to select data based on patterns matching. Using MySQL LI KE in appropriate

    way is essential to increase application's performance. In this tutorial, you will learn how to useMySQL LI KEand when to avoid using it to increase the speed of retrieving data from databasetable.

    MySQL LIKE allows you to perform pattern matching in your characters column in a databasetable. MySQL LIKE is often used with SELECT statement in WHERE clause. MySQL providesyou two wildcard characters for using with LIKE, the percentage % and underscore _.

    Percentage (%) wildcard allows you to match any string of zero or more characters Underscore (_) allows you to match any single character.

    Lets practice with couples of examples which use MySQL Like with different wildcard

    characters.

    Suppose you want to search for employee in employees table who has first name starting withcharacter a, you can do it as follows:

    1SELECTemployeeNumber, lastName, firstName

    2 FROMemployees

    3 WHEREfirstName LIKE'a%'+----------------+----------+-----------+| employeeNumber | lastName | firstName |+----------------+----------+-----------+| 1611 | Fixter | Andy |+----------------+----------+-----------+1 row in set (0.00 sec)

    MySQL scans the whole employeestable to find all employees which have first name startingwith character a and followed by any number of characters.

    To search all employees which have last name ended with on string you can perform the queryas follows:

    1SELECTemployeeNumber, lastName, firstName

    2 FROMemployees

    3 WHERElastName LIKE'%on'+----------------+-----------+-----------+

    | employeeNumber | lastName | firstName |+----------------+-----------+-----------+| 1088 | Patterson | William || 1216 | Patterson | Steve |+----------------+-----------+-----------+2 rows in set (0.00 sec)

  • 8/14/2019 BASIC_MYSQL.docx

    33/56

    If you know a searched string is embedded somewhere in a column, you can put the percentagewild card at the beginning and the end of it to find all possibilities. For example, if you want tofind all employees which have last name containing on string you can execute following query:

    1SELECTemployeeNumber, lastName, firstName

    2FROMemployees3WHERElastname LIKE'%on%'+----------------+-----------+-----------+| employeeNumber | lastName | firstName |+----------------+-----------+-----------+| 1088 | Patterson | William || 1102 | Bondur | Gerard || 1216 | Patterson | Steve || 1337 | Bondur | Loui || 1504 | Jones | Barry |+----------------+-----------+-----------+5 rows in set (0.00 sec)

    To search all employees whose name are such as Tom, Tim You can use underscore wildcard

    1SELECTemployeeNumber, lastName, firstName

    2FROMemployees

    3WHEREfirstname LIKE''T_m"+----------------+----------+-----------+| employeeNumber | lastName | firstName |+----------------+----------+-----------+| 1619 | King | Tom |+----------------+----------+-----------+1 row in set (0.00 sec)

    The MySQL LIKE allows you to put the NOT keyword to find all strings which are unmatchedwith a specific pattern. Suppose you want to search for all employees whose last name are notstarting with B, you can use the following query

    1SELECTemployeeNumber, lastName, firstName

    2FROMemployees

    3WHERElastName NOTLIKE'B%'+----------------+-----------+-----------+| employeeNumber | lastName | firstName |+----------------+-----------+-----------+| 1088 | Patterson | William |

    | 1188 | Firrelli | Julie || 1216 | Patterson | Steve || 1286 | Tseng | Foon Yue || 1323 | Vanauf | George || 1370 | Hernandez | Gerard || 1401 | Castillo | Pamela || 1504 | Jones | Barry || 1611 | Fixter | Andy || 1612 | Marsh | Peter || 1619 | King | Tom |

  • 8/14/2019 BASIC_MYSQL.docx

    34/56

    | 1621 | Nishi | Mami || 1625 | Kato | Yoshimi || 1702 | Gerard | Martin |+----------------+-----------+-----------+14 rows in set (0.00 sec)

    Be noted that SQL LIKE is not case sensitive so b% and B% are the same.

    What if you want to search for records which have a field starting with a wildcard character? Inthis case, you can use ESCAPE to shows that the wildcard characters followed it has literalmeaning not wildcard meaning. If ESCAPE does not specify explicitly, the escape character inMySQL by default is \. For example, if you want to find all products which as product codewhich has _20 embedded on it, you can perform following query

    1SELECTproductCode, productName

    2FROMproducts

    3WHEREproductCode LIKE'%\_20%'

    +-------------+-------------------------------------------+| productCode | productName |+-------------+-------------------------------------------+| S10_2016 | 1996 Moto Guzzi 1100i || S24_2000 | 1960 BSA Gold Star DBD34 || S24_2011 | 18th century schooner || S24_2022 | 1938 Cadillac V-16 Presidential Limousine || S700_2047 | HMS Bounty |+-------------+-------------------------------------------+5 rows in set (0.00 sec)

    MySQL LIKE gives you a convenient way to find records which have character columns matchspecified patterns. Because MySQL LIKE scans the whole table to find all the matching records

    therefore it does not allow database engine to use the index for fast searching. When the data inthe table is big enough, the performance of MySQL LIKE will degrade. In some cases you canavoid this problem by using other techniques to achieve the same result as MySQL LIKE. Forexample, if you want to find all employees which have first name starting with a specified stringyou can use LEFT function in where clause like the following query:

    1SET@str = 'b';

    2SELECTemployeeNumber, lastName, firstName

    3FROMemployees

    4WHERELEFT(lastname,length(@str)) = @str;

    It returns the same result as the query below but it faster because we can leverage the index onthe column lastname.

    1SELECTemployeeNumber, lastName, firstName

    2FROMemployees

    3WHERElastname LIKE'b%'

  • 8/14/2019 BASIC_MYSQL.docx

    35/56

    And another technique to achieve all string which end with a specified string by using RIGHTfunction. Suppose we want to retrieve all employees which have last name ended with on

    string, we can use RIGHT function instead of MySQL LIKE as follows:

    1SET@str = 'on';

    2SELECTemployeeNumber, lastName, firstName3FROMemployees

    4WHERERIGHT(lastname,length(@str)) = @str;+----------------+-----------+-----------+| employeeNumber | lastName | firstName |+----------------+-----------+-----------+| 1088 | Patterson | William || 1216 | Patterson | Steve |+----------------+-----------+-----------+2 rows in set (0.00 sec)

    It returns the same result as the following query

    1SELECTemployeeNumber, lastName, firstName

    2FROMemployees

    3WHERElastname LIKE'%on'

    Combining Result Sets with MySQL UNION

    Summary: In this tutorial, you will learn how to use MySQL UNI ONstatement to combine twoor more result sets from multiple SQL SELECT statements into a single result set.

    Like SQL standard, MySQL UNION allows you to combine two or more result sets frommultiple tables together. The syntax of using MySQL UNION is as follows:

    1SELECTstatement

    2UNION[DISTINCT| ALL]

    3SELECTstatement

    4UNION[DISTINCT| ALL]

    5

    6

    In order to use UNION statement, there are some rules you need to follow:

    The number of columns in each SELECT statement has to be the same . The data type of the column in the column list of the SELECT statement must be the

    same or at least convertible.

  • 8/14/2019 BASIC_MYSQL.docx

    36/56

    By default the MySQL UNION removes all duplicate rows from the result set even if you dontexplicit using DISTINCT after the keyword UNION.

    If you use UNION ALL explicitly, the duplicate rows remain in the result set. You only use thisin the cases that you want to keep duplicate rows or you are sure that there is no duplicate rows

    in the result set.

    Lets practice with couples of examples with MySQL UNION to get a better understanding.

    Suppose you want to combine customersand employeesinfomation into one result set, you usethe following query:

    1SELECTcustomerNumber id, contactLastname name

    2FROMcustomers

    3UNION

    4SELECTemployeeNumber id,firstname name

    5FROMemployees

    Here is the excerpt of the output:

    id name------ ---------------

    103 Schmitt112 King114 Ferguson119 Labrune121 Bergulfsen124 Nelson125 Piestrzeniewicz128 Keitel129 Murphy131 Lee

    When using ORDER BY to sort the result with UNION, you have to use it in the lastSQL SELECT statement. It would be the best to parenthesize all the SELECT statements andplace ORDER BY at the end.

    Suppose you want to sort the combination of employees and customers in the query above bynameandID in ascending order.

    1(SELECTcustomerNumber id,contactLastname name2FROMcustomers)

    3UNION

    4(SELECTemployeeNumber id,firstname name

    5FROMemployees)

    6ORDERBYname,id

  • 8/14/2019 BASIC_MYSQL.docx

    37/56

  • 8/14/2019 BASIC_MYSQL.docx

    38/56

  • 8/14/2019 BASIC_MYSQL.docx

    39/56

  • 8/14/2019 BASIC_MYSQL.docx

    40/56

    condition. In the join condition, you specify the columns to be used formatching row in the two tables. The syntax of MySQL is as follows:

    1SELECTt1.c1, t1.c2,t2.c1,t2.c2

    2FROMt1

    3LEFTJOINt2 ONt1.c1 = t2.c1 (join_condition)

    4WHEREwhere_condition

    The MySQL LEFT JOIN clause works like this: when a row from the lefttable matches a row from the right table based on join_condition, the rows

    content are selected as an output row. When row in the left table has nomatch it is still selected for output, but combined with a fake row from theright table that contains NULL in all columns. In short, the MySQL LEFTJOIN clause allows you to select all rows from the left table even there is nomatch for them in the right table.

    Example of MySQL LEFT JOIN

    Lets take a look at two table customers and orders: If you want to knowwhich customer has which order and each orders status. You can use the

    MySQL LEFT JOIN as follows:

  • 8/14/2019 BASIC_MYSQL.docx

    41/56

    1SELECTc.customerNumber, customerName,orderNUmber, o.status

    2FROMcustomers c

    3LEFTJOINorders o ONc.customerNumber = o.customerNumber;

    There are more rows which are not listed on this screenshot.

    The left table is the customers table so you see all customers are listed as theway MySQL LEFT JOIN clause works. However, there are rows that wehave customer information but all order information are NULL. This meansthose customers do not have any order in our database. The MySQL LEFT

    JOIN clause is very useful when you want to find the records in the left tablethat are unmatched by the right table. You can accomplish this by add aWHERE clause to select only that have NULL values in a right table column.So to find all customers who does not have any order in our database we canuse the MySQL LEFT JOIN clause as follows:

    1SELECTc.customerNumber, customerName,orderNUmber, o.status

    2FROMcustomers c

    3LEFTJOINorders o ONc.customerNumber = o.customerNumber

    4WHEREorderNumber isNULL

  • 8/14/2019 BASIC_MYSQL.docx

    42/56

    There are more rows which are not listed on this screenshot.

    As the result, the query only returns customers which do not have any orderrepresented by NULL values.

    In this tutorial, you have learned how to use MySQL LEF T JOINclause toselect data from multiple tables. You've also learned how to use MySQLLEFT JOINto find unmatched records between two tables.

    There are more returned rows that are not listed on this screenshot

  • 8/14/2019 BASIC_MYSQL.docx

    43/56

    The MySQL INNER JOIN clause compares each row of table products and orderDetails table tofind a pair of rows that has the same productCode. If a pair of rows that have the same, theproduct code, product name and order number are combined into a returned row.

    In this tutorial, you have learned how to useMySQL INNER JOINto select data from multiple

    tables. You have also learned how to use table qualifier to avoid column ambiguous error inMySQL INNER JOIN clause.

    MySQL GROUP BY

    Summary:In this tutorial, you will learn how to use MySQL GROUP BYto group selectedrecords into a set of summary records by the one or more column's value or expression.

    Introducing to MySQL GROUP BY clause

    The MySQL GROUP BYclause is used with SQL SELECT statement to togroup selected records into a set of summary records by the one or morecolumn's value or expression. The MySQL GROUP BY clause is anoptional part of the SQL SELECT statement. The MySQL GROUP BYclause must appear after the WHERE clause or FROM clause if WHEREclause is omitted of the SQL SELECT statement. The MySQL GROUP BY

    clause consists of GROUP BY keyword followed by a list of expressions separated by commas.The following illustrates the MySQL GROUP BY clause:

    1SELECTcol1_,col_2,... col_n, aggregate_function(expression)

    2FROMtable

    3WHEREwhere_conditions

    4GROUPBYcol_1, col_2, ... col_n

    5ORDERBYcolumn_list

    We will examine the GROUP BY clause in details. Lets take a look at the order table in oursample database.

    Example of MySQL GROUP BY clause

    Now, suppose you want to get groups for each order, you can use the MySQL GROUP BYclause as follows:

    http://www.mysqltutorial.org/mysql-inner-join.aspxhttp://www.mysqltutorial.org/mysql-inner-join.aspxhttp://www.mysqltutorial.org/mysql-inner-join.aspxhttp://www.mysqltutorial.org/mysql-inner-join.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    44/56

    1SELECTstatus

    2FROMorders

    3GROUPBYstatus

    +------------+| status |+------------+| Cancelled || Disputed || In Process || On Hold || Resolved || Shipped |+------------+6 rows in set (0.00 sec)

    It seems that the GROUP BY clause only scans for unique occurrences in the status column andreturn the result set. However if you look at the data of the orders table you will see that eachrow in result set above is summary of records that represent a group orders that have the samestatus on the status column.

    MySQL GROUP BY with aggregate function

    Theaggregate functionsallow you to perform calculation of a set of records and return a singlevalue. The most commonaggregate functions are SUM, AVG, MAX, MIN and COUNT. Formore information on aggregate functions, please refer to theaggregate functions in MySQLtutorial.

    Aggregate functions are used with MySQL GROUP BY clause to perform calculation on eachgroup of records on return a single value for each row. Lets say if you want to know how manyorders in each status group you can use the COUNT function as follows:

    1SELECTstatus, count(*)

    2FROMorders

    3GROUPBYstatus

    +------------+----------+| status | count(*) |+------------+----------+| Cancelled | 6 || Disputed | 3 || In Process | 6 || On Hold | 4 || Resolved | 4 || Shipped | 303 |+------------+----------+

    http://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspxhttp://www.mysqltutorial.org/mysql-aggregate-functions.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    45/56

    6 rows in set (0.00 sec)

    The query counts number of orders for each orders status.

    MySQL GROUP BY vs. ANSI SQL GROUP BY

    MySQL follows ANSI SQL. However, there are two differences the way GROUP BY works inMySQL and ANSI SQL.

    In ANSI SQL you must group by all columns you specifies in the SELECT clause. MySQL does nothave this restriction. You can have additional columns in the SELECT clause that are not in the

    GROUP BY clause.

    MySQL also allows you to sort the group order in which the results are returned. The defaultorder is ascending.

    If you want to see the result of the query above in the descending order, you can do it as follows:

    1SELECTstatus, count(*)

    2FROMorders

    3GROUPBYstatus DESC;

    +------------+----------+| status | count(*) |+------------+----------+| Shipped | 303 || Resolved | 4 || On Hold | 4 || In Process | 6 || Disputed | 3 || Cancelled | 6 |+------------+----------+6 rows in set (0.00 sec)

    As you see the status of orders now are in reverse alphabetical order. By default it is ascendingorder determined by ASC.

    In this tutorial, you have learned how to use MySQL GROUP BY to retrieve data records in-group. Youve also learned how to sort the result set in the MySQL GROUP BY clause

    supported only in MySQL.

    MySQL HAVING

    Summary: In this tutorial, you will learn how to use MySQL HAVINGclause to specify a filter

    condition for a group of records or an aggregate.

  • 8/14/2019 BASIC_MYSQL.docx

    46/56

    Introducing MySQL HAVING clause

    The MySQL HAVING clause is an optional part of and used only with the SQL SELECTstatement. The MySQL HAVING clause specifies a filter condition for a group of record or anaggregate. The MySQL HAVING is often used withMySQL GROUP BYclause. When using

    withMYSQL GROUP BYclause, you can apply filter condition of the HAVING clause only tothe columns appear in the GROUP BY clause. If theMySQL GROUP BY clause is omitted, theMySQL HAVING clause will behave like a WHERE clause. Notes that the MySQL HAVINGclause applies to groups as a whole while the WHERE clause applies to individual rows.

    Examples of MySQL HAVING clause

    Lets take a look at an example of using MySQL HAVING clause to have a betterunderstanding.

    We have orderDetails table in oursample database.We can use theMySQL GROUP BY clause

    to get all orders, number of items sold and total values in each order as follows:

    1SELECTordernumber,

    2 sum(quantityOrdered) ASitemsCount,

    3 sum(priceeach) AStotal

    4FROMorderdetails

    5GROUPBYordernumber

    http://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    47/56

    Now you can ask what order has total value greater than $1000. In this case, you need to use theMySQL HAVING clause on aggregate to answer that question.

    1SELECTordernumber,

    2 sum(quantityOrdered) ASitemsCount,

    3 sum(priceeach) AStotal

    4FROMorderdetails

    5GROUPBYordernumber

    6HAVINGtotal > 1000

  • 8/14/2019 BASIC_MYSQL.docx

    48/56

    We use column alias for the aggregatesum(priceeach)as totalso in the HAVING clause we justhave to specify that column alias totalinstead of typing the aggregatesum(priceeach) again.

    You can use a complex condition in the MySQL HAVING clause such as OR, AND operators.For example if you want to know what order has total value greater than $1000 and has more

    than 600 items in it. You can use the following query to find out:

    1SELECTordernumber,

    2 sum(quantityOrdered) ASitemsCount,

    3 sum(priceeach) AStotal

    4FROMorderdetails

    5GROUPBYordernumber

    6HAVINGtotal > 1000 ANDitemsCount > 600

    The MySQL HAVING clause is useful only with the MySQL GROUP BY clause for building

    output of high-level reports. For example, you can use the MySQL HAVING clause to answerquestions like how many order has total values more than 1000 this month, this quarter and thisyear?...

    In this tutorial, you have learned how to use the MySQL HAVI NGclause together with theMySQL GROUP BY to specify filter condition on a group or aggregate.

  • 8/14/2019 BASIC_MYSQL.docx

    49/56

    Inserting Data into Database Tables

    Summary:In the previous tutorials you learn different ways toquery data from database tableby using SQL SELECT statement.Are you wonder that how data is added into those table? Inthis tutorial, you will learn do it by using SQL INSERT statement.

    INSERT Statement

    INSERT statement allows you to insert one or more rows to the table. In MySQL, the INSERTstatement forms are listed as follows:

    1INSERT[LOW_PRIORITY | DELAYED] [IGNORE]

    2 [INTO] table_name [(column_name,...)]

    3 VALUES((expression | DEFAULT),...),(...),...

    1INSERT[LOW_PRIORITY | DELAYED] [IGNORE]

    2 [INTO] table_name [(column_name,...)]

    1INSERT[LOW_PRIORITY | DELAYED] [IGNORE]

    2 [INTO] table_name

    3 SETcolumn_name=(expression | DEFAULT), ...

    As you can see INTO in the INSERT statement is optional. In the first form, you insert a newdata row into an existing table by specifying the column name and data for each. As an exampleto insert a new office to the officestable in the sample database you can do as follows:

    01INSERTINTOclassicmodels.offices

    02 (officeCode,

    03 city,

    04 phone,

    05 addressLine1,

    http://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    50/56

    06 addressLine2,

    07 state,

    08 country,

    09 postalCode,

    10 territory

    11 )

    12 VALUES

    13 ('8',

    14 'Boston',

    15 '+1 215 837 0825',

    16 '1550 dummy street',

    17 'dummy address',

    18 'MA',

    19 'USA',

    20 '02107',

    21 'NA'

    22 )

    In the second form, instead of providing explicit data, you select it from other table by usingSELECT statement. This form allows you to copy some or some part of data from other table tothe inserted table. As an example, we can create a temporary table and insert all offices whichlocate in US into that one by using this query:

    1INSERTINTOtemp_table

    2SELECT* FROMoffices WHEREcountry = 'US'

    The third form enables you to specify the column you want to insert the data. For example, wehave the query like this:

  • 8/14/2019 BASIC_MYSQL.docx

    51/56

    1INSERTINTOproductlines

    2SETproductLine = 'Luxury Cars'

    It means we only insert the data intoproductLine column inproductLines table.

    Updating Data in Database Tables

    Summary: Updating existing data is one of the most important task when you work with

    database. In this tutorial, you will learn how to use MySQL UPDATEstatement to update data

    in database tables.

    SQL UPDATE statement is used to update existing data in database tables. It can be used tochange values of single row, group of rows or even all rows in a table. In MySQL, the SQLUPDATE statement form is as below:

    1UPDATE[LOW_ PRIORITY] [IGNORE] table_name [, table_name...]

    2 SETcolumn_name1=expr1

    3 [, column_name2=expr2 ...]

    4[WHEREcondition]

    Let's examine the MySQL UPDATE statement in details:

    Followed by the UPDATE keyword is the name of a table you want to change the data. InMySQL, you can change the data of multiple tables at a time. If an UPDATE command

    violates any integrity constraint, MySQL does not perform the update and it will issue anerror message.

    The SET clause determines the columns' name and the changed values. The changedvalues could be a constant value, expression or even asubquery.

    WHERE clause determines which rows of the tables will be updated. It is an optional partof SQL UPDATE statement. If WHERE clause is ignored, all rows in the tables will beupdated. The WHERE clause is so important that you should not forget. Sometimes youwant to change just one row of a table but you forget WHERE clause so you accidentallyupdate the whole table.

    LOW_ PRIORITY keyword is used to delay the execution until no other clientapplications reading data from the table. This is used for controlling the update process in

    MySQL database server. IGNORE keyword is used to execute the update even errors occurred during the

    execution. The errors in the update process could be duplicate value on unique column, ornew data does not match with the column data type. In the first situation data is notupdated and in the second one MySQL tries to convert the data into closest valid values.

    Let's practice with a couple of examples in our sample database to understand more aboutSQL UPDATE statement.

    http://www.sqltutorial.org/sql-subqueries.aspxhttp://www.sqltutorial.org/sql-subqueries.aspxhttp://www.sqltutorial.org/sql-subqueries.aspxhttp://www.sqltutorial.org/sql-subqueries.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    52/56

    In employeestable, if you want to update the email of Mary Patterson with employeeNumber 1with the new email as [email protected], you can execute the followingquery:

    Make sure we are truly updating the data we select it first to see what the current data looks like.

    1SELECTfirstname,

    2 lastname,

    3 email

    4FROMemployees

    5WHEREemployeeNumber = 1+-----------+-----------+--------------------------------+| lastname | firstname | email |+-----------+-----------+--------------------------------+| Patterson | Mary | [email protected] |+-----------+-----------+--------------------------------+1 row in set (0.02 sec)

    Update her email to the new email [email protected]

    1UPDATEemployees

    2SETemail = '[email protected]'

    3WHEREemployeeNumber = 1

    Execute the select query above again; you will see the email change to the new value.

    +-----------+-----------+------------------------------------+| lastname | firstname | email |

    +-----------+-----------+------------------------------------+| Patterson | Mary | [email protected] |+-----------+-----------+------------------------------------+1 row in set (0.00 sec)

    In this tutorial, you've learned how to use SQL UPDATE statement in MySQL to update data ofdatabase tables.

    Deleting Records from Tables Using MySQL

    DELETE

    Summary: The MySQL DELETEstatement not only allows you to delete record from one table

    but also multiple tables. In this tutorial, you will learn how to use MySQL DELETE statement

    with examples.

    To remove all rows or records from a database table you use MySQL DELETE statement. Thefollowing illustrates MySQL DELETEstatement:

  • 8/14/2019 BASIC_MYSQL.docx

    53/56

    1DELETE[LOW_PRIORITY] [QUICK]

    2 FROMtable_name

    3[WHEREconditions] [ORDERBY...] [LIMIT rows]

    1DELETE[LOW_PRIORITY] [QUICK]

    2 table_name[.*] [, table_name[.*] ...]

    3FROMtable-references

    4[WHEREwhere_definition]

    1DELETE[LOW_PRIORITY] [QUICK]

    2FROMtable_name[.*] [, table_name[.*] ...]

    3USING table-references

    4[WHEREwhere_definition]

    Let's examine the MySQL DELETE statements in details as below:

    In the first form of MySQL DELETE statement, followed the DELETE FROM part is thetable name where you want to delete records. The WHERE clause specifies condition tolimit which rows you want to to remove. If a record meets WHERE condition, it will beremoved from the database table permanently. If the WHERE clause is ignored in theMySQL DELETE statement, all rows of the table are deleted.

    The second form of MySQL DELETE statement, It deletes records from multiple tableswhich reference to other table.

    The third form of MySQL DELETE statement is quite similar to the second one exceptUsing keyword is used instead of FROM keyword.

    Let's have a couple of examples of using MySQL DELETE statement in thesample database.

    It is recommended that youmake a copy of employee tablebefore practicing with theMySQL DELETE statement.

    Suppose you want to delete all employees in an office with officeNumber is 4, just execute thefollowing query:

    1DELETEFROMemployees

    2WHEREofficeCode = 4

    To delete all employees from all offices, just remove the WHERE condition as follows:

    1DELETEFROMemployees

    It will remove all rows from employeestable.

    If you want to delete all employee who work for office with officecode1 and also that office.You can use the second form of MySQL DELETE statement to delete data from multiple tablesas follows:

    http://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-copy-table-data.aspxhttp://www.mysqltutorial.org/mysql-copy-table-data.aspxhttp://www.mysqltutorial.org/mysql-copy-table-data.aspxhttp://www.mysqltutorial.org/mysql-copy-table-data.aspxhttp://www.mysqltutorial.org/mysql-copy-table-data.aspxhttp://www.mysqltutorial.org/mysql-copy-table-data.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    54/56

    1DELETEemployees,offices

    2FROMemployees,offices

    3WHEREemployees.officeCode = offices.officeCode AND

    4 offices.officeCode = 1

    You can achieve the same above effect by using the third form of DELETE statement as below:

    1DELETEFROMemployees,offices

    2USING employees,offices

    3WHEREemployees.officeCode = offices.officeCode AND

    4 offices.officeCode = 1

    In this tutorial, you've learned various forms of MySQL DELETE statement to delete recordsfrom one or multiple database tables

    How to Use MySQL REPLACE to Insert orUpdate Data

    Summary: In this tutorial, you will learn how to use MySQL REPLACE statement to insert or

    update data in database tables.

    MySQL REPLACE statement is a MySQL extension to SQL standard. MySQL REPLACEworks like theINSERT statementwith the following rules:

    If the record being inserting does not exist, MySQL REPLACE will insert a new record. If the record being inserting exists, MySQL REPLACE will delete the old record first and

    then insert a new record with new values.

    In order to use MySQL REPLACE you need to have at least both INSERT and DELETEprivileges for the table.

    The first form of MySQL REPLACE statementis similar to the INSERT statement except thekeyword INSERT is replaced by the REPLACE keyword as follows:

    1REPLACEINTOtable_name(column_name1,column_name2,)

    2VALUES(value1,value2,)

    For example if you want to insert a new office into offices table, you use the following query:1REPLACEINTOoffices(officecode,city)

    2VALUES(8,'San Jose')

    Note that all values of missing columns in the REPLACE statement will be set to default value.

    Now if you want to update the inserted office with San Mateo city, we can do it as follows:

    http://www.mysqltutorial.org/mysql-insert-statement.aspxhttp://www.mysqltutorial.org/mysql-insert-statement.aspxhttp://www.mysqltutorial.org/mysql-insert-statement.aspxhttp://www.mysqltutorial.org/mysql-insert-statement.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    55/56

    1REPLACEINTOoffices(officecode,city)

    2VALUES(8,'San Mateo')

    You see that two rows affected by the query above because the existing record is deleted and thenew record is inserted.

    The second form of MySQL REPLACE like UPDATE statement as follows:

    1REPLACEINTOtable_name

    2SETcolumn_name1 = value1 AND

    3 column2 = value2

    Note that there is no WHERE clause is specified in the REPLACE statement. For example, ifyou want to update office in San Mateo with officecode8 you can do it as follows:

    1REPLACEINTOoffices

    2SETofficecode = 8 and3 city = Santa Cruz

    The third form of MySQL REPLACE is similar toSQL INSERT INTO SELECTstatement asfollows:

    1REPLACEINTOtable_name1(column_name1,column_name2,)

    2SELECTcolumn_name1, column_name2

    3FROMtable_name2

    4WHEREwhere_condition

    Lets say if we want to copy the office with officecode 1, we can do it as follows:

    01REPLACEINTOoffices(officecode,

    02 city,

    03 phone,

    04 addressline1,

    05 addressline2,

    06 state,

    07 country,

    08 postalcode,

    09 territory)

    10SELECT(SELECTMAX(officecode) + 1 FROMoffices),

    11 city,

    12 phone,

    13 addressline1,

    14 addressline2,

    15 state,

    http://www.mysqltutorial.org/mysql-insert-statement.aspxhttp://www.mysqltutorial.org/mysql-insert-statement.aspxhttp://www.mysqltutorial.org/mysql-insert-statement.aspxhttp://www.mysqltutorial.org/mysql-insert-statement.aspx
  • 8/14/2019 BASIC_MYSQL.docx

    56/56

    16 country,

    17 postalcode,

    18 territory

    19FROMoffices

    20WHEREofficecode = 1

    There are several important points you need to know before using MySQL REPLACE statement:

    If you are developing an application that potentially supports not only MySQL database,try to avoid using MySQL REPLACE because other database management system maynot support the REPLACE statement. You can use the combination ofINSERT andDELETEstatement instead.

    If you are using MySQL REPLACE in the table which hastriggers associate with it andif the deletion of duplicate key happens, the triggersare fired in the following orders:

    1. Before insert2. Before delete3. After delete4. After insert

    It is preferred usingMySQL UPDATEstatement to using MySQL REPLACE in caseyou just want to update data. BecauseMySQL UPDATEperforms faster than MySQLREPLACE.

    In this tutorial, you've learned different forms of MySQL REPLACEstatement to insert orupdate data in database tables.

    http://www.mysqltutorial.org/mysql-insert-statement.aspxhttp://www.mysqltutorial.org/mysql-insert-statement.aspxhttp://www.mysqltutorial.org/mysql-delete-statement.aspxhttp://www.mysqltutorial.org/mysql-delete-statement.aspxhttp://www.mysqltutorial.org/mysql-triggers.aspxhttp://www.mysqltutorial.org/mysql-triggers.aspxhttp://www.mysqltutorial.org/mysql-triggers.aspxhttp://www.mysqltutorial.org/mysql-update-data.aspxhttp://www.mysqltutorial.org/mysql-update-data.aspxhttp://www.mysqltutorial.org/mysql-update-data.aspxhttp://www.mysqltutorial.org/mysql-update-data.aspxhttp://www.mysqltutorial.org/mysql-update-data.aspxhttp://www.mysqltutorial.org/mysql-update-data.aspxhttp://www.mysqltutorial.org/mysql-update-data.aspxhttp://www.mysqltutorial.org/mysql-update-data.aspxhttp://www.mysqltutorial.org/mysql-triggers.aspxhttp://www.mysqltutorial.org/mysql-delete-statement.aspxhttp://www.mysqltutorial.org/mysql-insert-statement.aspx