+ All Categories
Home > Documents > Database+Manual+2[1]

Database+Manual+2[1]

Date post: 04-Apr-2018
Category:
Upload: aylate
View: 215 times
Download: 0 times
Share this document with a friend

of 20

Transcript
  • 7/30/2019 Database+Manual+2[1]

    1/20

    Page 1 of20

    Addishiwot Page 1

    Laboratory Manual on MYSQL for year IV database students

    (power and control engineering stream students)

    Manual 2

    Prepared by: Addishiwot Tadesse(MSc)

    [email protected]

  • 7/30/2019 Database+Manual+2[1]

    2/20

    Page 2 of20

    Addishiwot Page 2

    Data Types and Table Types

    Overview

    As you know, MySQL uses a number of table types. By default, it uses the MyISAM table type, optimized for

    SELECT speed. Most websites use this table, as websites usually have infrequent INSERT or UPDATE statements

    and frequent SELECT statements

    Exploring the Various Column Types

    There are three main types of columns in MySQL: numeric, string, and date. Although there are many more specific

    types, which you'll learn about shortly, you can classify each of these into one of the three main types. Generally,

    you should choose the smallest possible column type, as this will save space and be faster to access and update.

    However, choosing too small a column can result in data being lost or cut off when you insert it, so be sure to

    choose a type that covers all eventualities

    Numeric types are designed for storing any kind of numeric data, such as prices, ages, or quantities. There are two

    main kinds of numeric types: integer types (whole numbers, without any decimal places or fractional parts) and

    floating-point types.

    All numeric types allow two options: UNSIGNED and ZEROFILL. UNSIGNED prohibits negative numbers

    (extending the positive range of the type for integer types), and ZEROFILL pads the value with zeroes instead of the

    usual spaces, as well as automatically making it UNSIGNED. For example

    Notice that because the field is UNSIGNED, the negative number is adjusted to fit into the bottom of the range, and

    because the 340 exceeds the maximum of the range, it is adjusted to 255, the maximum allowable positive value.

  • 7/30/2019 Database+Manual+2[1]

    3/20

    Page 3 of20

    Addishiwot Page 3

    Use the following guidelines when deciding what numeric type to choose:

    Choose the smallest applicable type (TINYINT rather than INT if the value would never go beyond 127signed). For whole numbers, choose an integer type. (Remember that money can also be stored as a whole

    numberfor example, it can be stored in cents rather than dollars, which are integers.) It could also be

    reasonably stored as a DECIMAL.

    For high precision, use integer types rather than floating-point types (rounding errors afflict floating-pointnumbers).

    The M value in the above table often causes confusion. Setting M to a higher value than the type allows will not

    allow you to extend its limit.

    Even though the figure inserted was fewer than 10 digits, because it is a signed TINYINT, it is limited to a

    maximum positive value of 127. However, if you try to limit a type to less than its allowable limit, the value is not

    cut off. It neither constrains the range that can be stored nor the number of digits displayed

    For example

  • 7/30/2019 Database+Manual+2[1]

    4/20

  • 7/30/2019 Database+Manual+2[1]

    5/20

    Page 5 of20

    Addishiwot Page 5

    Table 2. String Types

    Type Description

    LONGBLOB Large binary large object. Maximum of 4,294,967,295 characters (232- 1). Requireslength + 4 bytes storage. Same as LONGTEXT, except that searching is done case

    sensitively. Note that because of external limitations, there is a limit of 16MB percommunication packet/table row.

    LONGTEXT Maximum of 4,294,967,295 characters (232- 1). Requires length + 4 bytes storage.Same as LONGBLOB, except that searching is done case insensitively. Note thatbecause of external limitations, there is a limit of 16MB per communicationpacket/table row.

    ENUM('value1','value2',...) Enumeration. Can only have one of the specified values, NULL or "". Maximum of

    65,535 values.

    SET('value1','value2',...) A set. Can contain zero to 64 values from the specified list.

    Use the following guidelines when deciding what string type to choose:

    Never store numbers in string columns. It is much more efficient to store them in numeric columns. Eachdigit in a string field takes up an entire byte, as opposed to a numeric field, which is stored in bits. Also,

    ordering numbers if they are stored as a string may yield inconsistent results. For speed, choose fixed columns, such as CHAR. To save space, use dynamic columns, such as VARCHAR. For limiting contents of a column to one choice, use ENUM. For allowing more than one entry in a column, choose SET. For text you want to search case insensitively, use TEXT. For text you want to search case sensitively, use BLOB. For images, and other binary objects, store them on the file system rather than directly in the database.

    Note :Searching CHAR and VARCHAR fields case insensitively is not common among most DBMSs, so be careful

    if you're moving to MySQL from another DBMS.

    The NATIONAL keyword is only there for ANSI SQL compliance. (ANSI stands for the American National

    Standards Institute, and they have developed a "standard" SQL. Most database management systemsDBMSs

    adhere to this to some degree, but few do so entirely, and many have their own additions.) It tells the DBMS to use

    the MySQL default character set (which is the MySQL standard anyway).

    Note: Using CHAR as opposed to VARCHAR leads to larger tables, but usually faster processing, because MySQL

    knows exactly where each record starts. .

    ENUM columns have some interesting features. If you add an invalid value, an empty string ("") is inserted instead,

    as follows

  • 7/30/2019 Database+Manual+2[1]

    6/20

    Page 6 of20

    Addishiwot Page 6

    You can also perform queries on enumerated fields based on their indexes (the first value starts at 1).for

    example

    Operators

    Operators are the building blocks of complex queries.Logical operators (such as AND and OR) allow you to relate

    numbers of conditions in various ways.Arithmetic operators (such as are + or *) allow you to perform basic

    mathematical operations in your queries. Comparison operators (such as > or

  • 7/30/2019 Database+Manual+2[1]

    7/20

    Page 7 of20

    Addishiwot Page 7

    Table 3: Logical Operators

    Operator Syntax Description

    AND, && c1 AND c2, c1 && c2 Only true if both conditions c1 and c2 are true.

    OR, || c1 OR c2, c1 || c2 True if either c1 or c2 is true.

    !, NOT ! c1, NOT c1 True if c1 is false, false if c1 is true.

    Instead of populating a table and running queries against this, the following examples will produce either a 1 or a 0.

    Each row in the tables you query will also reduce to a 1 or a 0. 1s will be returned, and 0s will not be. If you

    understand this, you can apply the principles to any of your own tables. If you're going through these operators for

    the first time, see if you can predict the results based on Table 3.1.

    mysql> SELECT 1 AND 0;

    +---------+| 1 AND 0 |+---------+| 0 |+---------+

    mysql> SELECT NOT(1 AND 0);+--------------+| NOT(1 AND 0) |+--------------+| 1 |+--------------+

    mysql> SELECT !((1 OR 0) AND (0 OR 1));+--------------------------+| !((1 OR 0) AND (0 OR 1)) |+--------------------------+

    | 0 |+--------------------------+

    Remember that conditions inside the innermost parentheses are evaluated first. So, MySQL simplifies the complex

    statement in the previous example as follows:

    !((1 OR 0) AND (0 OR 1))!((1) AND (1))!(1)0

    Arithmetic Operators

    Arithmetic operators are used to perform basic mathematical operations. For example, when I say that 2 + 3 = 5, the

    plus sign (+) is an arithmetic operator. Table 4 describes the arithmetic operators available in MySQL.

    Table 5: Arithmetic Operators

    Operator Syntax Description

    + a + b Adds a and b together, returning the sum of both

    - a - b Subtracts b from a, returning the difference

  • 7/30/2019 Database+Manual+2[1]

    8/20

    Page 8 of20

    Addishiwot Page 8

    Table 5: Arithmetic Operators

    Operator Syntax Description

    * a * b Multiplies a and b, returning the product of both

    / a / b Divides a by b, returning the quotient

    % a % b a modulus b, returning the remainder after a / b

    For example, adding together two columns of type INT will produce an INT:

    mysql> SELECT 2+1;+-----+| 2+1 |+-----+| 3 |+-----+

    mysql> SELECT 4-2/4;+-------+

    | 4-2/4 |+-------+| 3.50 |

    Comparison Operators

    Comparison operators are used when making comparisons between values. For example, I can make the statement

    that 34 is greater than 2. The is greater than part is a comparison operator. Table 6.lists and describes the comparison

    operators used in MySQL.

    Table 6: Comparison Operators

    Operator Syntax Description

    = a = b True if both a and b are equal (excludingNULL).

    !=, a != b, a b True if a is not equal to b.

    > a > b True if a is greater than b.

    < a < b True if a is less than b.

    >= a >= b True if a is greater than or equal to b.

  • 7/30/2019 Database+Manual+2[1]

    9/20

    Page 9 of20

    Addishiwot Page 9

    Table 6: Comparison Operators

    Operator Syntax Description

    characters) and _ (which means one

    character).

    IN a IN (b1, b2, b3) True if a is equal to anything in the list.

    NOT IN a NOT IN (b1,b2,b3) True if a is not equal to anything in the list.

    REGEXP, RLIKE a REGEXP b, a RLIKE b True if a matches b with a regular expression.

    NOT REGEXP, NOT RLIKE a NOT REGEXP b, a NOT

    RLIKE B

    True if a does not match b with a regular

    expression.

    Bit Operators

    To understand how bit operations work, you'll need to know a little bit about Boolean numbers and Boolean

    arithmetic. These kinds of queries aren't often used, but any self-respecting "guru2be" needs to have them as part of

    their repertoire. Table 7describes the bit operators.

    Table 7: Bit OPeratorsOperator Syntax Description

    & a & b Bitwise AND

    | a | b Bitwise OR

    a >> b Right shift of a by b bit positions

    For example : the binary representation of 9 is 1001 and the binary representation of 8 is 1000.

    8 | 9 implies (1000 |1001)= 1001 which is 9.

    8 & 9 implies(1000 & 1001)=1000 which is 8

    The >> is the right shift operator, so a >> b shifts the bits of a right by b columns. Bits shifted beyond the "ones"

    column are lost. And, again, shifting by a negative number returns 0.

    For example:

  • 7/30/2019 Database+Manual+2[1]

    10/20

    Page 10 of20

    Addishiwot Page 10

    Advanced Joins

    You've already looked at a basic two-table join in Manual 1. But joins can get much more complicated than that, and

    badly written joins are the culprits in the majority of serious performance problems.

    Let's return to the tables created in the manual 1.

    The Sales table that you built on manual 1 was

    The Customer table that you created on manual 1 was

    Because the relationship between the sales_rep and sales tables is on the employee_number, or sales_rep field, those

    two fields form the join condition of the WHERE clause.

  • 7/30/2019 Database+Manual+2[1]

    11/20

    Page 11 of20

    Addishiwot Page 11

    To do a more complex join over all three tables is not much more complicated. If you wanted to return the first

    names and surnames of both the sales rep and the customer, as well as the value of the sale, you'd use this query:

    Inner Joins

    Inner joins are just another way of describing the first kind of join you learned. The following two queries are

    identical:

    mysql> SELECT first_name,surname,value FROM customer,sales WHERE

    id=customer;

    This simple join can be done using JOIN statement as follows

    Lets say that you have forgotten capturing the details of one customer.lets put NULL for the customer to whom you

    forget to record his/her detail

    Mysql>INSERT INTO sales(code,sales_rep,customer,value) VALUES

    (7, 2,NULL,670);

    Let's run the query that returns the value and the names of the sales reps and customers for each sale again

  • 7/30/2019 Database+Manual+2[1]

    12/20

    Page 12 of20

    Addishiwot Page 12

    Let's first try a simple example first, performing a LEFT JOIN on just the customerand sales tables.

    mysql> SELECT first_name,surname,value FROM sales LEFT JOIN customer

    ON id=customer;

    Table order in a LEFT JOIN is important. The table from which all matching rows are returned must be the left table

    (before the LEFT JOIN keywords). If you'd reversed the order and tried the following:

    mysql> SELECT first_name,surname,value FROM customer LEFT JOIN sales ON id=customer;

    Of course, you can extend this across a third table to answer the original query (names of customers and sales reps,

    as well as sales values, for each sale). See if you can do it. This is my suggestion:

    Right Joins (Right Outer Joins)

    Right joins are exactly the same as left joins, except that the order of the join is reversed. To return for each sale the

    names of all customers, including those sales where there is no corresponding customer data, you have to put the

    sales table on the right in your join:

  • 7/30/2019 Database+Manual+2[1]

    13/20

    Page 13 of20

    Addishiwot Page 13

    mysql> SELECT first_name,surname,value FROM customer RIGHT JOIN

    sales ON id=customer;

    Natural Joins and the USINGKeyword

    The id field in the customer table and the customer field in the sales table are related. If you have given them the

    same name, SQL has a few shortcuts that make the JOIN statements less unwieldy. Let's rename sales.customer to

    sales.id for now, to demonstrate:

    mysql> ALTER TABLE sales CHANGE customer id INT;

    Now because the two tables have fields with identical names, you can perform a NATURAL JOIN, which looks for

    identically named fields on which to perform the JOIN:

    mysql> SELECT first_name,surname,value FROM customer NATURAL JOIN sales;

    This is identical to the following:

    mysql> SELECT first_name,surname,value FROM customer INNER JOIN

    sales ON customer.id=sales.id;

    The USING keyword allows a bit more control than a NATURAL JOIN. If there is more than one identical field in

    the two tables, this keyword allows you to specify which of these fields are used as join conditions. For example,

    taking two tables A and B with identical fields a,b,c,d, the following are equivalent:

    SELECT * FROM A LEFT JOIN B USING (a,b,c,d)

    SELECT * FROM A NATURAL LEFT JOIN B

    The USING keyword allows more flexibility because it allows you to use only some of the four identical fields. For

    example:

    SELECT * FROM A LEFT JOIN B USING (a,d)

    NoteFor purposes of a NATURAL JOIN, identical means identical in name, not in type. The two id fields could beINT and DECIMAL, or even INT and VARCHAR, as long as they have the same name.

    Returning Results Found in One Table, but Not the Other

    So far you've returned rows that appear in both tables you're joining with an INNER JOIN. With the OUTER JOIN,

    you also returned records from one table where wasn't a corresponding match in the other table. Quite often it's

  • 7/30/2019 Database+Manual+2[1]

    14/20

    Page 14 of20

    Addishiwot Page 14

    useful to do the converse and return results that are found only in one table, but not the other. To demonstrate this,

    let's first add a new sales_ rep:

    mysql> INSERT INTO sales_rep VALUES(5, 'Roman', 'Temesgen', 10,

    '2002-11-29', '1989-12-01');

    Now, if you do an INNER JOIN, you can return all the sales reps who have made a sale:

    mysql> SELECT DISTINCT first_name,surname FROM sales_rep INNER JOIN sales ON

    sales_rep=employee_number;

    This code returned records found in one table i.e sales_rep table but not found in sales table

    mysql> SELECT first_name,surname FROM sales_rep LEFT JOIN sales ON sales_rep=employee_number

    WHERE sales_rep IS NULL;

    To see the use of this statement, let's create another table, containing a list of customers handed over from the

    previous owner of your store:

    mysql> CREATE TABLE old_customer(id int, first_name varchar(30),

    surname varchar(40));mysql> INSERT INTO old_customer VALUES (10, 'Oli', 'Tilahun'),

    (11, 'Habtamu', 'Tamire');

  • 7/30/2019 Database+Manual+2[1]

    15/20

    Page 15 of20

    Addishiwot Page 15

    Now, to get a list of all customers, both old and new, you can use the following:

    mysql> SELECT id, first_name, surname FROM old_customer UNION SELECT

    id, first_name,surname FROM customer;

    This line of SQL cod can also retrieves the union of the two tables

    SELECT * FROM customer UNION SELECT * FROM old_customer;

    You can also order the output as normal. You just need to be careful about whether the ORDER BY clause applies

    to the entire UNION or just to the one SELECT:

    mysql> SELECT id, first_name, surname FROM old_customer UNION SELECT

    id, first_name, surname FROM customer ORDER BY surname,first_name;

    By default, UNION does not return duplicate results (similar to the DISTINCT keyword). You can override this by

    specifying that all results must be returned with the ALL keyword:

    mysql> SELECT id FROM customer UNION ALL SELECT id FROM sales;

    Rewriting Sub-selects as Joins

    Let's take a query where you want to return all the sales reps who have made a sale with a value greater than Birr

    1,000. If you can run a sub-select, try the following:

    mysql> SELECT first_name,surname FROM sales_rep WHEREsales_rep.employee_number IN (SELECT code FROM sales WHEREvalue>1000);

    Adding Records to a Table from Other Tables

    withINSERT SELECT

  • 7/30/2019 Database+Manual+2[1]

    16/20

    Page 16 of20

    Addishiwot Page 16

    The INSERT statement also allows you to add records, or parts of records, that exist in other tables. For example,

    let's say you want to create a new table containing the customer names and the values of all the purchases they have

    made. The query to return the results you want would be the following:

    mysql> SELECT first_name,surname,SUM(value) FROM sales NATURAL JOIN customerGROUP BY first_name, surname;

    First you'll need to create the table to receive the results:

    mysql> CREATE TABLE customer_sales_values(first_name VARCHAR(30), surnameVARCHAR(40), value INT);

    Now, you insert the results into this table:

    mysql> INSERT INTO customer_sales_values(first_name,surname,value)SELECT first_name,surname, SUM(value) FROM sales NATURAL JOINcustomer GROUP BY first_name, surname;

    The customer_sales_values table now contains the following:

    More about Adding Records

    INSERT also allows a syntax similar to the one used by an UPDATE statement. Instead of saying the following:

    mysql> INSERT INTO customer_sales_values(first_name, surname, value)VALUES('Chala', 'meshesha', 0);

    you could say this:

    mysql> INSERT INTO customer_sales_values SET first_name =

    'Chala', surname='meshesha', value=0;

  • 7/30/2019 Database+Manual+2[1]

    17/20

    Page 17 of20

    Addishiwot Page 17

    Creating a Primary Key

    Aprimary key is an index on a field where each value is unique and none of the values are NULL.

    Note:The term primary key is, strictly speaking, a logical term, but MySQL uses it to denote a physical index. When

    MySQL indicates that a primary key exists, there is always an associated index. Throughout this text, the term

    key indicates the presence of a physical index.

    To create a primary key when creating a table, use PRIMARY KEY at the end of the field definitions, with a list of

    the fields to be included:

    CREATE TABLE tablename(fieldname columntype NOT NULL,[fieldname2...,] PRIMARY KEY(fieldname1 [,fieldname2...]));

    Note that the keyword NOT NULL is mandatory when creating a primary key; primary keys cannot contain a null

    value. MySQL warns you if you forget to specify this:

    mysql> CREATE TABLE pk_test(f1 INT, PRIMARY KEY(f1));

    ERROR 1171: All parts of a PRIMARY KEY must be NOT NULL;If you need NULL in a key, use UNIQUE instead

    To create a primary key on an already existing table, you can use the ALTER keyword:

    ALTER TABLE tablename ADD PRIMARY KEY(fieldname1 [,fieldname2...]);

    Choosing a primary key for the customer table is fairly easy. You can useALTER TABLE statement

    ALTER TABLE customer MODIFY id int not null, add primary key(id);

    Now you can see the new customer table definition as

    Primary keys can also consist of more than one field. Sometimes there is no one field that can uniquely identify a

    record. To add a primary key in this instance, separate the fields with a comma:

    mysql> CREATE TABLE pk2(id INT NOT NULL, id2 INT NOT NULL, PRIMARYKEY(id,id2));

  • 7/30/2019 Database+Manual+2[1]

    18/20

  • 7/30/2019 Database+Manual+2[1]

    19/20

  • 7/30/2019 Database+Manual+2[1]

    20/20

    Page 20 of20

    Addishiwot Page 20

    Inserting Records Containing an Auto Increment Field

    Now, if you add a record, you don't need to specify the value of the id; MySQL will automatically add the next

    highest value:

    mysql> SELECT * FROM customer;

    Mysql>INSERT INTO customer(first_name,surname) VALUES('Amanuel','Alemu');

    An important feature is that MySQL's auto increment counter remembers the most recently added number, even if

    this record is deleted. This ensures that the newly inserted record has a new id value and does not clash with any

    records related to the old entry:

    mysql> DELETE FROM customer WHERE id=6;

    mysql> INSERT INTO customer(first_name,surname)VALUES('Amanuel','Wale');

    The id is now 7. Even though the next highest remaining record is 5, the most recently inserted value was 6.


Recommended