MySQL Development.docx

Embed Size (px)

Citation preview

  • 8/21/2019 MySQL Development.docx

    1/23

    1.Basic MySQL Tutorial

    A.Manage Database in MySQL

    Including - creating a new database, Removing an Existing database, Selecting a database to work withand listing all databases.

    Creating DatabaseBefore doing anything else with the data, you need to create a database. In MySQL, a database is acollection of objects that are used to store and manipulate data such as tables, databaseviews,triggers,stored procedures,etc.

    CREATE DATABASE [IF NOT EXISTS] database name;

    Displaying Databases

    SHOW DATABASES;

    Selecting a database to work with

    Before working with a particular database, you must tell MySQL which database you want to work with

    by using the USE statement.

    USE database_name;

    From now all operations such asquerying data,create new tables orstored procedures which youperform, will take effects on the current database

    Removing Databases

    Removing database means you delete the database physically. All the data and related objects inside the

    database are permanently deleted and this cannot be undone, therefore it is very important to execute

    this query with extra cautions.

    To delete a database, you use the DROP DATABASE statement as follows:

    DROP DATABASE [IF EXISTS] database_name;

    Followed the DROP DATABASE is the database name that you want to remove. Similar to the CREATE

    DATABASE statement, the IF EXISTS is an optional part of the statement to prevent you from removing a

    database that does not exist in the database server.

    If you want to practice with the DROP DATABASE statement, you can create a new database, make sure

    that it is created and remove it. Take a look at the following queries:

    1

    2

    3

    CREATE DATABASE IF NOT EXISTS temp_database;

    SHOW DATABASES;

    DROP DATABASE IF EXISTS temp_database;

    http://www.mysqltutorial.org/basic-mysql-tutorial.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/mysql-views-tutorial.aspxhttp://www.mysqltutorial.org/mysql-views-tutorial.aspxhttp://www.mysqltutorial.org/mysql-triggers.aspxhttp://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspxhttp://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspxhttp://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspxhttp://www.mysqltutorial.org/mysql-create-table/http://www.mysqltutorial.org/mysql-select-statement-query-data.aspxhttp://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspxhttp://www.mysqltutorial.org/mysql-triggers.aspxhttp://www.mysqltutorial.org/mysql-views-tutorial.aspxhttp://www.mysqltutorial.org/mysql-views-tutorial.aspxhttp://www.mysqltutorial.org/mysql-create-drop-database.aspxhttp://www.mysqltutorial.org/basic-mysql-tutorial.aspx
  • 8/21/2019 MySQL Development.docx

    2/23

    B. Understanding MySQL Table Types, or Storage Engines

    Summary: in this tutorial, you will learn various MySQL table types, or storage engines. It is essential tounderstand the features of each table type in MySQL so that you can use them effectively to maximizethe performance of your databases.

    MySQL provides various storage engines for its tables as below:

    MyISAM

    InnoDB

    MERGE

    MEMORY (HEAP)

    ARCHIVE

    CSV

    FEDERATED

    MySQL supports several storage engines that act as handlers for different table types. MySQL storageengines include both those that handle transaction-safe tables and those that handle nontransaction-safe tables.

    Note

    Prior to MySQL 5.1.38, the pluggable storage engine architecture is supported on Unix platforms only

    and pluggable storage engines are not supported on Windows.

    To determine which storage engines your server supports by using theSHOW ENGINESstatement.

    The value in the Supportcolumn indicates whether an engine can be used. A value of YES,NO,

    or DEFAULTindicates that an engine is available, not available, or available and currently set as the

    default storage engine.

    mysql> SHOW ENGINES\G

    *************************** 1. Row ***************************

    Engine: FEDERATED

    Support: NO

    Comment: Federated MySQL storage engine

    Transactions: NULL

    XA: NULL

    Savepoints: NULL

    *************************** 2. row ***************************

    Engine: MRG_MYISAM

    Support: YES

    Comment: Collection of identical MyISAM tables

    Transactions: NO

    XA: NO

    Savepoints: NO

    http://www.mysqltutorial.org/understand-mysql-table-types-innodb-myisam.aspxhttp://www.mysqltutorial.org/understand-mysql-table-types-innodb-myisam.aspxhttp://dev.mysql.com/doc/refman/5.1/en/show-engines.htmlhttp://dev.mysql.com/doc/refman/5.1/en/show-engines.htmlhttp://dev.mysql.com/doc/refman/5.1/en/show-engines.htmlhttp://dev.mysql.com/doc/refman/5.1/en/show-engines.htmlhttp://www.mysqltutorial.org/understand-mysql-table-types-innodb-myisam.aspx
  • 8/21/2019 MySQL Development.docx

    3/23

    *************************** 3. Row ***************************

    Engine: MyISAM

    Support: DEFAULT

    Comment: Default engine as of MySQL 3.23 with great performance

    Transactions: NO

    XA: NO

    Savepoints: NO

    Each 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

    Change engine for tableAlter table information_schema`. CHARACTER_SETS` engine = MyISAM

  • 8/21/2019 MySQL Development.docx

    4/23

    Constraints

    Primary Key-The PRIMARY KEY constraint uniquely identifies each record in a database table.

    Primary keys must contain unique values.

    A primary key column cannot contain NULL values.

    Each table should have a primary key, and each table can have only ONE primary key.Foreign Key-Relation Between two tables-establish a link between the data in two tables.

    NOT NULL- Indicates that a column cannot store NULL value

    UNIQUE- Ensures that each row for a column must have a unique value

    CHECK- Ensures that the value in a column meets a specific condition

    DEFAULT- Specifies a default value when specified none for this column

    Zerofill-When you select a column with type ZEROFILL it pads the displayed value of the field with zeros up to

    the display width specified in the column definition. Values longer than the display width are not truncated. Note

    that usage of ZEROFILL also implies UNSIGNED.

    Using ZEROFILL and a display width has no effect on how the data is stored. It affects only how it is displayed.

    Here is some example SQL that demonstrates the use of ZEROFILL:

    CREATE TABLE yourtable (x INT(8) ZEROFILL NOT NULL, y INT(8) NOT NULL);

    INSERT INTO yourtable (x,y) VALUES

    (1, 1),

    (12, 12),

    (123, 123),

    (123456789, 123456789);

    SELECT x, y FROM yourtable;

    Result:

    x y

    00000001 1

    00000012 12

    00000123 123

    123456789 123456789

    Unsigned-All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permitonly nonnegative numbers in a columnor when you need a larger upper numeric rangefor the column. Forexample, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

    CREATE TABLE `employees55` (

    `Emp_No` INT(11) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,`Birth_Date` DATE DEFAULT NULL,

    `First_Name` VARCHAR(14) NOT NULL,

    `Last_Name` VARCHAR(16) NOT NULL,

    `Gender` ENUM('M','F') NOT NULL,

    `Hire_Date DATE DEFAULT NULL,

    PRIMARY KEY (`Emp_No`))

    CREATE TABLE dept_emp(

    emp_no INT NOT NULL,

    dept_no CHAR(4) NOT NULL,

    from_date DATE NOT NULL,

    to_date DATE NOT NULL,KEY (emp_no), -- Build INDEX on this non-unique-value column

  • 8/21/2019 MySQL Development.docx

    5/23

    KEY (dept_no), -- Build INDEX on this non-unique-value column

    FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE,

    -- Cascade DELETE from parent table 'employee' to this child table

    -- If an emp_no is deleted from parent 'employee', all records

    -- involving this emp_no in this child table are also deleted

    -- ON UPDATE CASCADE??

    FOREIGN KEY (dept_no) REFERENCES departments (dept_no) ON DELETE CASCADE,

    -- ON UPDATE CASCADE??

    PRIMARY KEY (emp_no, dept_no)

    -- Might not be unqiue?? Need to include from_date

    );

    CREATE TABLE `indextable` (

    `card_id` int(10) unsigned zerofill NOT NULL,`card_name` varchar(20) NOT NULL,

    PRIMARY KEY (`card_name`),

    UNIQUE KEY card_id` (`card_id`)

    )

    C.MySQL Data Types

  • 8/21/2019 MySQL Development.docx

    6/23

    CREATE TABLE test` (`sl_no` TINYINT(3) NOT NULL AUTO_INCREMENT,`emp_id` SMALLINT(6) DEFAULT NULL,`job_id` MEDIUMINT(9) DEFAULT NULL,`mobile_no1` VARCHAR(20) DEFAULT NULL,`mobile_no2` VARCHAR(40) DEFAULT NULL,`ctc_salary` DECIMAL(10,0) DEFAULT NULL,`gross_salary` FLOAT DEFAULT NULL,`net_salart` DOUBLE DEFAULT NULL,`PF` BIT(1) DEFAULT NULL,`name` CHAR(50) DEFAULT NULL,`fname` VARCHAR(50) DEFAULT NULL,`code1` BINARY(50) DEFAULT NULL,`code2` VARBINARY(50) DEFAULT NULL,

  • 8/21/2019 MySQL Development.docx

    7/23

    `photo1` TINYBLOB,`photo2` TINYBLOB,`photo3` MEDIUMBLOB,`photo4` LONGBLOB,`remarks1` TEXT,`remarks12` TINYTEXT,`remarks13` MEDIUMTEXT,`remarks14` LONGTEXT,`joining_date1` DATE NOT NULL,`joining_date2` TIME NOT NULL,`joining_date3` DATETIME NOT NULL,`joining_date4` NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,`joining_date5` YEAR(4) NOT NULL,KEY sl_no` (`sl_no`)

    )

    E. MySQL Sequence

    Each table has only one AUTO_INCREMENT column whose data type is typically integer or floatwhich is very rare.

    The AUTO_INCREMENT column must be indexed, which means it can be either PRIMARYKEY or UNIQUE index.

    The AUTO_INCREMENT column must have NOT NULL constraint. When yousetAUTO_INCREMENT attribute to a column, MySQL will make it NOT NULL for you in case youdont define it explicitly.

    CREATE TABLE employees(

    emp_no INT(4) AUTO_INCREMENT PRIMARY KEY,

    first_name VARCHAR(50),

    last_name VARCHAR(50)

    )ENGINE = INNODB;

    First, insert two new employees into the employees table:

    INSERT INTO employees(first_name,last_name)

    VALUES('John','Doe'),

    ('Mary','Jane');

    1 SELECT * FROM employees;

    Third, delete the second employee whose emp_no is 2:

    DELETE FROM employees

    WHERE emp_no = 2;

    http://www.mysqltutorial.org/mysql-sequence/http://www.mysqltutorial.org/mysql-sequence/http://www.mysqltutorial.org/mysql-sequence/
  • 8/21/2019 MySQL Development.docx

    8/23

    Fourth, insert a new employee:

    INSERT INTO employees(first_name,last_name)

    VALUES('Jack','Lee');

    Because the storage engine of the employees table is InnoDB, it does not reuse the deleted sequencenumber. The new row has emp_no 3.

    Fifth, update an existing employee with emp_no 3 to 1:

    UPDATE employees

    SET first_name = 'Joe',

    emp_no = 1

    WHERE emp_no = 3;

    MySQL issued an error of duplicate entry for the primary key. Lets fix it:

    UPDATE employees

    SET first_name = 'Joe',

    emp_no = 10

    WHERE emp_no = 3;

    Sixth, insert a new employee after updating the sequence number to 10:

    INSERT INTO employees(first_name,last_name)

    VALUES('Wang','Lee');

    The next sequence number of the last insert is 4, therefore MySQL use 4 for the new row instead of 11.

    In this tutorial, you have learned how to use MySQL sequence to generate unique numbers for a primary

    key column by assigning the column AUTO_INCREMENT attribute.

  • 8/21/2019 MySQL Development.docx

    9/23

    H. Changing Table Structure Using MySQL ALTER TABLE

    The ALTER TABLE statement is used to change the structure of existing tables. You can use the ALTERTABLE statement to add or drop column, changedata typeof column, add primary key, rename table andmany more. The following illustrates the ALTER TABLE statement syntax:

    ALTER TABLE test ADD PRIMARY KEY(sl_no);ALTER TABLE test DROP PRIMARY KEY,ADD PRIMARY KEY(emp_id);ALTER TABLE test ADD CONSTRAINT CK_Per_Place_Thing_Unique UNIQUE (sl_no);ALTER TABLE test ADD COLUMN complete1 DECIMAL(2,1) NULL;

    ALTER TABLE table_name action1[,action2,]

    To alter an existing table:

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

    Second, 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 table, etc. The ALTER TABLE statement

    allows you to apply multiple actions in a single ALTER TABLE statement, each action is separated by a

    comma (,).

    Were going to create anew table named tasksin oursample database.The following is the script forcreating the tasks table.

    CREATE TABLE tasks (

    task_id INT NOT NULL ,

    subject VARCHAR(45) NULL ,

    start_date DATE NULL ,

    end_date DATET NULL ,description VARCHAR(200) NULL ,

    PRIMARY KEY (task_id) ,

    UNIQUE INDEX task_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

    http://www.mysqltutorial.org/mysql-alter-table.aspxhttp://www.mysqltutorial.org/mysql-alter-table.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-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-data-types.aspxhttp://www.mysqltutorial.org/mysql-alter-table.aspx
  • 8/21/2019 MySQL Development.docx

    10/23

    Suppose you want thevalue of thetask_idcolumn to be increased automatically by one wheneveryouinsert a new recordinto the tasks table. To do this, you use the ALTER TABLE statement to set the

    attribute of the task_id column to AUTO_INCREMENT as follows:

    ALTER TABLE tasks

    CHANGE COLUMN task_id task_id INT (11) NOT NULL AUTO_INCREMENT;

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

    INSERT INTO tasks(subject,

    start_date,

    end_date,

    description)

    VALUES('Learn MySQL ALTER TABLE',

    Now(),

    Now(),

    'Practicing MySQL ALTER TABLE statement');

    INSERT INTO tasks(subject,

    start_date,

    end_date,

    description)

    VALUES('Learn MySQL CREATE TABLE',

    Now(),

    Now(),

    'Practicing MySQL CREATE TABLE statement');

    And you can query data to see if the value of the task_id column is increased by 1 each time you insert

    a new record:

    SELECT task_id, description

    FROM tasks

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

    Because of the new business requirement, you need to add a new column called complete to store the

    percentage of completion for each task in the tasks table. In this case, you can use the ALTER TABLE to

    add a new column to the tasks table as follows:

    ALTER TABLE tasks

    ADD COLUMN complete DECIMAL(2,1) NULL

    AFTER description;

    Using MySQL ALTER TABLE to drop a column from a table

    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/21/2019 MySQL Development.docx

    11/23

    Suppose you dont want to store the description of tasks in the tasks table and you have to remove it.

    The following statement allows you to remove the descriptioncolumn of the tasks table:ALTER TABLE tasks

    DROP COLUMN description;

    Renaming table using MySQL ALTER TABLE statement

    You can use the 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.

    The following statement rename the tasks table to work_items:

    ALTER TABLE tasks

    RENAME TO work_items;

    In this tutorial, youve learned how to use the MySQL ALTER TABLE statement to change existing tablestructure and to rename the table.

    I. MySQL DROP TABLE statement syntax

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

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

    [RESTRICT | CASCADE]

    The DROP TABLE statement removes a table and its data permanently from the database. In MySQL, you can

    also remove multiple tables using a single DROP TABLE statement, each table is separated by a comma (,).The

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

    accidentally remove non-temporary tables.The IF EXISTS addition allows you to hide the error message in case

    one or more tables in the list do not exist. When you use IF EXISTS addition, MySQL generates a NOTE, which

    can be retrieved by using the SHOW WARNING statement. It is important to notice that the DROP TABLE

    statement removes all existing tables and issues an error message or a NOTE when you have a non-existent

    table in the list.As mentioned above, 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 with the same name is re-

    created after that, the existing privileges will apply to the new table, which may pose a security risk.TheRESTRICT and CASCADE flags are reserved for the future versions of MySQL.Last but not least, you must have

    DROP privileges for the table that you want to remove.

    MySQL DROP TABLE exampleWe are going to remove the tasks table that we created in the previous tutorial on creating tables usingCREATE TABLE statement. In addition, we also remove a non-existent table to practice with the SHOWWARNING statement. The statement to remove the tasks table and a non-existent table is as follows:DROP TABLE IF EXISTS tasks, nonexistent_table;

    If you check the database, you will see that the tasks table was removed. You can check the NOTE, whichis generated by MySQL because of non-existent table, by using the SHOW WARNING statement asfollows:

    SHOW WARNINGS;

  • 8/21/2019 MySQL Development.docx

    12/23

    MySQL DROP TABLE LIKE

    Image you have a lot of tables whose names start with test in your database and you want to save timeby removing all of them using a single DROP TABLE statement. Unfortunately, MySQL does not providethe DROP TABLE LIKE statement that can remove tables based on pattern matching like the following:However, there are some workarounds. We will discuss one of them here for your reference.Lets start creating test* tables for the sake of demonstration.

    CREATE TABLE IF NOT EXISTS test1(id int(11) NOT NULL AUTO_INCREMENT,PRIMARY KEY(id)

    );

    CREATE TABLE IF NOT EXISTS test2 LIKE test1;CREATE TABLE IF NOT EXISTS test3 LIKE test1;

    CREATE TABLE IF NOT EXISTS test4 LIKE test1;

    Weve created four tables named test1, test2, test3 and test4 with the same table structure.

    Suppose you want to remove all test* tables at a time, you can follow the steps below:

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

    match:

    -- set table schema and pattern matching for tables

    SET @schema = 'classicmodels';

    SET @pattern = 'test%';

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

    -- build dynamic sql (DROP TABLE tbl1, tbl2...;)SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(@schema,'.',table_name)),';')INTO @droplikeFROM information_schema.tablesWHERE @schema = database()AND table_name LIKE @pattern;

    Basically, the query instructs MySQL to go to the information_schema table , which contains data on alltables in all databases, and to concatenate all tables in the database @schema (classicmodels ) thatmatches the pattern @pattern ( test%) with the prefix DROP TABLE. TheGROUP_CONCAT functioncreates a comma-separated list of tables.Then, we can display the dynamic SQL to verify if it works correctly:

    -- 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:

    http://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-prepared-statement.aspx
  • 8/21/2019 MySQL Development.docx

    13/23

    -- execute dynamic sqlPREPARE stmt FROM @dropcmd;EXECUTE stmt;DEALLOCATE PREPARE stmt;

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

    Putting it all together.

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

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

    WHERE @schema = database()AND table_name LIKE @pattern;

    -- display the dynamic sql statementSELECT @droplike;

    -- execute dynamic sqlPREPARE stmt FROM @dropcmd;EXECUTE stmt;DEALLOCATE PREPARE stmt;

    So if you want to drop multiple tables that have a specific pattern in a database, you just use the scriptabove to save time. All you need to do is replacing the pattern and the database schema in @patternand@schema variables. If you often have to deal with this task, you can always develop a stored procedure

    based on the script and reuse the stored procedure in the future.In this tutorial, weve shown you how to use the DROP TABLE statement to remove existing tables in aparticular database. We also discussed about a workaround that allows you to use the DROP TABLEstatement to remove tables based on pattern matching.

    J. MySQL Temporary Table

    Summary: in this tutorial, we will discuss about MySQL temporary table and show you how to create, useand drop temporary tables.Introduction to MySQL temporary tableIn MySQL, a temporary table is a special type of table that allows you to store a temporary result set,which you can reuse several times in a single session. A temporary table is very handy when it is

    impossible or expensive to query data that requires a single SELECT statement with JOIN clauses. Youoften use temporary tables in stored procedures to store immediate result sets for the subsequent uses.MySQL temporary tables have some additional features: A temporary table is created by using CREATE TEMPORARY TABLE statement. Notice thattheTEMPORARY keyword is added between CREATE and TABLE keywords. MySQL drops the temporary table automatically when the session ends or connection isterminated. Of course, you can use the DROP TABLE statement to drop a temporary table explicitly whenyou are no longer use it. A temporary table is only available and accessible by the client who creates the table. Different clients can create a temporary table with the same name without causing errorsbecause only the client who creates a temporary table can see it. However, in the same session, twotemporary tables cannot have the same name. A temporary table can have the same name as an existing table in a database. For example, ifyou create a temporary table named employees in the sample database, the existing employeestable

    becomes inaccessible. Every query you issue against the employees table refers to theemployeestemporary table. When you remove the employees temporary table, the permanentemployees table isavailable and accessible again. Though this is allowed however it is not recommended to create a

    http://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-temporary-table/http://www.mysqltutorial.org/mysql-temporary-table/http://www.mysqltutorial.org/mysql-temporary-table/http://www.mysqltutorial.org/mysql-prepared-statement.aspx
  • 8/21/2019 MySQL Development.docx

    14/23

    temporary table whose name is same as a name of a permanent table because it may lead to a confusion.For example, in case the connection to the MySQL databaseserver is lost and you reconnect to theserver automatically, you cannot differentiate between the temporary table and the permanent table. Inthe worst case, you may issue a DROP TABLE statement to remove the permanent table instead of thetemporary table, which is not expected.Create MySQL temporary tableLike the CREATE TABLE statement, MySQL provides many options to create a temporary table. To create

    a temporary table, you just add the TEMPORARY keyword to the CREATE TABLE statement.For example, the following statement creates a top 10 customers by revenue temporary table based on

    the result set of a SELECT statement:

    123456

    789

    CREATE TEMPORARY TABLE top10customersSELECT p.customerNumber,

    c.customerName,FORMAT(SUM(p.amount),2) total

    FROM payments pINNER JOIN customers c ON c.customerNumber = p.customerNumber

    GROUP BY p.customerNumberORDER BY total DESCLIMIT 10

    Drop MySQL temporary tableYou can use the DROP TABLE statement to remove temporary tables however it is good practice to usethe DROP TEMPORARY TABLE statement instead. Because the DROP TEMPORARY TABLE removesonly temporary tables, not the permanent tables. In addition, the DROP TEMPORARY TABLE statement

    helps you avoid the mistake of removing a permanent table when you name your temporary table thesame as the name of the permanent table.

    DROP TEMPORARY TABLE top10customers

    SHOW {BINARY | MASTER} LOGS

    SHOW BINLOG EVENTS [IN 'log_name'] [FROMpos] [LIMIT [offset,] row_count]

    SHOW CHARACTER SET [like_or_where]

    SHOW COLLATION [like_or_where]

    SHOW [FULL] COLUMNS FROM tbl_name[FROM db_name] [like_or_where]

    SHOW CREATE DATABASEdb_name

    SHOW CREATE FUNCTION func_name

    SHOW CREATE PROCEDUREproc_name

    SHOW CREATE TABLE tbl_name

    SHOW DATABASES [like_or_where]

    SHOW ENGINE engine_name{LOGS | STATUS }

    SHOW [STORAGE] ENGINES

    SHOW ERRORS [LIMIT [offset,] row_count]

    SHOW FUNCTION CODE func_name

    SHOW FUNCTION STATUS [like_or_where]

    SHOW GRANTS FOR userSHOW INDEX FROM tbl_name[FROM db_name]

  • 8/21/2019 MySQL Development.docx

    15/23

    SHOW INNODB STATUS

    SHOW PROCEDURE CODEproc_name

    SHOW PROCEDURE STATUS [like_or_where]

    SHOW [BDB] LOGS

    SHOW MASTER STATUS

    SHOW MUTEX STATUS

    SHOW OPEN TABLES [FROM db_name] [like_or_where]

    SHOW PRIVILEGES

    SHOW [FULL] PROCESSLIST

    SHOW SLAVE HOSTS

    SHOW SLAVE STATUS

    SHOW PROFILE [types] [FOR QUERY n] [OFFSET n] [LIMIT n]

    SHOW PROFILES

    SHOW [GLOBAL | SESSION] STATUS [like_or_where]

    SHOW TABLE STATUS [FROM db_name] [like_or_where]

    SHOW [FULL] TABLES [FROM db_name] [like_or_where]

    SHOW TRIGGERS [FROM db_name] [like_or_where]

    SHOW [GLOBAL | SESSION] VARIABLES [like_or_where]

    SHOW WARNINGS [LIMIT [offset,] row_count]

    Difference between TRUNCATE, DELETE and DROP commands

    DELETEThe DELETE command is used to remove rows from a table. A WHERE clause can be used to onlyremove some rows. If no WHERE condition is specified, all rows will be removed. After performing aDELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent orto undo it. Note that this operation will cause all DELETE triggers on the table to fire.SQL> SELECT COUNT(*) FROM emp;

    COUNT(*)----------

    14

    SQL> DELETE FROM emp WHERE job = 'CLERK';

    4 rows deleted.

    SQL> COMMIT;

    Commit complete.

    SQL> SELECT COUNT(*) FROM emp;

    COUNT(*)----------

    10

  • 8/21/2019 MySQL Development.docx

    16/23

    TRUNCATE

    TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will befired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.SQL> TRUNCATE TABLE emp;

    Table truncated.

    SQL> SELECT COUNT(*) FROM emp;

    COUNT(*)----------

    0DROPThe DROP command removes a table from the database. All the tables' rows, indexes and privileges willalso be removed. No DML triggers will be fired. The operation cannot be rolled back.SQL> DROP TABLE emp;

    Table dropped.

    SQL> SELECT * FROM emp;

    SELECT * FROM emp*ERROR at line 1:ORA-00942: table or view does not exist

    DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETEoperations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.From Oracle 10g a table can be "undropped". Example:SQL> FLASHBACK TABLE EMP TO BEFORE DROP;

    Flashback complete.PS: DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. As such, DELETEoperations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.

    MySQL/Language/Definitions: what are DDL, DML and DQL?

    DDL (Data Definition Language) refers to the CREATE, ALTER and DROP statements

    DDL allows to add / modify / delete the logical structures which contain the data or which allow users to access /

    mantain the data (databases, tables, keys, views...). DDL is about "metadata".

    DML (Data Manipulation Language) refers to the INSERT, UPDATE and DELETE statements

    DML allows to add / modify / delete data itself.

    DQL (Data Query Language) refers to the SELECT, SHOW and HELP statements (queries)

    SELECT is the main DQL instruction. It retrieves data you need. SHOW retrieves infos about the metadata.

    HELP... is for people who need help.

    DCL (Data Control Language) refers to the GRANT and REVOKE statements

    DCL is used to grant / revoke permissions on databases and their contents. DCL is simple, but MySQL's

    permissions are rather complex. DCL is about security.

    DTL (Data Transaction Language) refers to the START TRANSACTION, SAVEPOINT, COMMIT and

    ROLLBACK [TO SAVEPOINT] statements

  • 8/21/2019 MySQL Development.docx

    17/23

    DTL is used to manage transactions (operations which include more instructions none of which can be executed

    if one of them fails).

    Granting Privileges on the new database:

    -----------------------------------------------

    mysql> GRANT ALL PRIVILEGES ON DatabaseName.* TO Username@localhost

    or

    mysql> GRANT ALL PRIVILEGES ON DatabaseName.* TO Username@localhost IDENTIFIED BY'newpassword';

    mysql> GRANT SELECT,INSERT,UPDATE,DELETE ON vworks.* TO newuser@localhost IDENTIFIEDBY 'newpassword';

    mysql> GRANT ALL PRIVILEGES ON DatabaseName.* TO [email protected] IDENTIFIED BY

    'newpassword';

    Now a user on the machine '192.168.0.2' can connect to the database. To allow a user to connectfrom anywhere you would use a wildcard '%'

    mysql> GRANT ALL PRIVILEGES ON DatabaseName.* TO Username@localhost IDENTIFIED BY'newpassword' WITH GRANT OPTION;

    This would allow the user 'newuser' to log into the database and give their friend privileges toSELECT,INSERT,UPDATE or DELETE from the database.

    For example to REVOKE the privileges assigned to a user called 'user1':

    mysql> REVOKE ALL PRIVILEGES ON DATABASENAME.* FROM user1@localhost;

    Or just to remove UPDATE, INSERT and DELETE privileges to that data cannot be changed.

    mysql> REVOKE INSERT,UPDATE,DELETE ON DATABASENAME.* FROM user1@localhost;

    Backing Up DataBase:-------------------------

    mysqlhotcopy -u -p /backup/location/

    Which SHOULD copy all the tables (*.frm, *.MYI, *.MYD) into the new directory - the script doesrequire the DBI perl module though. To restore these backup files simply copy them back into yourMySQL data directory.

    This is my preferred method of backing up. This outputs the table structure and data in series ofSQL commands stored in a text file. The simplified syntax is

    mysqldump -u -p > file.sql

    eg:

    mysqldump -u user1 -p accounts > dump.sql

    Restoring a DataBase from Dump:

  • 8/21/2019 MySQL Development.docx

    18/23

    ---------------------------------------

    mysqldump -u -p < file.sql

    eg:

    mysqldump -u user1 -p accounts < dump.sql

    FLUSH PRIVILEGES;

    When you create accounts withINSERT,it is necessary to useFLUSH PRIVILEGESto tell the server to reload

    the grant tables. Otherwise, the changes go unnoticed until you restart the server. WithCREATE USER,FLUSH

    PRIVILEGESis unnecessary.

    Queries

    SELECT customerNumber id, contactLastname name

    FROM customers

    UNION

    SELECT employeeNumber id,firstname name

    FROM employees

    SELECT customerNumber id, contactLastname name

    FROM customers

    UNION all

    SELECT employeeNumber id, firstname name

    FROM employees

    UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not.

    Inner join:The MySQL INNER JOIN clause matches rows in one table with rows in other tables

    SELECT column_list

    FROM t1

    INNER JOIN t2 ON join_condition1

    INNER JOIN t3 ON join_condition2

    ...

    WHERE where_conditions;

    inner join

    left join

    The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right

    table (table2).

    The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.

    http://dev.mysql.com/doc/refman/5.1/en/insert.htmlhttp://dev.mysql.com/doc/refman/5.1/en/insert.htmlhttp://dev.mysql.com/doc/refman/5.1/en/insert.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/create-user.htmlhttp://dev.mysql.com/doc/refman/5.1/en/create-user.htmlhttp://dev.mysql.com/doc/refman/5.1/en/create-user.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/create-user.htmlhttp://dev.mysql.com/doc/refman/5.1/en/flush.htmlhttp://dev.mysql.com/doc/refman/5.1/en/insert.html
  • 8/21/2019 MySQL Development.docx

    19/23

    SQL FULL OUTER JOIN Syntax

    SELECT column_name(s)FROM table1FULL OUTER JOIN table2ON table1.column_name=table2.column_name;

    SELECT Customers.CustomerName, Orders.OrderIDFROM CustomersFULL OUTER JOIN OrdersON Customers.CustomerID=Orders.CustomerIDORDER BY Customers.CustomerName;

    MySQL HAVING clause

    SELECT ordernumber,

    SUM(quantityOrdered) AS itemsCount,

    SUM(priceeach) AS total

    FROM orderdetails

    GROUP BY ordernumber

    HAVING total > 1000

    UPDATE T1, T2

    SET T1.c2 = T2.c2,

    T2.c3 = expr

    WHERE T1.c1 = T2.c1 AND condition

    UPDATE T1,T2

    INNER JOIN T2 ON T1.C1 = T2.C1

    SET T1.C2 = T2.C2,

    T2.C3 = expr

    WHERE condition

    UPDATE employees

    INNER JOIN merits ON employees.performance = merits.performance

    SET salary = salary + salary * percentage

    UPDATE employees

    LEFT JOIN merits ON employees.performance = merits.performance

    SET salary = salary + salary * 0.015;

    WHERE merits.percentage IS NULL

    Delete

    DELETE FROM employees

    WHERE officeCode = 4

    DELETE FROM employees

    DELETE employees,

    offices

    FROM employees,

    offices

    WHERE employees.officeCode = offices.officeCode AND

    offices.officeCode = 1

  • 8/21/2019 MySQL Development.docx

    20/23

    DELETE FROM employees, offices

    USING employees, offices

    WHERE employees.officeCode = offices.officeCode AND

    offices.officeCode = 1

    Truncate-truncate table categories

    ReplaceREPLACE INTO categories(categoryname,categoryid)VALUES('PQR','4');

    RDBMS

    RDBMS stands for Relational Database Management System.

    RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBMDB2, Oracle, MySQL, and Microsoft Access.

    The data in RDBMS is stored in database objects called tables.

    A table is a collection of related data entries and it consists of columns and rows.

    What is SQL?

    SQL stands for Structured Query Language

    SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard

    SELECT DISTINCT City FROM Customers;

    SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin';

    SELECT * FROM Customers WHERE City='Berlin' OR City='Mnchen';

    SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR

    city='Mnchen');

    SELECT * FROM Persons LIMIT 5;

    SELECT * FROM Persons WHERE ROWNUM

  • 8/21/2019 MySQL Development.docx

    21/23

    SELECT * FROM Customers WHERE City LIKE 'ber%' ;

    SELECT * FROM Customers WHERE City LIKE '_erlin'; (The following SQL statement

    selects all customers with a City starting with any character, followed by "erlin")

    SELECT * FROM Customers WHERE City LIKE 'L_n_on'; (The following SQL statement

    selects all customers with a City starting with "L", followed by any character, followedby "n", followed by any character, followed by "on")

    SELECT * FROM Customers WHERE City LIKE '[bsp]%'; (The following SQL statement

    selects all customers with a City starting with "b", "s", or "p")

    SELECT * FROM Customers WHERE City LIKE '[a-c]%'; (The following SQL statement

    selects all customers with a City starting with "a", "b", or "c")

    SELECT * FROM Customers WHERE City LIKE '[!bsp]%'; (The following SQL statement

    selects all customers with a City NOT starting with "b", "s", or "p")

    SQL UNION Example

    The following SQL statement selects all the differentcities (only distinct values) from the

    "Customers" and the "Suppliers" tables:

    SELECT City FROM Customers

    UNION

    SELECT City FROM Suppliers

    ORDER BY City;

    The following SQL statement uses UNION ALL to select all(duplicate values also) cities from the

    "Customers" and "Suppliers" tables:SELECT City FROM Customers

    UNION ALL

    SELECT City FROM Suppliers

    ORDER BY City;

    The following SQL statement uses UNION ALL to select all(duplicate values also) Germancities

    from the "Customers" and "Suppliers" tables:

    SELECT City, Country FROM Customers

    WHERE Country='Germany'

    UNION ALL

    SELECT City, Country FROM SuppliersWHERE Country='Germany'

    ORDER BY City;

    SQL SELECT INTO Examples

    Create a backup copy of Customers:

    SELECT *

    INTO CustomersBackup2013

    FROM Customers;

    Use the IN clause to copy the table into another database:

  • 8/21/2019 MySQL Development.docx

    22/23

    SELECT *

    INTO CustomersBackup2013 IN 'Backup.mdb'

    FROM Customers;

    Copy only a few columns into the new table:

    SELECT CustomerName, ContactNameINTO CustomersBackup2013

    FROM Customers;

    Copy only the German customers into the new table:

    SELECT *

    INTO CustomersBackup2013

    FROM Customers

    WHERE Country='Germany';

    Copy data from more than one table into the new table:

    SELECT Customers.CustomerName, Orders.OrderID

    INTO CustomersOrderBackup2013

    FROM Customers

    LEFT JOIN Orders

    ON Customers.CustomerID=Orders.CustomerID;

    Tip: The SELECT INTO statement can also be used to create a new, empty table using the

    schema of another. Just add a WHERE clause that causes the query to return no data:

    SELECT *

    INTO newtable

    FROM table1

    WHERE 1=0;

    SQL INSERT INTO SELECT ExamplesINSERT INTO Customers (CustomerName, Country)SELECT SupplierName, Country FROM Suppliers WHERE

    Country='Germany';

    NULL Function

    MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's

    ISNULL() function.

    In MySQL we can use the IFNULL() function, like this:

    SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))

    FROM Products

    or we can use the COALESCE() function, like this:

    SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))

    FROM Products

  • 8/21/2019 MySQL Development.docx

    23/23