Laboratory Manual On MYSQL For Year IV Database Students (Power and Control Engineering Stream Students)
Laboratory Manual On MYSQL For Year IV Database Students (Power and Control Engineering Stream Students)
Laboratory Manual on MYSQL for year IV database students (power and control engineering stream students)
Manual 2
Addishiwot
Page 1
Page 2 of 20
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.
Addishiwot
Page 2
Page 3 of 20
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 127 signed). 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-point numbers).
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
Addishiwot
Page 3
Page 4 of 20
The width specification is most often used with zerofill because you can easily see the results:
The effect of the width specification in id is to limit the display to three characters, while the id2 field uses the normal unsigned INT default (10).
Table 2. String Types Type [NATIONAL] CHAR(M) [BINARY] Description Character. A fixed-length string, right-padded with spaces to the specified length. From 0 to 255 characters (1 to 255 prior to MySQL version 3.23). Trailing spaces are removed when the value is retrieved. This is a synonym for CHAR(1). Variable-length character. A variable-length string, where trailing spaces are removed when the value is stored (this is a bug, and can catch out those coming from another DBMS, where this is not the case). From 0 to 255 characters (1 to 255 prior to MySQL version 4.0.2). Tiny binary large object. Maximum 255 characters (28- 1). Requires length + 1 bytes storage. Same as TINYTEXT, except that searching is done case sensitively. In most situations, use rather use VARCHAR BINARY, as it should be faster. Maximum 255 characters (28- 1). Requires length + 1 bytes storage. Same as TINYBLOB, except that searching is done case insensitively. In most situations, rather use VARCHAR, as it should be faster. Binary large object. Maximum 65,535 characters (216- 1). Requires length + 2 bytes storage. Same as TEXT, except that searching is done case sensitively. Maximum 65,535 characters (216- 1). Requires length + 2 bytes storage. Same as BLOB, except that searching is done case insensitively. Medium-sized binary large object. Maximum 16,777,215 characters (224- 1). Requires length + 3 bytes storage. Same as MEDIUMTEXT, except that searching is done case sensitively. Maximum 16,777,215 characters (224- 1). Requires length + 3 bytes storage. Same as MEDIUMBLOB, except that searching is done case insensitively.
TINYBLOB
TINYTEXT
MEDIUMTEXT
Addishiwot
Page 4
Page 5 of 20
Table 2. String Types Type LONGBLOB Description Large binary large object. Maximum of 4,294,967,295 characters (232- 1). Requires length + 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 per communication packet/table row. 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 that because of external limitations, there is a limit of 16MB per communication packet/table row. Enumeration. Can only have one of the specified values, NULL or "". Maximum of 65,535 values. A set. Can contain zero to 64 values from the specified list.
LONGTEXT
ENUM('value1','value2',...) SET('value1','value2',...)
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. Each digit 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
Addishiwot
Page 5
Page 6 of 20
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 <) allow you to compare values, and narrow result sets in this way. Finally, bit operators, while not often used, allow you to work at a bit level in your queries.
Logical Operators
Logical operators reduce to either true (1) or false (0). For example, if you are male, and I ask whether you're male OR female (assume I'm asking for a yes/no answer), the answer would be yes, or true. If I ask whether you're male AND female, the answer would be no, or false. The AND and OR in the questions are logical operators. Table 3.describes the operators in more detail.
Addishiwot
Page 6
Page 7 of 20
Table 3: Logical Operators Operator AND, && OR, || !, NOT Syntax c1 AND c2, c1 && c2 c1 OR c2, c1 || c2 ! c1, NOT c1 Description Only true if both conditions c1 and c2 are true. True if either c1 or c2 is true. 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 a+b a-b Description Adds a and b together, returning the sum of both Subtracts b from a, returning the difference
Addishiwot
Page 7
Page 8 of 20
Table 5: Arithmetic Operators Operator * / % Syntax a*b a/b a%b Description Multiplies a and b, returning the product of both Divides a by b, returning the quotient 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 = !=, <> > < >= <= <=> IS NULL IS NOT NULL BETWEEN NOT BETWEEN LIKE NOT LIKE Syntax a=b a != b, a <> b a>b a<b a >= b a <= b a <=> b a is NULL a IS NOT NULL a BETWEEN b and c a NOT BETWEEN b and c a LIKE b a NOT LIKE b Description True if both a and b are equal (excluding NULL). True if a is not equal to b. True if a is greater than b. True if a is less than b. True if a is greater than or equal to b. True if a is less than or equal to b. True if a and b are equal (including NULL). True if a contains a NULL value. True if a does not contain a NULL value. True if a is between the values of b and c, inclusive. True if a is not between the values of b and c, inclusive. True if a matches b on an SQL pattern match. True if a does not match b on an SQL pat-tern match. The two acceptable wildcard characters are % (which means any number of
Addishiwot
Page 8
Page 9 of 20
Table 6: Comparison Operators Operator Syntax Description characters) and _ (which means one character). IN NOT IN REGEXP, RLIKE NOT REGEXP, NOT RLIKE a IN (b1, b2, b3) a NOT IN (b1,b2,b3) a REGEXP b, a RLIKE b a NOT REGEXP b, a NOT RLIKE B True if a is equal to anything in the list. True if a is not equal to anything in the list. True if a matches b with a regular expression. 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 OPerators Operator & | << >> Syntax a&b a|b a << b a >> b Description Bitwise AND Bitwise OR Left shift of a by b bit positions 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:
Addishiwot
Page 9
Page 10 of 20
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.
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.
Addishiwot
Page 10
Page 11 of 20
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;
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
Addishiwot
Page 11
Page 12 of 20
Let's first try a simple example first, performing a LEFT JOIN on just the customer and 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:
Addishiwot
Page 12
Page 13 of 20
mysql> SELECT first_name,surname,value FROM customer RIGHT JOIN sales ON id=customer;
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 be INT and DECIMAL, or even INT and VARCHAR, as long as they have the same name.
Addishiwot
Page 13
Page 14 of 20
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');
Addishiwot
Page 14
Page 15 of 20
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 WHERE sales_rep.employee_number IN (SELECT code FROM sales WHERE value>1000);
Addishiwot
Page 15
Page 16 of 20
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 customer GROUP 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), surname VARCHAR(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 JOIN customer 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;
Addishiwot
Page 16
Page 17 of 20
Creating a Primary Key A primary 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 use ALTER TABLE statement ALTER TABLE customer MODIFY id int not null, add primary key(id);
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, PRIMARY KEY(id,id2));
Addishiwot
Page 17
Page 18 of 20
or as follows if the table already exists: mysql> ALTER TABLE pk2 ADD PRIMARY KEY(id,id2); The sales table from does not yet have a key: SHOW COLUMNS FROM sales; Or equivalently DESCRIBE sales;
Let's assume you add a new record with the same code as an existing record: mysql> INSERT INTO sales VALUES(7,3,3,1000);
There is no problem so far. Even though there are now two records with a code of 7, there is nothing in the table structure that disallows this. But now, with your new knowledge of the reasons for using a primary key, you decide to make the code field a primary key: ERROR mysql> ALTER TABLE sales MODIFY code INT NOT NULL,ADD PRIMARY KEY(code);
You have a duplicate value for the code field, and by definition a primary key should always be unique. Here, you would have to either remove or update the duplicates or use an ordinary index that allows duplicates. Most tables work better with a primary key, though. In this situation, it's easy to update the responsible record: mysql> UPDATE sales SET code=8 WHERE code=7 AND sales_rep=3;
Addishiwot
Page 18
Page 19 of 20
mysql> ALTER TABLE sales MODIFY code INT NOT NULL,ADD PRIMARY KEY(code);
Now if you try to insert duplicate entries for code then an error message will be displayed
Using an Auto Increment Field An auto increment field is a useful feature that allows the value of a field to be automatically incremented each time a new record is inserted. Only one field in a record can be auto incremented, and this field must be a numeric primary key or a numeric unique index. Creating an Auto Increment Field The syntax to create an auto increment field when creating a new table is: CREATE TABLE tablename(fieldname INT AUTO_INCREMENT, [fieldname2...,] PRIMARY KEY(fieldname)); To create an auto increment field in an already existing table, use this syntax: ALTER TABLE tablename MODIFY fieldname columntype AUTO_INCREMENT; Lets try to add an auto increment on sales table Mysql>ALTER TABLE sales MODIFY code int not null auto_increment,add primary key(code); Since we have already added primary key,we must modify the above code as Mysql>ALTER TABLE sales MODIFY code int not null auto_increment;
The id field is a numeric field that is already a primary key, and because you've been assigning the id in sequence to date, turning the id into an auto increment field will allow MySQL to automate this process for you. The following code makes the id field auto increment: mysql> ALTER TABLE customer MODIFY id INT AUTO_INCREMENT;
Addishiwot
Page 19
Page 20 of 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;
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.
Addishiwot
Page 20