My SQL(Basic)

Embed Size (px)

Citation preview

  • 7/29/2019 My SQL(Basic)

    1/52

    Summary: in this tutorial, you will learn how to manage databases in MySQL. You will learn how to create a new databases, list all

    databases in the MySQL database server and remove databases from database catalog.

    Lets start creating a new database in MySQL.

    Creating Database

    Before doing anything else with data, you need to create a database. A database is a container of data. It stores contact, vendor or customer

    or any kind of data you can think of. In MySQL, a database is a collection of objects that are used to store and manipulate data such as

    tables, stored proceduresetc. To create a database in MySQL, you useCREATE DATABASE statement as follows:

    ?

    1 CREATEDATABASE[IF NOTEXISTS] database_name;

    Lets examine the CREATE DATABASE statement in greater detail:

    Followed by CREATE DATABASE statement is database name you want MySQL to create. It is recommended that database nameshould be meaningful and descriptive.

    IF NOT EXISTS is an optional part of the statement. The IF NOT EXISTS statement prevents you from error if there is a database withthe same name exists in the database catalog. Of course, you cannot have 2 databases with the same name in a same database

    catalog.For example, to create classicmodels database, you just need to execute the CREATE DATABASE statement as follows:

    ?

    1 CREATEDATABASEclassicmodels;

    After executing the statement, MySQL will returns you a message to notify the new database created successfully or not.

    Showing Databases Statement

    SHOW DATABASE statement shows all databases in your database server. You can use SHOW DATABASE statement to check the

    database youve created or to see all the databases on the database server before you create a new database, for example:

    ?

    1 SHOW DATABASES;In my database server, the output is :

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    +--------------------+

    | Database |+--------------------+| information_schema || classicmodels || mysql |+--------------------+8 rowsinset(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.

    ?

    1 USE database_name;

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

    http://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.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-sample-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspx
  • 7/29/2019 My SQL(Basic)

    2/52

    ?

    1 USE 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 objects inside the database are permanently deleted

    and cannot be undone. So it is very important to execute this query with cares. To delete a database you can use DROP DATABASE

    statement, which is a standard SQL statement as well.

    ?

    1 DROPDATABASE[IF EXISTS] database_name;

    You need to specify database name after the DROP DATABASE statement. Like CREATE DATABASE statement, IF EXIST is an optional

    part to prevent you from removing database which does not exist in database catalog.

    If you want to practice with DROP DATABASE statement, you can first create a new temporary database, make sure that it is created and

    remove it. The sequence of SQL query to execute is as follows:

    ?

    1

    2

    3

    CREATEDATABASEIF NOTEXISTS temp_database;SHOW DATABASES;DROPDATABASEIF EXISTS temp_database;

    In this tutorial, youve learned how to create a new database, drop an existing database, select the database you want to work with and list

    all databases in database catalog.

    Summary: in this tutorial, you will learn various MySQL table types, or storage engine. It is essential to understand the features of each

    table type in MySQL so that you can use them effectively to maximize the performance of your databases.

    MySQL provides various storage engines for its tables as below:

    MyISAM InnoDB MERGE MEMORY (HEAP) ARCHIVE CSV FEDERATEDEach storage engine has its own advantages and disadvantages. It is crucial to understand each storage engine features and choose the

    most appropriate one for your tables to maximize the performance of the database. In the following sections we will discuss about each

    storage engine and its features so that you can decide which one to use.

    MyISAM

    MyISAM extends the former ISAM storage engine. The MyISAM tables are optimized for compression an speed. MyISAM tables are also

    portable between platforms and OSs.

    The size of MyISAM table can be up to 256TB, which is huge. In addition, MyISAM tables can be compressed into read-only tables to save

    space. At startup, MySQL checks MyISAM tables for corruption and even repair them in case of errors. The MyISAM tables are not

    transaction-safe.

    Before MySQL version 5.5, MyISAM is the default storage engine when you create a table without explicitly specify the storage engine. From

    version 5.5, MySQL uses InnoDB as the default storage engine.

    http://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspx
  • 7/29/2019 My SQL(Basic)

    3/52

    InnoDB

    The InnoDB tables fully support ACID-compliant and transactions. They are also very optimal for performance. InnoDB table supports foreign

    keys, commit, rollback, roll-and forward operations. The size of the InnoDB table can be up to 64TB.

    Like MyISAM, the InnoDB tables are portable between different platforms and OSs. MySQL also checks and repair InnoDB tables, if

    necessary, at startup.

    MERGE

    A MERGE table is a virtualtable that combines multiple MyISAM tables, which has similar structure, into one table. The MERGE storage

    engine is also known as the MRG_MyISAM engine. The MERGE table does not have its own indexes; it uses indexes of the component

    tables instead.

    Using MERGE table, you can speed up performance in joining multiple tables. MySQL only allows you to perform SELECT, DELTE,

    UPDTATE and INSERT operations on the MERGE tables. If you useDROP TABLE statementon a MERGE table, only MERGE specification

    is removed. The underlying tables will not be affected.

    Memory

    The memory tables are stored in memory and used hash indexes so that they are faster than MyISAM tables. The lifetime of the data of thememory tables depends on the up time of the database server. The memory storage engine is formerly known as HEAP.

    Archive

    The archive storage engine allows you to store a large number of records, which for archiving purpose, into a compressed format to save

    disk space. The archive storage engine compresses a record when it is inserted and decompress it using zlib library as it is read.

    The archive tables only allow INSERT and SELECT commands. The archive tables do not support indexes, so reading records requires a full

    table scanning.

    CSV

    The CSV storage engine stores data in comma-separated values file format. A CSV table brings a convenient way to migrate data into non-

    SQL applications such as spreadsheet software.

    CSV table does not support NULL data type and read operation requires a full table scan.

    FEDERATED

    The FEDERATED storage engine allows you to manage data from a remote MySQL server without using cluster or replication technology.

    The local federated table stores no data. When you query data from a local federated table, the data is pull automatically from the remote

    federated tables.

    Choosing MySQL Table Types

    You can download the following checklist to choose the most appropriate storage engine, or table type, based on various criteria.

    Summary: In this tutorial, you will learn various MySQL data types to use them effectively in database 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 data type 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.

    http://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-table
  • 7/29/2019 My SQL(Basic)

    4/52

    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 and approximate numeric data types including

    integer, fixed-point and floating point. In addition, MySQL also supports BIT data type for storing bit field values. Numeric types can be

    signed or unsigned except BIT type. The following table shows you the summary of numeric types in MySQL:

    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 regular expression. 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

    MEDIUMBLOB A 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 to store the year without date and month, you can use YEAR data type. Here is the table which

    showing MySQL date and type data types:

    Date and Time

    TypesDescription

    DATE A date value in CCYY-MM-DD format

    TIME A time value in hh:mm:ss format

  • 7/29/2019 My SQL(Basic)

    5/52

    Date and Time

    TypesDescription

    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 TypesMySQL support many spatial data types as below table which contains various kind of geometrical and geographical values.

    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

    GEOMETRYCOLLECTION A collection of GEOMETRY values

    MULTILINESTRING A collection of LINESTRING values

    MULTIPOINT A collection of POINT values

    MULTIPOLYGON A collection of POLYGON values

    Summary: in this tutorial, we will show you how to create new tables in a particular database usingMySQL CREATE TABLE statement.

    MySQL CREATE TABLE syntax

    In order to create a new table within a database, you use the MySQL CREATE TABLE statement. The CREATE TABLE statement is one of

    the most complex statement in MySQL. The following illustrates the simple syntax of the CREATE TABLE statement:

    ?

    1

    2

    3

    CREATETABLE[IF NOTEXISTS] table_name(column_list

    ) engine=table_type

    Lets examine the syntax in greater detail:

    First, you specify the name of table that you want to create after the CREATE TABLE clause. The table name must be unique within adatabase. The IF NOT EXISTS is an optional part of the statement that allows you to check if the table you are creating already exists

    in the database. If this is the case, MySQL will ignore the whole statement and it will not create any new table. We highly recommend

    you to use IF NOT EXISTS in every CREATE TABLE statement for preventing from error of creating a new table that already exists.

    Second, you specify a list of columns for the table in the column_listsection. Columns are separated by a comma (,). We will show youhow to define columns in more detail in the next section.

    Third, you need to specify the storage engine for the table in the engine clause. You can use any storage engine such asInnoDB, MyISAM, HEAP, EXAMPLE, CSV, ARCHIVE, MERGE FEDERATED or NDBCLUSTER. If you dont explicit declare the

    storage engine, MySQL will useInnoDB by default.

    InnoDB became the default storage engine s ince MySQL version 5.5. InnoDB brings many benefits of relational database management

    system such as ACID transaction, referential integrity and crash recovery. In the previous versions, MySQL used MyISAM as the defaultstorage engine.

    To define a column for the table in the CREATE TABLE statement, you use the following syntax:

    ?

    1

    2

    column_name data_type[size] [NOTNULL|NULL] [DEFAULTvalue][AUTO_INCREMENT]

    http://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-create-table/
  • 7/29/2019 My SQL(Basic)

    6/52

    The most important components of the syntax above are:

    column_name specifies the name of the column. Each column always associates with a specificdata typeand the sizee.g. VARCHAR(255).

    NOT NULL or NULL indicates that the column accepts NULL value or not. DEFAULT value is used to specify the default value of the column.

    AUTO_INCREMENTindicates that the value of column is increased by one whenever a new record is inserted into the table. Each tablehas one and only one AUTO_INCREMENT column.

    If you want to set particular columns of the table as the primary key, you use the following syntax:

    ?

    1 PRIMARYKEY(col1,col2,...)

    Example of MySQL CREATE TABLE statement

    Lets practice with an example of creating a new table namedtasks in oursample databaseas follows:

    You can use the CREATE TABLE statement to create the tasks table as follows:

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    CREATETABLEIF NOTEXISTS tasks (task_id int(11) NOTNULLAUTO_INCREMENT,subject varchar(45) DEFAULTNULL,start_date DATEDEFAULTNULL,end_date DATEDEFAULTNULL,description varchar(200) DEFAULTNULL,PRIMARYKEY(task_id)

    ) ENGINE=InnoDB

    In this tutorial, you have learned how to use MySQL CREATE TABLE to create a new tables within a database.

    Summary: in this tutorial, you will learn how to use MySQL ALTER TABLE statement to change the structure of existing tables.

    MySQL ALTER TABLE syntax

    MySQL ALTER TABLE statement is used to change the structure of existing tables. You can use MySQL ALTER TABLE to add or drop

    column, change data type of column, add primary key, rename table and many more. The following illustrates the MySQL ALTER TABLE

    syntax:

    ?

    http://www.mysqltutorial.org/mysql-data-types.aspxhttp://www.mysqltutorial.org/mysql-data-types.aspxhttp://www.mysqltutorial.org/mysql-data-types.aspxhttp://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-create-table/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-create-table/http://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-data-types.aspx
  • 7/29/2019 My SQL(Basic)

    7/52

    1 ALTERTABLEtable_name action1[,action2,]

    First, you specify the table name that you want to change after the ALTER TABLE clause.

    Next, you list a set of actions that you want to apply to the table. An action can be anything such as adding a new column, adding primary

    key, renaming tableetc. MySQL ALTER TABLE statement allows you to apply multiple actions using a single ALTER TABLE statement,

    each action is separated by a comma.

    Lets create a new table for practicing MySQL ALTER TABLE statement. Were going to create a ne w table named tasks in oursample

    database. Here is the script for creating tasks table.

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    CREATE TABLEtasks (

    task_id INTNOTNULL,

    subject VARCHAR(45) NULL,

    start_date DATENULL,

    end_date DATET NULL,

    description VARCHAR(200) NULL,

    PRIMARYKEY(task_id) ,

    UNIQUEINDEXtask_id_UNIQUE (task_id ASC) );

    Changing columns using MySQL ALTER TABLE statement

    Using MySQL ALTER TABLE statement to set auto-increment attribute for a column

    Suppose we want thevalue of the task_idcolumn to be increased automatically by one whenever you insert a new task into the tasks table.

    In order to accomplish this, we use the MySQL ALTER TABLE statement to set the attribute of the task_id column to AUTO_INCREMENT

    as 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-sample-database.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspxhttp://www.mysqltutorial.org/mysql-sample-database.aspx
  • 7/29/2019 My SQL(Basic)

    8/52

    1

    2

    ALTERTABLEtasks

    CHANGE COLUMNtask_id task_id INT(11) NOTNULL

    AUTO_INCREMENT;

    We can verify the change by adding some records to the tasks table.

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    INSERTINTOtasks(subject,

    start_date,

    end_date,

    description)

    VALUES('Learn MySQL ALTER TABLE',

    Now(),

    Now(),

    'Practicing MySQL ALTER TABLE statement');

    INSERTINTOtasks(subject,

    start_date,

    end_date,

    description)

    VALUES('Learn MySQL CREATE TABLE',

    Now(),

    Now(),

    'Practicing MySQL CREATE TABLE statement');

    And query data to see if the value of the task_idcolumn is increased by one each time you insert a new record:

    ?

    1

    2

    SELECTtask_id, description

    FROMtasks

    http://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspx
  • 7/29/2019 My SQL(Basic)

    9/52

    Using MySQL ALTER TABLE statement to add a new column into a table

    Because of the new business requirement, we need to add a new column called complete to store percentage of completion for each task in

    the tasks table. In this case, we can use MySQL ALTER TABLE to add a new column as follows:

    ?

    1

    2

    3

    ALTERTABLEtasks

    ADDCOLUMNcomplete DECIMAL(2,1) NULL

    AFTERdescription;

    Using MySQL ALTER TABLE to drop a column from a table

    Suppose we dont want to store description of tasks in thetasks table anymore so we have to remove it. The following command allows you

    to remove description column of the tasks table:

    ?

    1

    2

    ALTERTABLEtasks

    DROPCOLUMNdescription;

    Renaming table using MySQL ALTER TABLE statement

    We can use MySQL ALTER table statement to rename a table. Notice that before renaming a table, you should take a serious consideration

    to see if the change affects both database and application layers.

    We can rename ourtasks table to work_items table as follows:

    ?

    1

    2

    ALTERTABLEtasks

    RENAME TOwork_items;

    In this tutorial, youve learned how to use MySQL ALTER TABLE statement to change existing table structure as well as to rename table.

    Summary: in this tutorial, we will show you how to remove existing tables using MySQL DROP TABLEstatement.

    MySQL DROP TABLE statement syntax

    In order to remove existing tables, you use the MySQL DROP TABLE statement. The syntax of the DROP TABLE is as follows:

    ?

    1

    2

    DROP[TEMPORARY] TABLE[IF EXISTS] table_name [,table_name] ...[RESTRICT| CASCADE]

    http://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspx
  • 7/29/2019 My SQL(Basic)

    10/52

    The DROP TABLE statement removes tables and their data from a particular database. It allows you to remove multiple tables at a time by

    naming them in a comma-separated list.

    The TEMPORARY flag allows you to remove only temporary tables. It is very convenient to ensure that you do not accidentally remove non-

    temporary tables.

    The addition IF EXISTS allows you to hide the error message in case one or more table in the list does not exist. When you use IF EXISTS,MySQL generates a NOTE, which can be retrieved using SHOW WARNING statement. It is important to notice that the DROP TABLE

    statement still removes all existing tables and issues an error message or a NOTE when you have non-existent tables in the list.

    The DROP TABLE statement only removes table and its data. However it does not remove specific user privileges associated with the table.

    Therefore if a table is later re-created with the same name, the existing privileges will apply to the new table, which poses a security risk.

    The RESTRICT and CASCADE flags are reserved for the future versions of MySQL.

    Last but not least, you must have DROP privileges for each table in order to remove it.

    MySQL DROP TABLE example

    We are going to remove the table tasks that we created in the previous tutorial oncreating tables using CREATE TABLE statement. In

    addition, we also remove a non-existent table to practice with SHOW WARNING statement. The query is as follows:

    ?

    1 DROPTABLEIF EXISTS tasks, nonexistent_table;

    If you check the database, you will see that the table tasks was removed. We can check the NOTE, which is generated by MySQL because

    of non-existent table. using SHOW WARNING statement as follows:

    ?

    1 SHOW WARNINGS;

    MySQL DROP TABLE LIKE

    Image you have a lot of table that has prefix test in your database and you want to remove them all instead of remove one table at a

    time. Unfortunately MySQL does not provide DROP TABLE LIKE to allow you to remove tables based on pattern matching like the following:

    ?

    1 DROP TABLE LIKE '%pattern%'

    However there are some workarounds. We will discuss one of them here for your reference.

    Lets start creatingtest* tables for the sake of demonstration.

    ?

    1

    2

    3

    4

    5

    6

    7

    CREATETABLEIF NOTEXISTS test1(id int(11) NOTNULLAUTO_INCREMENT,PRIMARYKEY(id)

    );

    CREATETABLEIF NOTEXISTS test2 LIKEtest1;CREATETABLEIF NOTEXISTS test3 LIKEtest1;CREATETABLEIF NOTEXISTS test4 LIKEtest1;

    http://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-create-table/
  • 7/29/2019 My SQL(Basic)

    11/52

    8

    Weve create four tables test1, test2, test3 and test4 with the same structure.

    Suppose you want to remove all test*table at a time, you can do as follows:

    First, you declare two variables that accepts database schema and a pattern that you want to the tables to match:

    ?

    1

    2

    3

    -- set table schema and pattern matching for tablesSET @schema = 'classicmodels';SET @pattern = 'test%';

    Next, you need to build a dynamic DROP TABLE statement:

    ?

    1

    2

    3

    45

    6

    -- build dynamic sql (DROP TABLE tbl1, tbl2...;)SELECTCONCAT('DROP TABLE',GROUP_CONCAT(CONCAT(@schema,'.',table_name)),';') INTO@droplike

    FROMinformation_schema.tablesWHERE@schema= database()ANDtable_name LIKE@pattern;

    Basically, the query is telling MySQL to go to the table information_schema_tables, which contains data of all tables in all databases, and

    concatenates all tables in the database @schema (classicmodels ) that match the pattern @pattern (test%) with prefix DROP TABLE. The

    GROUP_CONCAT function creates a comma-separated list of tables.

    Then, we can display the dynamic SQL to verify if it works correctly:

    ?

    1

    2

    -- display the dynamic sql statementSELECT@droplike;

    You can see that it works as expected.

    After that, you can execute the statement usingprepared statement in MySQLas follows:

    ?

    1

    2

    3

    4

    -- execute dynamic sqlPREPAREstmt FROM@dropcmd;EXECUTEstmt;DEALLOCATEPREPAREstmt;

    For more information on MySQL prepared statement, check it out theMySQL prepared statementtutorial.

    Putting it all together.

    ?

    1

    2

    -- set table schema and pattern matching for tablesSET@schema= 'classicmodels';SET@pattern = 'test%';

    http://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-prepared-statement.aspxhttp://www.mysqltutorial.org/mysql-prepared-statement.aspxhttp://www.mysqltutorial.org/mysql-prepared-statement.aspxhttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-prepared-statement.aspxhttp://www.mysqltutorial.org/mysql-prepared-statement.aspxhttp://www.mysqltutorial.org/mysql-prepared-statement.aspxhttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-prepared-statement.aspxhttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-prepared-statement.aspxhttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-tablehttp://www.mysqltutorial.org/mysql-drop-table
  • 7/29/2019 My SQL(Basic)

    12/52

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    -- build dynamic sql (DROP TABLE tbl1, tbl2...;)SELECTCONCAT('DROP TABLE',GROUP_CONCAT(CONCAT(@schema,'.',table_name)),';') INTO@droplikeFROMinformation_schema.tables

    WHERE@schema

    = database()

    ANDtable_name LIKE@pattern;

    -- display the dynamic sql statementSELECT@droplike;

    -- execute dynamic sqlPREPAREstmt FROM@dropcmd;EXECUTEstmt;DEALLOCATEPREPAREstmt;

    So next time if you want to drop many tables that have a specific pattern in a particular database, you just use the script above to save time.

    All you need to do is replacing thepattern and the database schema in @pattern and @schema variables. If you often have to deal with this

    task, you can always develop astored procedurebased on the script above to reuse it in the future.

    In this tutorial, weve shown you how to use MySQL DROP TABLE statement to remove existing tables in a particular database. We also

    shown you a workaround that allows you to use MySQL DROP TABLE statement to remove tables based on pattern matching.

    Summary: in this tutorial, you will learn how to work with MySQL index and how to take advantages of MySQL index to speed up the

    data retrieval. We will introduce several SQL statements to allow you to manage MySQL index.

    Database index, or just index, helps speed up the retrieval of data from tables. When you query data from database tables, first MySQL

    checks if the indexes of tables exists, if yes MySQL then uses the indexes to select exact physical corresponding records of the table instead

    of scanning the whole table.

    A database index is similar to an index of a book. If you want to find a topic, you look up in the index first, and then you open the page that

    has the topic without scanning the whole book.

    It is highly recommended that you should create index on columns of table from which you often query the data. Notice that all primary key

    columns are in primary index of the table.

    If index helps speed up the querying data, why dont we use index all columns? If you create index for every column, MySQL has to build and

    maintain the index table. In addition, whenever a change is made to the table, MySQL has to rebuild the index, which takes time as well as

    decreases the performance of the database server.

    Creating MySQL Index

    You often create indexes when you create tables. MySQL automatically add any column that is declared as PRIMARY KEY, KEY, UNIQUE

    or INDEX to the index. In addition, you can add indexes to the tables that already have data.

    In order to create index, you use CREATE INDEX statement. The following illustrates the syntax of the CREATE INDEX statement:

    ?

    1

    2

    CREATE[UNIQUE|FULLTEXT|SPATIAL] INDEXindex_nameUSING [BTREE | HASH | RTREE]ONtable_name (column_name [(length)] [ASC| DESC],...)

    http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspxhttp://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspxhttp://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspxhttp://www.mysqltutorial.org/mysql-create-drop-index.aspxhttp://www.mysqltutorial.org/mysql-create-drop-index.aspxhttp://www.mysqltutorial.org/mysql-create-drop-index.aspxhttp://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspx
  • 7/29/2019 My SQL(Basic)

    13/52

    3

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

    UNIQUE means MySQL will create a constraint that all values in the index must be unique. Duplicate NULL is allowed in all storageengine except BDB.

    FULLTEXT index is supported only by MyISAM storage engine and only accepted on column that has data type is CHAR,VARCHAR or

    TEXT. SPATIAL index supports spatial column and is available on MyISAM storage engine. In addition, the column value must not be NULL.Then, you name the index and type of index after USING clause such as BTREE, HASH or RTREE also based on the storage engine of the

    table.

    Here are the storage engines of the table with the corresponding allowed index types:

    Storage Engine Allowable Index Types

    MyISAM BTREE, RTREE

    InnoDB BTREE

    MEMORY/HEAP HASH, BTREE

    NDB HASHThird, you declare table name and a list columns that you want to add to the index.

    Example of creating index in MySQL

    In thesample database, you can add officeCode column of the employees table to the index by using CREATE INDEX statement as follows:

    ?

    1

  • 7/29/2019 My SQL(Basic)

    14/52

    3

    4

    5

    6

    7

    8

    [INNER| LEFT|RIGHT] JOINtable_2 ONconditionsWHEREconditionsGROUPBYgroupHAVINGgroup_conditionsORDERBYcolumn_1 [ASC| DESC]LIMIT offset, row_count

    The SELECT statement has many clauses as follows:

    SELECT chooses which columns of the table you want to see the data. FROM specifies the main table from which you get the data. JOIN gets data from multiple table based on certain join conditions. WHERE filters rows to select GROUP BY group rows to apply aggregate functions on each group. HAVING filters group based on groups defined by GROUP BY clause ORDER BY specifies the order of the returned result set. LIMIT constrains number of returned rows.

    You will learn about each clause in more detail in the next tutorial. In this tutorial, we are going to focus on the simple form of the SELECTstatement.

    MySQL SELECT Examples

    To select all columns and rows in the employees table, you use the following query:

    ?

    1 SELECT* FROMemployees

    The asterisk (*) notation selects all columns in the table.

    The SELECT statement also allows you to select partial data of a table by specifying a list of comma-separated columns in the SELECT

    clause. For example, if you want to view only first name, last nameandjob title of the employees, you use the following query:

    ?

    1

    2

    3

    4

    SELECTlastname,firstname,jobtitle

    FROMemployees

    http://www.mysqltutorial.org/mysql-inner-join.aspxhttp://www.mysqltutorial.org/mysql-inner-join.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-having.aspxhttp://www.mysqltutorial.org/mysql-having.aspxhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.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.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-having.aspxhttp://www.mysqltutorial.org/mysql-group-by.aspxhttp://www.mysqltutorial.org/mysql-inner-join.aspx
  • 7/29/2019 My SQL(Basic)

    15/52

    In this tutorial, youve learned about the basicMySQL SELECT statement to query data from one database table.

    Summary: you will learn how to use MySQL WHERE clause to filter rows that returns from the SELECT statement.

    If you use theSELECT statement without the WHERE clause, you will get all the records in a database table, which is a lot more information

    than you need. The WHERE clause allows you to specify exact rows to select based on certain criteria e.g., find all customers in the U.S.

    In the following query, we get customers name and city from the customers table, and only select customers in USA. In the WHERE clause,

    we compare the values of the country column with the string USA.

    ?

    1

    23

    SELECTcustomerName, city

    FROMcustomersWHEREcountry = 'USA';

    http://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-where/http://www.mysqltutorial.org/mysql-where/http://www.mysqltutorial.org/mysql-where/http://www.mysqltutorial.org/mysql-select-statement-query-data.aspx
  • 7/29/2019 My SQL(Basic)

    16/52

    We typically call the expression in the WHERE clause is a condition. You can form a very simple condition like the query above, or a complex

    one which combines multiple expressions with logical operators such as AND and OR. For example, to find all customers in the U.S . and in

    New York city, you use the following query:

    ?

    1

    2

    3

    4

    SELECT customerName, cityFROM customersWHERE country = 'USA' AND

    city = 'NYC';

    You can test the condition not only for equality but also for inequality. For example, to find all customers who have credit limit greater than

    200000 USD, you use the following query:

    ?

    1

    2

    3

    SELECTcustomerName, creditlimitFROMcustomersWHEREcreditlimit > 200000;

    http://www.mysqltutorial.org/mysql-where/http://www.mysqltutorial.org/mysql-where/http://www.mysqltutorial.org/mysql-where/http://www.mysqltutorial.org/mysql-where/http://www.mysqltutorial.org/mysql-where/http://www.mysqltutorial.org/mysql-where/
  • 7/29/2019 My SQL(Basic)

    17/52

    There are several useful operators that you can use the WHERE clause to form practical queries such as:

    BETWEEN selects values within a range of values. LIKE matches value based on pattern matching. IN specifies if the value matches any value in a list. IS NULL checks if the value is NULL

    The WHERE clause is used not only with the SELECT statement but also other SQL statements to filter rows suchasDELETE andUPDATE.

    In this tutorial, weve shown you how to use MySQL WHERE clause to filter records based on conditions.

    Summary: in this tutorial, you will learn how to sort the result set usingMySQL ORDER BY with various sorting techniques.

    MySQL ORDER syntax

    When you use theSELECT statementto query the data from tables, the result set is not sorted in a specific order. In order to sort the result

    set, you use the ORDER BY clause. The ORDER BY clause allows you to:

    Sort a result set using single column or multiple columns.

    Sort a result set using different columns in different directions, either ascending or descending order.The following illustrates the syntax of the MySQL ORDER BY clause:

    ?

    1

    2

    3

    SELECTcol1, col2,...FROMtblORDERBYcol1 [ASC|DESC], col2 [ASC|DESC],...

    ASC stands for ascending and DESC stands for descending.

    MySQL ORDER BY examples

    Lets practice with some examples to see how the ORDER BY clause works.

    The following query sorts the result set by contact last name in ascending order.

    ?

    1

    2

    3

    4

    SELECTcontactLastname,contactFirstname

    FROMcustomersORDERBYcontactLastname;

    http://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/mysql-delete-statement.aspxhttp://www.mysqltutorial.org/mysql-delete-statement.aspxhttp://www.mysqltutorial.org/mysql-delete-statement.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-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-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-update-data.aspxhttp://www.mysqltutorial.org/mysql-delete-statement.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspx
  • 7/29/2019 My SQL(Basic)

    18/52

    The MySQL ORDER BY sorts the result set in the ascending order by default if you dont explicitly using ASC or DESC. If you want to sort

    the customers by contact last name in descending order, you need to use DESC after the column name in the ORDER BY clause:

    ?

    1

    2

    3

    4

    SELECTcontactLastname,contactFirstname

    FROMcustomersORDERBYcontactLastname DESC;

    If you want to sort the customer by contact last name in descending order and contact first name in ascending order, you can use the follow

    query:

    ?

    1

    2

    3

    4

    5

    SELECTcontactLastname,contactFirstname

    FROMcustomersORDERBYcontactLastname DESC,

    contactFirstname ASC;

    In the query above, MySQL ORDER sorts the result set by contact last name in descending order first, and then sorts the sorted result set by

    contact first name in ascending order to produce the final result set.

    http://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-by
  • 7/29/2019 My SQL(Basic)

    19/52

    MySQL ORDER BY clause allows you to sort the result set based on expression. In the following example, we will query order line items

    from the orderdetails table. In the query, we calculate the subtotal for each line item and sort the result set using the subtotal and order

    number.

    ?

    1

    23

    4

    5

    SELECTordernumber,

    quantityOrdered * priceEachFROMorderdetailsORDERBYordernumber,

    quantityOrdered * priceEach;

    To make the query more readable, you can use alias, and sort the result based on the alias.

    ?

    1

    2

    3

    4

    5

    SELECTorderNumber,quantityOrdered * priceEach ASsubTotal

    FROMorderdetailsORDERBYorderNumber,

    subTotal;

    ?1

    In the above query, we used subtotal as the alias for the expression quantityOrdered * priceEach, and sorted the result set based on

    the subtotalalias. The MySQL ORDER BY clause enables you to define your own custom sort order for the values in a column using FIELD()

    function. For example, if you want to sort the orders based on the following orders status sequence:

    In Process On Hold Cancelled Resolved Disputed ShippedYou can use the FIELD() function to map those values to a list of numeric values and use the numbers for sorting; see the following query:

    ?

    1

    2

    3

    4

    5

    6

    SELECTorderNumber, statusFROMordersORDERBYFIELD(status, 'In Process',

    'On Hold','Cancelled',

    'Resolved','Disputed',

    http://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-byhttp://www.mysqltutorial.org/mysql-order-by
  • 7/29/2019 My SQL(Basic)

    20/52

    7

    8

    'Shipped');

    In this tutorial, weve shown you various techniques to sort the result set using MySQL ORDER BY clause.

    Summary: in this tutorial, you will learn how to use MySQL DISTINCT with the SELECT statement to eliminate duplicate records in the result

    set.

    When querying data from a database table, you may get duplicate records. In order to remove duplicate records, you use the DISTINCT

    keyword along with theSELECT statement. The syntax of the MySQL DISTINCT is as follows:

    ?

    1

    2

    3

    SELECTDISTINCTcolumnsFROMtable_nameWHEREwhere_conditions

    Lets take a look a simple example of using DISTINCT to select unique last name ofemployees from the employees table.

    First, we query the last names of employees from the employees table using the SELECT statement as follows:

    ?

    1

    2

    3

    SELECTlastnameFROMemployeesORDERBYlastname

    We have employee records that have the same last name so we get duplicate last names in the result set. To remove the duplicate last

    names, you use the DISTINCT after the SELECT clause as follows:

    ?

    1

    2

    3

    SELECTDISTINCTlastnameFROMemployeesORDERBYlastname

    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-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspx
  • 7/29/2019 My SQL(Basic)

    21/52

    ?

    1

  • 7/29/2019 My SQL(Basic)

    22/52

    Without the DISTINCT keyword, you will get duplicate combination state and city as below:

    ?

    1

    2

    3

    4

    SELECTstate, cityFROMcustomersWHEREstate ISNOTNULLORDERBYstate, city

    DISTINCT vs. GROUP BY Clause

    http://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/wp-content/uploads/2011/02/mysql-distinct-multiple-columns-duplicate.png?9d7bd4http://www.mysqltutorial.org/wp-content/uploads/2011/02/mysql-distinct-multiple-columns-duplicate.png?9d7bd4http://www.mysqltutorial.org/mysql-distinct.aspx
  • 7/29/2019 My SQL(Basic)

    23/52

    If you useGROUP BY clausein the SELECT statement without usingaggregate functions, the GROUP BY clause will work like the

    DISTINCT. The following queries produce the same result set:

    ?

    1

    2

    3

    4

    5

    6

    SELECTDISTINCTstateFROMcustomers;

    SELECTstateFROMcustomersGROUPBYstate;

    The difference between DISTINCT and GROUP BY is that the GROUP BY clause sort the result set while DISTINCT does not.

    MySQL DISTINCT and COUNT aggregate function

    The MySQL DISTINCT is used with the COUNT function to count unique records that a column contains. In this case, it ignores the NULL

    values. To count unique states of our customers in the US, you use the following query:

    ?

    12

    3

    SELECTCOUNT(DISTINCTstate)FROMcustomersWHEREcountry = 'USA';

    In this tutorial, we have shown you various ways of using MySQL DISTINCT such as eliminating duplicate records and counting non-NULL

    values.

    Summary: in this tutorial, you will learn how to use MySQL LIMIT clause to select records from the beginning, middle and end of a result set.

    MySQL LIMIT syntaxThe LIMIT clause is used in theSELECT statementto constrain the number of rows in a result set. The LIMIT clause accepts one or two

    arguments. The values of both arguments must be zero or positive integer constants.

    The following illustrates the LIMIT clause syntax with 2 arguments:

    ?

    1

    2

    SELECT* FROMtblLIMIT offset, count

    The offsetspecifies the offset of the first row to return. The offset of the first row is 0, not 1. The countspecifies maximum number of rows to return.When you use LIMIT with one argument, the argument will be used to specifies maximum number of rows to return from the beginning of the

    result set.

    ?

    1

    2

    SELECT* FROMtblLIMIT count

    The query above is equivalent to the following LIMIT clause with two arguments:

    ?

    1 SELECT * FROM tbl

    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-functions/mysql-aggregate-functions/http://www.mysqltutorial.org/mysql-functions/mysql-aggregate-functions/http://www.mysqltutorial.org/mysql-functions/mysql-aggregate-functions/http://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.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-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-functions/mysql-aggregate-functions/http://www.mysqltutorial.org/mysql-group-by.aspx
  • 7/29/2019 My SQL(Basic)

    24/52

    2 LIMIT 0, count

    Using MySQL LIMIT to get the first N rows

    You can use the LIMIT clause to select the first N rows in a table as follows:

    ?

    1

    2SELECT

    * FROM

    tbl

    LIMIT N

    For example, to select the first 10 customers, you use the following query:

    ?

    1

    2

    3

    4

    5

    SELECTcustomernumber,customername,creditlimit

    FROMcustomersLIMIT 10;

    Using MySQL LIMIT to get the highest and lowest values

    The LIMIT clause often used with ORDER BY clause. First, you use the ORDER BY clause to sort the result set based on a certain criteria,

    and then you use LIMIT clause to find lowest or highest values.

    For example, to select 5 customers who have the highest credit limit, you use the following query:

    ?

    1

    2

    3

    4

    5

    6

    SELECTcustomernumber,customername,creditlimit

    FROMcustomersORDERBYcreditlimit DESCLIMIT 5;

    http://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspx
  • 7/29/2019 My SQL(Basic)

    25/52

    And the following query returns 5 customers who have the lowest credit limit:

    ?

    1

    2

    3

    4

    5

    6

    SELECTcustomernumber,customername,creditlimit

    FROMcustomersORDERBYcreditlimit ASCLIMIT 5;

    Using MySQL LIMIT to get the N highest values

    One of the toughest questions in MySQL is how to select the N highest values in a result set e.g., select the second most expensive product,

    which you cannot useMAX or MIN functionsto answer. You can use MySQL LIMIT to answer those kinds of questions.

    Lets take a look at the products result set:

    ?

    1

    2

    3

    4

    SELECTproductName,buyprice

    FROMproductsORDERBYbuyprice DESC;

    http://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-functions/mysql-aggregate-functions/http://www.mysqltutorial.org/mysql-functions/mysql-aggregate-functions/http://www.mysqltutorial.org/mysql-functions/mysql-aggregate-functions/http://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-functions/mysql-aggregate-functions/http://www.mysqltutorial.org/mysql-limit.aspx
  • 7/29/2019 My SQL(Basic)

    26/52

    Our task is to get the highlight product, which is the second most expensive product in the products result set. In order to do so, you use

    MySQL LIMIT clause to select 1 record from the second row (offset starts from zero) as follows:

    ?

    1

    2

    3

    4

    5

    SELECTproductName,buyprice

    FROMproductsORDERBYbuyprice DESCLIMIT 1, 1

    In this tutorial, weve introduced MySQL LIMIT clause syntax and its useful applications in querying data

    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. The usage of the SQL IN operator is listed as follows:

    ?

    12

    3

    SELECTcolumn_listFROMtable_nameWHEREcolumnIN("list_item1","list_item2")

    The column in WHERE clause does not need to be in column_listyou selected, but it has to be a column in the table table_name. If the list

    has more than one value, each item has to be separated by a comma.

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

    Lets practice with several examples of SQL IN.

    http://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/mysql-limit.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/mysql-limit.aspx
  • 7/29/2019 My SQL(Basic)

    27/52

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

    ?

    1

    2

    3

    SELECTofficeCode, city, phoneFROMoffices

    WHEREcountry = 'USA' ORcountry = 'France'

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

    ?

    1

    2

    3

    SELECTofficeCode, city, phoneFROMofficesWHEREcountry IN('USA','France')

    Here is the output

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    +------------+--------+-----------------+ | 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 the where clause as follows:

    ?

    1

    2

    3

    SELECTofficeCode, city, phoneFROMofficesWHEREcountry NOTIN('USA','France')

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

    ?

    1

    2

    3

    4

    5

    6

    7

    +------------+--------+------------------+ | 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 the orders table which have total cost greater than

    $60000, we can use SQL IN with sub-query.

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

    http://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspxhttp://www.mysqltutorial.org/sql-in.aspx
  • 7/29/2019 My SQL(Basic)

    28/52

    ?

    1

    2

    3

    4

    SELECTorderNumberFROMorderDetailsGROUPBYorderNumberHAVINGSUM(quantityOrdered * priceEach) > 60000

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

    ?

    1

    2

    3

    4

    5

    6

    7

    SELECTorderNumber,customerNumber,status,shippedDate FROMordersWHEREorderNumber IN(

    SELECT orderNumber

    FROM orderDetails

    GROUPBY orderNumber

    HAVING SUM(quantityOrdered * priceEach) > 60000)

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

    ?

    1

    2

    3

    4

    5

    6

    7

    +-------------+----------------+---------+---------------------+| orderNumber | customerNumber | status |shippedDate |+-------------+----------------+---------+---------------------+| 10165 | 148 | Shipped | 2003-12-2600:00:00 || 10287 | 298 | Shipped | 2004-09-0100:00:00 || 10310 | 259 | Shipped | 2004-10-1800:00:00 |+-------------+----------------+---------+---------------------+

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

    BETWEEN operator.

    SQL BETWEEN Operator Syntax

    The SQL BETWEEN operator allows you to retrieve values within a specific range. the SQL between must be used in the WHERE clause of

    theSQL SELECT statement. The following illustrates the SQL BETWEEN syntax:

    ?

    1

    2

    3

    SELECTcolumn_listFROMtable_nameWHEREcolumn_1 BETWEENlower_range ANDupper_range

    MySQL returns all records in which the column_1 value is in the range of lower_rage and upper_range as well as the values lower_rage and

    upper_range. The query which is equivalent to SQL BETWEEN to get the same result is

    ?

    1

    2

    3

    SELECTcolumn_listFROMtable_nameWHEREcolumn_1 >= lower_range ANDcolumn_1

  • 7/29/2019 My SQL(Basic)

    29/52

    Suppose we want to find all products which buy price is in a range of 90$ and 100$, we can perform the following query to do so:

    ?

    1

    2

    3

    4

    SELECTproductCode,ProductName,buyPriceFROMproductsWHEREbuyPrice BETWEEN90 AND100

    ORDERBYbuyPrice DESC

    Here is the output

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    +-------------+--------------------------------------+----------+| productCode | ProductName |buyPrice |+-------------+--------------------------------------+----------+| S10_1949 | 1952 Alpine Renault1300 | 98.58 || S24_3856 | 1956 Porsche 356ACoupe | 98.3 || S12_1108 | 2001 FerrariEnzo | 95.59 || S12_1099 | 1968 FordMustang | 95.34 || S18_1984 | 1995 HondaCivic | 93.89 || S18_4027 | 1970 TriumphSpitfire | 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 buy price 90$ or 100$, it will be included in theoutput too.

    In order to find all records which are not in a range we use NOT BETWEEN. To find all products that buy price outside the range of 20 and

    100, we can operate following query:

    ?

    1

    2

    3

    SELECTproductCode,ProductName,buyPriceFROMproductsWHEREbuyPrice NOTBETWEEN20 AND100

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    +-------------+-------------------------------------+--

    --------+

    | productCode | ProductName |buyPrice |+-------------+-------------------------------------+----------+| S10_4962 | 1962 LanciaA Delta16V | 103.42 || S18_2238 | 1998 Chrysler PlymouthProwler | 101.51 || S24_2972 | 1982 Lamborghini

    http://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspx
  • 7/29/2019 My SQL(Basic)

    30/52

    Diablo | 16.24 || S24_2840 | 1958 Chevy Corvette Limited Edition| 15.91 |+-------------+-------------------------------------+----------+

    The query above is equivalent to the following query

    ?

    1

    2

    3

    4

    SELECTproductCode,ProductName,buyPriceFROMproductsWHEREbuyPrice < 20 ORbuyPrice > 100ORDERBYbuyPrice DESC

    In this tutorial, youve learned how to use SQL BETWEEN to select data from database tables in a range.

    Summary: MySQL provides LIKE operator in SQL standard. The MySQL LIKE operator is commonly used to select data based on patterns

    matching. UsingMySQL LIKE in appropriate way is essential to increase applications performance. In this tutorial, you will learn how to

    use MySQL L IKE and when to avoid using it to increase the speed of retrieving data from database table.

    MySQL LIKE allows you to perform pattern matching in your characters column in a database table. MySQL LIKE is often used with SELECTstatement in WHERE clause. MySQL provides you 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 with character a, you can do it as follows:

    ?

    1

    2

    3

    SELECTemployeeNumber, lastName, firstNameFROMemployeesWHEREfirstName LIKE'a%'

    ?

    1

    2

    3

    4

    5

    6

    +----------------+----------+-----------+ | employeeNumber | lastName | firstName |+----------------+----------+-----------+ | 1611 | Fixter | Andy |+----------------+----------+-----------+ 1 row inset(0.00 sec)

    MySQL scans the whole employeestable to find all employees which have first name starting with 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 query as follows:

    ?

    1

    2

    3

    SELECTemployeeNumber, lastName, firstNameFROMemployeesWHERElastName LIKE'%on'

    ?

    1

    2

    +----------------+-----------+-----------+ | employeeNumber | lastName | firstName |+----------------+-----------+-----------+

    http://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-between-mysql.aspx
  • 7/29/2019 My SQL(Basic)

    31/52

    3

    4

    5

    6

    7

    | 1088 | Patterson | William || 1216 | Patterson | Steve |+----------------+-----------+-----------+ 2 rowsinset(0.00 sec)

    If you know a searched string is embedded somewhere in a column, you can put the percentage wild card at the beginning and the end of it

    to find all possibilities. For example, if you want to find all employees which have last name containing on string you can execute following

    query:

    ?

    1

    2

    3

    SELECTemployeeNumber, lastName, firstNameFROMemployeesWHERElastname LIKE'%on%'

    ?

    1

    2

    3

    45

    6

    7

    8

    9

    10

    +----------------+-----------+-----------+ | employeeNumber | lastName | firstName |+----------------+-----------+-----------+

    | 1088 | Patterson | William || 1102 | Bondur | Gerard || 1216 | Patterson | Steve || 1337 | Bondur | Loui || 1504 | Jones | Barry |+----------------+-----------+-----------+ 5 rowsinset(0.00 sec)

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

    ?

    1

    2

    3

    SELECTemployeeNumber, lastName, firstNameFROMemployees

    WHEREfirstname LIKE''T_m"

    ?

    1

    2

    3

    4

    5

    6

    +----------------+----------+-----------+ | employeeNumber | lastName | firstName |+----------------+----------+-----------+ | 1619 | King | Tom |+----------------+----------+-----------+ 1 row inset(0.00 sec)

    The MySQL LIKE allows you to put the NOT keyword to find all strings which are unmatched with a specific pattern. Suppose you want to

    search for all employees whose last name are not starting with B, you can use the following query

    ?1

    2

    3

    SELECTemployeeNumber, lastName, firstNameFROMemployeesWHERElastName NOTLIKE'B%'

    ?

    1

    2

    3

    +----------------+-----------+-----------+ | employeeNumber | lastName | firstName |+----------------+-----------+-----------+ | 1088 | Patterson | William |

    http://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspx
  • 7/29/2019 My SQL(Basic)

    32/52

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    | 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 || 1621 | Nishi | Mami || 1625 | Kato | Yoshimi || 1702 | Gerard | Martin |+----------------+-----------+-----------+ 14 rowsinset(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? In this case, you can use ESCAPE to shows that

    the wildcard characters followed it has literal meaning not wildcard meaning. If ESCAPE does not specify explicitly, the escape character in

    MySQL by default is \. For example, if you want to find all products which as product code which has _20 embedded on it, you can perform

    following query

    ?

    1

    2

    3

    SELECTproductCode, productNameFROMproductsWHEREproductCode LIKE'%\_20%'

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    +-------------+---------------------------------------

    ----+| productCode |productName |+-------------+-------------------------------------------+| S10_2016 | 1996 Moto Guzzi1100i || S24_2000 | 1960 BSA Gold StarDBD34 || S24_2011 | 18th centuryschooner || S24_2022 | 1938 Cadillac V-16 PresidentialLimousine |

    | S700_2047 | HMSBounty |+-------------+-------------------------------------------+5 rowsinset(0.00 sec)

    MySQL LIKE gives you a convenient way to find records which have character columns match specified 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 in the table is big enough, the performance of MySQL LIKE will degrade. In some cases you can avoid this problem by using other

    techniques to achieve the same result as MySQL LIKE. For example, if you want to find all employees which have first name starting with a

    specified string you can use LEFT function in where clause like the following query:

    http://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspx
  • 7/29/2019 My SQL(Basic)

    33/52

    ?

    1

    2

    3

    4

    SET@str = 'b';SELECTemployeeNumber, lastName, firstNameFROMemployeesWHERELEFT(lastname,length(@str)) = @str;

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

    ?

    1

    2

    3

    SELECTemployeeNumber, lastName, firstNameFROMemployeesWHERElastname LIKE'b%'

    And another technique to achieve all string which end with a specified string by using RIGHT function. 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:

    ?

    1

    2

    3

    4

    SET@str = 'on';SELECTemployeeNumber, lastName, firstNameFROMemployeesWHERERIGHT(lastname,length(@str)) = @str;

    ?

    1

    2

    3

    4

    5

    6

    7

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

    It returns the same result as the following query

    ?

    1

    2

    3

    SELECTemployeeNumber, lastName, firstNameFROMemployeesWHERElastname LIKE'%on'

    Summary: in this tutorial, you will learn how to use MySQL UNION operator to combine two or more result sets from multiple SQL SELECT

    statements into a single result set.

    MySQL UNION Operator

    MySQL UNION operator allows you to combine two or more result sets from multiple tables into a single result set. The syntax of the MySQL

    UNION is as follows:

    ?1

    2

    3

    4

    5

    6

    SELECTcolumn1, column2UNION[DISTINCT| ALL]SELECTcolumn1, column2UNION[DISTINCT| ALL]

    There are some rules that you need to follow in order to use the UNION operator:

    http://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspxhttp://www.mysqltutorial.org/sql-like-mysql.aspx
  • 7/29/2019 My SQL(Basic)

    34/52

    The number of columns appears in the correspondingSELECT statementsmust be equal. The columns appear in the corresponding positions of each SELECT statement must have the samedata typeor at least convertible

    data type.

    By default, the UNION operator eliminates duplicate rows from the result even if you dont useDISTINCTkeyword explicitly. Therefore it is

    said that UNION is the shortcut of UNION DISTINCT.

    If you use UNION ALL explicitly, the duplicate rows, if available, remain in the result. The UNION ALL performs faster than the UNIONDISTINCT.

    MySQL UNION example

    Lets practice with an example of using MySQL UNION to get a better understanding.

    Suppose you want to combine customers and employees data into a single result set, you can UNION operator as the following query:

    ?

    1

    2

    3

    4

    5

    SELECTcustomerNumber id, contactLastname nameFROMcustomersUNION

    SELECTemployeeNumber id,firstname nameFROMemployees

    Here is the output:

    MySQL UNION without AliasIn the example above, we used the column alias for each column in the SELECT statements. What would be the output if we didn t use the

    column alias? MySQL uses the names of columns in the first SELECT statement as the labels for the output.

    Lets try the query that combinescustomers and employees information without using column alias:

    ?

    1

    2

    3

    4

    5

    6

    (SELECTcustomerNumber, contactLastnameFROMcustomers)UNION(SELECTemployeeNumber, firstnameFROMemployees)

    ORDERBYcontactLastname, customerNumber

    The result has customerNumberand contactLastname, which are the name of column in the first SELECT statement , as the labels.

    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-data-types.aspxhttp://www.mysqltutorial.org/mysql-data-types.aspxhttp://www.mysqltutorial.org/mysql-data-types.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/wp-content/uploads/2009/12/mysql-union-result-set.png?9d7bd4http://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/mysql-distinct.aspxhttp://www.mysqltutorial.org/mysql-data-types.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspx
  • 7/29/2019 My SQL(Basic)

    35/52

    MySQL UNION with ORDER BY

    If you want to sort the results that return from the query using UNION operator, you need to use ORDER BY clause in the last SQL SELECT

    statement. You can put each SELECT statement in the parenthesis and use ORDER BY clause as the last statement.

    Lets take a look at the following example:

    ?

    1

    2

    3

    4

    5

    6

    (SELECTcustomerNumber id,contactLastname name

    FROMcustomers)

    UNION(SELECTemployeeNumber id,firstname nameFROMemployees)ORDERBYname,id

    In the query above, first we combine idand name of both employees and customers into one result set using UNION operator. Then we sort

    the result set using ORDER BY clause. It is noticed that we put the SELECT statements inside the parenthesis and place the ORDER BY

    clause as the last statement.

    If you place the ORDER BY clause in each SELECT statement, it will not affect the order of the rows in the final result produced by the

    UNION operator.

    MySQL also provides you with alternative option to sort the result set based on column position using ORDER BY clause as the following

    query:

    ?

    1

    2

    3

    (SELECTcustomerNumber, contactLastnameFROMcustomers)UNION(SELECTemployeeNumber,firstname

    http://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/wp-content/uploads/2009/12/mysql-union-order-by.png?9d7bd4http://www.mysqltutorial.org/wp-content/uploads/2009/12/mysql-union-column-alias.png?9d7bd4http://www.mysqltutorial.org/wp-content/uploads/2009/12/mysql-union-order-by.png?9d7bd4http://www.mysqltutorial.org/wp-content/uploads/2009/12/mysql-union-column-alias.png?9d7bd4http://www.mysqltutorial.org/sql-union-mysql.aspxhttp://www.mysqltutorial.org/sql-union-mysql.aspx
  • 7/29/2019 My SQL(Basic)

    36/52

    4

    5

    6

    FROMemployees)ORDERBY2, 1

    In this tutorial, you have learned how to use MySQL UNION statement to combine data from multiple tables into a single result set.

    Summary: In this tutorial, you will learn how to use MySQL INNER J OIN clause to select data from multiple tables based on join conditions.

    Introducing MySQL INNER JOIN clause

    The MySQL INNER JOINclause is an optional part ofSQL SELECT statement. The MySQL INNER JOIN clause appears immediately after

    the FROM clause. Before using MySQL INNER JOIN clause, you have to specify the following criteria:

    First, you need to specify the tables where you want to join with the main table. The main table appears in the FROM clause. The tablesyou want to join with appear after keyword INNER JOIN. Theoretically, you can join a table with unlimited number of tables. However,

    for better performance you should limit the number of tables to join based on join conditions and volume of data.

    Second, you need to specify the join condition or join predicate. The join condition appears after the keyword ON of the INNER JOINclause. The join condition is the rule for matching rows between the main table and other tables being joined with.

    The syntax of the MySQL INNER JOIN is as follows:

    ?

    1

    2

    3

    4

    5

    6

    SELECTcolumn_listFROMt1INNERJOINt2 ONjoin_condition1INNERJOINt3 ONjoin_condition2...WHEREwhere_conditions;

    For example, if you join two tables A and B, the MySQL INNER JOIN clause compares each record of the table A with each record of table B

    to find all pair of records that satisfy the join-condition. When the join-condition are satisfied, column values for each matched pair of record

    of table A and table B are combined into a returned record. Note that the records on both tables have to match based on the join-condition. If

    no record on both table A and B matches, the query will return an empty result.

    Avoid column ambiguous error in MySQL INNER JOIN

    If you join multiple tables that has column with similar name, you have to use table qualifier to refer to column to avoid column ambiguous

    error. Suppose if table tbl_A and tbl_B has the same column M. In the SELECT statement with MySQL INNER JOIN clause, you have to

    refer to column Mby using the table qualifier as tbl_A.Mortbl_B.M(table_name.column_name).

    Another effective way to avoid column ambiguous is by using table alias. For example, you can give A as the table alias of the

    table tbl_A and refer to the column MasA.Mso you dont have to type again and again the long table name in your SQL statement.

    Example of MySQL INNER JOIN clause

    Lets take a look at two tables: products and orderDetails in our sample database.

    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-inner-join.aspxhttp://www.mysqltutorial.org/mysql-inner-join.aspxhttp://www.mysqltutorial.org/mysql-inner-join.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspx
  • 7/29/2019 My SQL(Basic)

    37/52

    The products table is the master data table that stores all products. Whenever a product is sold, it is stored in the orderDetails table with

    other information. The link between products table and orderDetails table is productCode.

    Now, if you want to know what product was sold in which order, you can use the MySQL INNER JOINclause as follows:

    ?

    1

    2

    3

    SELECTA.productCode, A.productName, B.orderNumberFROMproducts AINNERJOINorderDetails B onA.productCode =B.productCode;

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

    The MySQL INNER JOIN clause compares each row of table products and orderDetails table to find a pair of rows that has the same

    productCode. If a pair of rows that have the same, the product code, product name and order number are combined into a returned row.

    http://www.mysqltutorial.org/mysql-inner-join.aspxhttp://www.mysqltutorial.org/mysql-inner-join.aspxhttp://www.mysqltutorial.org/wp-content/uploads/2009/12/mysql-inner-join-query.gif?9d7bd4http://www.mysqltutorial.org/wp-content/uploads/2009/12/mysql-inner-join.gif?9d7bd4http://www.mysqltutorial.org/wp-content/uploads/2009/12/mysql-inner-join-query.gif?9d7bd4http://www.mysqltutorial.org/wp-content/uploads/2009/12/mysql-inner-join.gif?9d7bd4http://www.mysqltutorial.org/mysql-inner-join.aspx
  • 7/29/2019 My SQL(Basic)

    38/52

    In this tutorial, you have learned how to use MySQL INNER JOIN to select data from multiple tables. You have also learned how to use table

    qualifier to avoid column ambiguous error in MySQL INNER JOIN clause.

    Summary: in this tutorial, you will learn how to use MySQL LEFT J OIN clause to retrieve data from more than one table.

    Introducing to MySQL LEFT JOIN

    The MySQL LEFT JOIN clause is an optional element of the SQL SELECT statement to allow you to retrieve data from additional tables. The

    MySQL LEFT JOIN clause consists of LEFT JOIN keyword followed by the second table you want to join. Next element is the ON keyword

    followed by the join condition. In the join condition, you specify the columns to be used for matching row in the two tables. The syntax of

    MySQL is as follows:

    ?

    1

    2

    3

    4

    SELECTt1.c1, t1.c2,t2.c1,t2.c2FROMt1LEFTJOINt2 ONt1.c1 = t2.c1 (join_condition)WHEREwhere_condition

    The MySQL LEFT JOIN clause works like this: when a row from the left table 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 no match it is still selected for output, but combined with a fake

    row from the right table that contains NULL in all columns. In short, the MySQL LEFT JOIN clause allows you to select all rows from the left

    table even there is no match 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 know which customer has which order and each orders status. You can

    use the MySQL LEFT JOIN as follows:

    ?

    1

    2

    SELECTc.customerNumber, customerName,orderNUmber,o.statusFROMcustomers c

    http://www.mysqltutorial.org/mysql-left-join.aspxhttp://www.mysqltutorial.org/mysql-left-join.aspxhttp://www.mysqltutorial.org/mysql-left-join.aspxhttp://www.mysqltutorial.org/mysql-left-join.aspxhttp://www.mysqltutorial.org/basic-mysql-tutorial/using-mysql-select-statement-to-query-data/mysql-left-join-tables/http://www.mysqltutorial.org/mysql-left-join.aspxhttp://www.mysqltutorial.org/mysql-left-join.aspx
  • 7/29/2019 My SQL(Basic)

    39/52

    3 LEFTJOINorders 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 the way MySQL LEFT JOIN clause works. However, there are

    rows that we have customer information but all order information are NULL. This means those 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 table that are unmatched by the right

    table. You can accomplish this by add a WHERE 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 can use the MySQL LEFT JOIN clause as follows:

    ?

    1

    2

    3

    4

    SELECTc.customerNumber, customerName,orderNUmber,o.statusFROMcustomers cLEFTJOINorders o ONc.customerNumber = o.customerNumberWHEREorderNumber isNULL

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

    As the result, the query only returns a list ofcustomers who have never ordered any product.

    In this tutorial, you have learned how to use MySQL LEFT JOIN clause to select data from multiple tables. Youve also learned how to use

    MySQL LEFT JOIN to find unmatched records between two tables

    http://www.mysqltutorial.org/mysql-left-join.aspxhttp://www.mysqltutorial.org/mysql-left-join.aspxhttp://www.mysqltutorial.org/basic-mysql-tutorial/using-mysql-select-statement-to-query-data/mysql-left-join-unmatched-records/http://www.mysqltutorial.org/basic-mysql-tutorial/using-mysql-select-statement-to-query-data/mysql-left-join/http://www.mysqltutorial.org/basic-mysql-tutorial/using-mysql-select-statement-to-query-data/mysql-left-join-unmatched-records/http://www.mysqltutorial.org/basic-mysql-tutorial/using-mysql-select-statement-to-query-data/mysql-left-join/http://www.mysqltutorial.org/mysql-left-join.aspx
  • 7/29/2019 My SQL(Basic)