Mysql Chapter-1: Database
Mysql Chapter-1: Database
Mysql Chapter-1: Database
MYSQL CHAPTER-1
Introduction
Database
A database is a organized collection of data.
Database -> Data File -> Record - > Data Item
Relational Database
It is a collection of logically related tables.
Table/Relation: A group of rows and columns form a table. The horizontal subset of
the Table is known as a Row/Tuple. The vertical subset of the Table is known as a
Column/an Attribute.
Example:
Table: Employee
Eno
45
32
12
09
Name
Ramanuj Singh
Gareema Seth
John Brooke
Ahmed Abdul
Desig
Dir
Mgr
Acc
Mgr
Salary
90000
78000
25000
78000
A Primary Key is one of the candidate keys, which is used to identift a row
uniquely.
MySQL - 1
MYSQL
Note: A table may have more than one candidate keys but definitely has one
and only one primary key.
Alternate Key: Only one of the candidate key will be selected as a primary
key of a table. All other candidates are called Alternate keys.
Introduction to MySQL.
MySQL is a fast, easy-to-use RDBMS used for small and big business applications.
MySQL is developed, marketed, and supported by a Swedish Company MySQL AB.
MySQL is a easy to install RDBMS and capable of handling large data sets.
2
MySQL - 2
MYSQL CHAPTER-2
Installing MySQL
Windows Environment
DOWNLOADING MySQL
INSTALLING MySQL
After the installation file has finished downloading, double-click it, which begins
the MySQL Setup Wizard.
MySQL - 3
MYSQL
4
MySQL - 4
CONFIGURING MySQL
At the initial Server Instance Configuration Wizard dialog box, click the "Next"
button.
Keep selecting the default options provided in subsequent windows. If the
configuration does not encounter any errors, then information will be prompted
that the configuration file was created, the MySQL service was installed and
started, and the security settings have been applied.
Note: In the process of configuration of MySQL, a prompt for password will be
displayed Remember this password will be required each time to start MySQL
Testing MySQL
Follow the steps to start MySQL
Start> Programs>MySQL>.>MySQL Command Line Client
OR
MySQL - 5
MYSQL
MySQL will prompt a message to provide password (it requires the same password,
which was entered during the installation)
Enter Password:****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.0.51a-community-nt MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
Mysql>
To exit from MySQL, type QUIT or EXIT
Mysql>QUIT
The above steps ensure successful installation and configuration of MySQL database
server. Next time in the MySQL prompt, one can create and use databases, create
tables and execute SQL queries.
Linux Environment
Installation of the binary version of MySQL, release 4.0.20, to run on Linux is as
follows:
DOWNLOADING MYSQL
# cd mysql
# scripts/mysql_install_db --user=mysql
6
Preparing db table
Preparing host table
MySQL - 6
...
...
...
The latest information about MySQL is available on the web at
http://www.mysql.com
Support MySQL by buying support/licenses at https://order.mysql.com
STARTING AND STOPPING THE DATABASE SOFTWARE
Ensure that the MySQL Software, the mysqld server, is running and the initial
MySQL tables has been set.
MySQL - 7
MYSQL
MYSQL CHAPTER 3
Starting with MySQL
Connecting To Server
To start working with MySQL, a connection to the database is required. The first
step in database management is to create a database (assuming the user has
privilege to create database)
mysql> CREATE DATABASE School;
Now the database called School is created. One must be connected to the database
before using it.
mysql> use mydatabase;
Database Changed
Now, MySQL prompt can accept any query related to the database School.
To create a table in the database
Syntax:
CREATE TABLE <TableName>(<ColumnName1> <Data Type1>,
<ColumnName2> <Data Type2>, ,<ColumnNameN> <Data TypeN>);
Example:
mysql> CREATE TABLE Student
(
RollNo DECIMAL(3),
Name
VARCHAR(25)
);
Syntax:
SELECT * FROM <TableName>;
8
MySQL - 8
Example:
mysql> SELECT * FROM Student;
+---------------------------+
|Rno
| Name
|
+---------------------------+
| 14
| Aruna Asaf Ali
|
| 12
| Tarun Sinha
|
| 16
| John Fedrick
|
| 10
| Yogi Raj Desai
|
+---------------------------+
Any time to know the database currently in use, the command SELECT DATABASE()
can be used.
mysql> select database();
database()
school_db
1 row in set 0.0 secs
MySQL - 9
MYSQL
MYSQL CHAPTER 4
Creating and Managing Tables
MySQL Data Types
Every column (or data item) should belong to a unique domain (known as data
type). These data types help to describe the kind of information a particular
column holds. MySQL supports the ANSI SQL data types. Some of the commonly
used data types alongwith their characteristics are as follows:
Class
Data Type
Description
Text
CHAR(size)
Format
VARCHAR(size) A
variable-length
string VARCHAR
between 1 and 255 characters (size)
in
length;
for
example
VARCHAR(25).
Values must be enclosed in
single quotes or double quotes.
#
NUMERIC
date
Example
Maths
TexT
Computer
Me and u
DECIMAL(p,s)
Number(p,s) 17.32
345
INT
INT
INT(5)
DATE
YYYY-MMDD
2009-07-02
SQL Commands
SQL commands can be classified into the following:
Data Definition Language (DDL): A database scheme is defined by set of
definitions, which are expressed, by a special set of commands called Data
Definition Language (DDL). They are used to create tables, databases, identify
data items, provide unique names to the data items and to define the length and
provide the range of values that each data item can assume. They are CREATE
TABLE, ALTER TABLE and DROP TABLE commands.
10
Data Manipulation Language (DML): The data manipulation language (DML) handles
operations such as entering rows into a table, changing data, deleting rows, and
MySQL - 10
extracting data from rows and tables. With DML, one does not change the table's
structure, but rather its contents. It contains commands like INSERT, UPDATE and
DELETE.
Data Control Language (DCL): This allows definition of a security mechanisms for
protecting data from unauthorized access. It contains commands like GRANT and
REVOKE.
CREATE TABLE
Tables are defined with the CREATE TABLE command. When tables are created its
columns are named, data types and sizes supplied for each column. At least one
column must be specified.
Syntax:
CREATE TABLE <table-name> (< column name><data type> [
<size>], (< column name><data type> [ <size>], );
Example:
mysql> USE school_db;
Database changed
mysql> CREATE TABLE Student(
Rollno decimal(3,0),
Name varchar(15),
Gender char(1),
Marks1 int);
Query OK, 0 rows affected (0.16 sec)
DESCRIBE
The describe statement can be used to see the structure of the table as indicated
in the Create Command,
mysql> DESCRIBE Student;
+--------+------------------+------+-----+---------+---------------+
| Field | Type
| Null | Key |Default | Extra
|
+--------+------------------+------+-----+---------+---------------+
| rollno | decimal(3,0)
|
|
|
|
|
| name
| varchar(15)
|
|
|
|
|
| gender | char(1)
|
|
|
|
|
| marks1 | int
|
|
|
|
|
+--------+------------------+------+-----+---------+---------------+
4 rows in set (0.00 sec)
ALTER Command
The ALTER statement can add, remove or change table's column(s).
Syntax:
ALTER TABLE <table_name>
Example:
mysql> ALTER TABLE student ADD games
VARCHAR(5);
MySQL - 11
MYSQL
After this command the games column will be added and a null value will be
assigned for all the rows in this column.
mysql> SELECT * from student;
+-----------+---------+-----------+-----------+-------+---------+
|
rollno |
name |
Gender |
Marks1 |Grade | games
|
+-----------+---------+-----------+-----------+-------+---------+
| 15001
| Nidhi
|
F
|
60
| C
|
NULL |
| 15002
| John
|
M
|
70
| B
|
NULL |
| 15003
| Mukesh
|
M
|
78
| B
|
NULL |
| 15004
| Priya R |
F
|
68
| C
|
NULL |
| 15005
| Ashish Jr|
M
|
84
| A
|
NULL |
| 15006
|Govindan
|
M
|
52
| D
|
NULL |
| 15007
|Maya
|
F
|
60
| C
|
NULL |
| 15008
|Priya
|
F
|
80
| A
|
NULL |
| 15009
|Radha
|
F
|
55
| D
|
NULL |
| 15010
|Sneha
|
F
|
70
| B
|
NULL |
| 15011
|Ashish
|
M
|
40
| F
|
NULL |
| 15012
|Mukund
|
M
|
55
| D
|
NULL |
| 15013
|Asif
|
M
|
90
| S
|
NULL |
| 15014
|Helen
|
F
|
74
| B
|
NULL |
| 15015
|Goody
|
F
|
87
| S
|
NULL |
+-----------|---------|-----------|-----------|-------|----------+
15 rows in set (0.15 sec)
12
+--------+------------------+------+-----+---------+----------------+
| Field | Type
| Null | Key | Default | Extra
|
+--------+------------------+------+-----+---------+----------------+
| rollno | decimal(3,0)
|
|
|
|
|
| name
| varchar(15)
|
|
|
|
|
| gender | char(1)
|
|
|
|
|
| marks1 | int
|
|
|
|
|
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
MySQL - 12
MYSQL CHAPTER -5
MySQL Select Statement
The SQL SELECT command is used to fetch data from MySQL database. There are
various ways and combinations, a select command can be used into.
Complete Syntax:
SELECT */<Column Name(s)/<Expression(s)>
FROM <Table Name>
[WHERE <Condition>]
[GROUP BY <Grouping Column>]
[HAVING <Grouping Condition>]
[ORDER BY <Column Name(s)>];
Selecting Specific Column
Here is generic SQL syntax of SELECT command to fetch data from MySQL table:
Syntax:
SELECT <column name> FROM <table name>;
mysql> select rollno from student;
+--------------------------+
|
roll no
|
+--------------------------+
|
15001
|
|
15002
|
|
15003
|
|
15004
|
|
15005
|
|
15006
|
|
15007
|
|
15008
|
|
15009
|
|
15010
|
|
15011
|
|
15012
|
|
15013
|
|
15014
|
|
15015
|
+--------------------------+
15 rows in set (0.6 sec)
from student;
+-----------+-----------+
|
rollno |
name
|
+-----------+-----------+
| 15001
| Nidhi
|
| 15002
| John
|
| 15003
| Mukesh
|
| 15004
| Priya R |
| 15005
| Ashish Jr|
| 15006
| Govindan |
| 15007
| Maya
|
| 15008
| Priya
|
| 15009
| Radha
|
MySQL - 13
MYSQL
14
Instead of displaying all the rows certain rows can be displayed based on the
criteria for selection of rows using the keyword WHERE
mysql> SELECT marks1 FROM student WHERE marks1 > 70;
MYSQL
Relational Operators
To compare two values, a relational operator is used. The relational operators are
=, >, <, >=, <=, < >. They are combined with WHERE clause.
Logical Operators
The logical operators OR, AND, NOT are used to connect search conditions in the
WHERE .
mysql> SELECT rollno, name FROM student WHERE marks1 > 50 AND marks1 < 60;
+------+----------+
|rollno|
name
|
MySQL - 16
MySQL - 17
MYSQL
If the name has more than one same value then those rows will be sorted as per
the marks1 in descending order.
18
MySQL - 18
MYSQL CHAPTER-6
Built-in Functions
MySQL supports functions that can be used to manipulate data. Such functions can
be used to manipulate data.
Single-row functions return a single result row for every row of a queried table. They are
categorize into: Numeric functions, String functions, and Date and Time functions.
Numeric Functions: Numeric functions accept numeric input and return numeric values.
Numeric Functions
SNo
1
Name
POWER()
Description
Example
ROUND()
(i) POW(2,4);
Result:16
(ii) POW(2,-2);
Result:0.25
(iii) POW(-2,3)
Result: -8
(i) ROUND(-1.23);
Result: -1
(ii) ROUND(-1.58);
Result: -2
(iii) ROUND(1.58);
Result: 2
(iv) ROUND(3.798, 1);
Result: 3.8
(v) ROUND(1.298, 0);
Result: 1
(vi) ROUND(23.298, -1);
Result: 20
TRUNCATE()
(i) TRUNCATE(7.29,1)
Result: 7.2
(ii) TRUNCATE(27.29,-1)
Result: 20
MySQL - 19
Character Functions
MYSQL
SNo Name
1
LENGTH()
Description
Returns the length of a string
in bytes.
Example
LENGTH(INFORMATICS)
Result:11
CHAR()
CHAR(65)
Result : A
CONCAT()
CONCAT(Informatics, ,
Practices)
Result : Informatics Practices
INSTR()
INSTR(Informatics, mat)
Result : 6
LOWER()
LOWER(INFORMATICS)
Result : informatics
LCASE()
LCASE(INFORMATICS)
Result : informatics
UCASE()
UCASE(informatics)
Result : INFORMATICS
UPPER()
UPPER(informatics)
Result : INFORMATICS
LEFT()
LEFT(INFORMATICS PRACTICES, 3)
Result : INF
10
RIGHT()
RIGHT(INFORMATICS PRACTICES,
3)
Result : CES
11
MID()
MID(INFORMATICS PRACTICES,
3,4)
Result : FORM
12
LTRIM()
13
RTRIM()
14
TRIM()
15
SUBSTR()
LTRIM('
INFORMATICS')
Result: 'INFORMATICS
RTRIM('INFORMATICS
')
Result: 'INFORMATICS
TRIM('
INFORMATICS
')
Result: 'INFORMATICS
SUBSTRING('Informatics
Practices',5)
Result : 'rmatics Practices'
SUBSTRING('Informatics
Practices',5,3)
Result : 'rma'
String functions are used to extract, change, format or alter character strings.
20
MySQL - 20
Name
CURDATE()
Description
Example
CURDATE();
Result: '2009-07-21'
NOW()
NOW();
Result : '2009-07-21
13:58:11'
SYSDATE()
SYSDATE();
Result: '2009-07-21
13:59:23
DATE()
DATE('2003-12-31
01:02:03');
Result:: '2003-12-31'
MONTH()
MONTH('2009-07-21');
Result : 7
YEAR()
YEAR('2009-07-21');
Result : 2009
DAYNAME()
DAYNAME('2009-07-21');
Result : TUESDAY
DAYOFMONTH()
DAYOFWEEK()
10
DAYOFYEAR()
DAYOFMONTH('2009-0721');
Result: 21
DAYOFWEEK('2009-0721');
Result: 3 (Sunday is
counted as 1)
i) DAYOFYEAR('2009-0721');
Result: 202
DAYOFYEAR('2009-01-01');
Result: 1
AGGREGATE FUNCTIONS
COUNT(), SUM(),AVG(), MAX(), MIN()
COUNT(<Column name>) Outputs the number of rows or column values selected
by the query
Example
mysql> USE school_db;
Database changed
mysql> SELECT COUNT(rollno) from Student;
MySQL - 21
MYSQL
COUNT(rollno)
--------------------------------14
The most common usage for this is just to specify an asterisks as the column to
count the number of rows (or in this case rollno).
Example
SELECT COUNT(*) FROM Student WHERE rollno > 15010;
COUNT(rollno)
--------------------------------5
Even though there were two students with marks 70 only one occurrence was
counted.
SUM() - The SUM aggregate function calculates the sum total of values in a column.
The column using sum must be of numeric data type.
mysql> SELECT SUM(marks1) FROM Student;
SUM(marks1)
--------------------------------215
AVG()- The AVG( ) calculates the average or arithmetic mean of the values
mysql> SELECT AVG(marks1) from Student;
AVG(marks1)
--------------------------------483.3
MAX()- The MAX( ) calculates the maximum value of the column data
mysql> SELECT MAX(marks1) from Student;
MAX(marks1)
--------------------------------60
MIN- The MIN( ) calculates the minimum value of the column data
mysql> SELECT MIN(marks1) from Student;
22
MIN(marks1)
---------------------------------
MySQL - 22
COLUMN ALIAS
While displaying the column values after extracting using select queries it might be
preferable for the result to show different headings instead of the column name
included in the table. This can be done by providing an Alias to the column name
(pseudoname). This will not affect the original column headings of the table or
their values. For example if the value of the column to be sorted is based on an
expression, column alias can be used and the same can be used in the ORDER BY
clause.
SELECT Name, Mark1*2 AS Total , grade
FROM Student
WHERE marks1>60
ORDER BY Total desc;
+-----------+---------+-------+
|
Name
| Total | Grade |
+------------+---------+------+
|
Asif
|
180
| S
|
|
Goody
|
174
| S
|
|
Ashish Jr|
168
| A
|
|
Priya
|
160
| A
|
|
Mukesh
|
156
| B
|
|
Helen
|
148
| B
|
|
John
|
140
| B
|
|
Sneha
|
140
| B
|
-----------|---------|---------|
Working with Character Strings and Dates, Working with NULL values
Strings are values such as english, Maximum MARKS. They can use either a
single quote or double quotes to surround a string value. Several escape sequences
are recognized within strings and can be used to indicate special characters.
\0
NULL
\
single quote
\
double quote
\b
backspace
\t
tab
\n
newline
\\
backslash
Quotes can be included within strings.
Examples
I cant
He said, I told you so.
I cant
I can\ t
Date and Time values.
Dates and times are values such as 2009-07-06 or 21:25:43. MySQL also
understands combined date/time values such as 2009-07-06 21: 34:25. By default
it represents year- month-day format.
MySQL - 23
MYSQL
To find records where the count column is or is not NULL, the queries should be
written like this:
mysql> SELECT * FROM tcount_tbl WHERE count IS NULL;
+-----------------+----------------+
| author
|
count |
+-----------------+----------------+
| mahnaz
|
NULL |
| Jen
|
NULL |
+-----------------+----------------+
2 rows in set (0.00 sec)
24
MySQL - 24
MYSQL CHAPTER-7
Grouping
Generating Summaries
One of the most useful things that is done by MySQL is to summarize lots of raw
data. The following query shows how many students are there in the student table.
The GROUP BY clause lets us group the results of a SELECT command before
printing them. It returns single value for a set of rows. It can be applied to all
numeric data types, some char and date data types. Grouping can be done by
column names or aggregate functions.
SELECT COUNT(*), marks1 FROM
The HAVING clause places conditions on groups in contrast to WHERE clause that
places conditions on individual rows. While WHERE conditions cannot include
aggregate functions, HAVING conditions can do so.
SELECT COUNT(*), marks1 FROM
+---------+-------------+
|
marks1 | count)(*) |
+---------+-------------+
|
60
|
2
|
|
70
|
2
|
|
55
|
2
|
+---------+-------------+
3 rows in set (0.05)
MySQL - 25
MYSQL
MYSQL CHAPTER-8
DML Statements
The data manipulation language (DML) handles operations such as entering rows
into a table, changing data, deleting rows, and extracting data from rows and
tables. With DML, one does not change the table's structure, but rather its
contents.
The DML commands are:
DELETE
INSERT
SELECT
UPDATE
The order of values should match the order of columns in the CREATE TABLE
command of the Student table.
Alternate Syntax :
mysql> INSERT INTO student (rollno,name,gender,marks1,grade)
VALUES(15017,Manju,F,80,A);
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0
+--------+---------+--------+-------+-------+
|rollno | name
| gender |marks1 |grade |
+--------+---------+--------+-------+-------+
| 15018 |
|
F
| 25 | A
|
+--------+---------+--------+-------+-------+
1 row in set (0.02 sec)
The default way to store a date in MySQL is with the type DATE. Below is the proper
format of a DATE.
YYYY-MM-DD
While entering a date in a format other than the Year-Month-Day format, it might work,
but it won't be storing them as expected. To insert the current date into the table MySQL's
built-in function CURDATE() can be used in the query. Following are some examples of
inserting date values.
mysql>
mysql>
mysql>
mysql>
mysql>
INSERT
INSERT
INSERT
INSERT
INSERT
INTO
INTO
INTO
INTO
INTO
my_table
my_table
my_table
my_table
my_table
(idate)
(idate)
(idate)
(idate)
(idate)
VALUES
VALUES
VALUES
VALUES
VALUES
(19970505);
('97-05-05');
('1997.05.05');
('1997 05 05');
('0000-00-00');
DELETE COMMAND
This is used to delete rows from a table. This removes the entire rows, not the
individual column values.
Syntax:
mysql> DELETE FROM < tablename> [ Where < condn>];
Query OK. 1 row affected
mysql > Select * from student where rollno = 15018;
+--------+---------+--------+-------+-------+
|rollno | name
| gender |marks1 |grade |
+--------+---------+--------+-------+-------+
|
|
|
|
|
|
+--------+---------+--------+-------+-------+
MYSQL
+--------+---------+--------+-------+-------+
|rollno | name
| gender |marks1 |grade |
+--------+---------+--------+-------+-------+
|
|
|
|
|
|
+--------+---------+--------+-------+-------+
0 row in set (0.01 sec)
UPDATE COMMAND
There may be a requirement where existing data in a MySQL table need to be
modified. UPDATE command can help in the same. This will modify any column
value of any MySQL table.
Syntax:
UPDATE <table_name>
SET <column name> = <value>, [ <column name> = <value>, ]
[WHERE <condn>];
The command can be used to update one or more column all together. WHERE
clause helps in updation of selected rows in a table.
Example:
mysql> UPDATE Student SET name = Manjula where rollno = 15017;
If the condition satisfies the column values of more than one row of the tables then
all those rows will be affected.
mysql> UPDATE Student SET grade = E
Query OK , 1 row affected (0.8 sec)
28
+-----------+---------+-----------+-----------+-------+
|
rollno |
name |
Gender |
Marks1 |Grade |
+-----------+---------+-----------+-----------+-------+
| 15001
| Nidhi
|
F
|
60
| C
|
| 15002
| John
|
M
|
70
| B
|
| 15003
| Mukesh
|
M
|
78
| B
|
| 15004
| Priya R |
F
|
68
| C
|
| 15005
| Ashish Jr|
M
|
84
| A
|
| 15006
|Govindan |
M
|
52
| E
|
| 15007
|Maya
|
F
|
60
| C
|
| 15008
|Priya
|
F
|
80
| A
|
| 15009
|Radha
|
F
|
55
| D
|
| 15010
|Sneha
|
F
|
70
| B
|
| 15011
|Ashish
|
M
|
40
| F
|
| 15012
|Mukund
|
M
|
55
| D
|
| 15013
|Asif
|
M
|
90
| S
|
| 15014
|Helen
|
F
|
74
| B
|
| 15015
|Goody
|
F
|
87
| S
|
+-----------|---------|-----------|-----------|-------|
MySQL - 28
MYSQL CHAPTER-9
Working with Two Tables
Thus far only data from one table had been retrieved at a time. This is fine for
simple takes, but in most real world MySQL usage often there is a need to get data
from multiple tables in a single query. Multiple tables can be used in a single SQL
query. The act of joining in MySQL refers to smashing two or more tables into a
single table.
JOINS can be used in SELECT, UPDATE and DELETE statements to join MySQL tables.
Lets see an example of LEFT JOIN also which is different from simple MySQL JOIN.
Suppose we have two tables Student and Activity in School_db. A complete listing
is given below:
Example:
Try out following examples:
mysql> use School_db;
Database changed
mysql> SELECT * from student;
+-----------+---------+-----------+-----------+-------+
|
rollno |
name |
Gender |
Marks1 |Grade |
+-----------+---------+-----------+-----------+-------+
| 15001
| Nidhi
|
F
|
60
| C
|
| 15002
| John
|
M
|
70
| B
|
| 15003
| Mukesh
|
M
|
78
| B
|
| 15004
| Priya R |
F
|
68
| C
|
| 15005
| Ashish Jr|
M
|
84
| A
|
| 15006
|Govindan |
M
|
52
| D
|
| 15007
|Maya
|
F
|
60
| C
|
| 15008
|Priya
|
F
|
80
| A
|
| 15009
|Radha
|
F
|
55
| D
|
| 15010
|Sneha
|
F
|
70
| B
|
| 15011
|Ashish
|
M
|
40
| F
|
| 15012
|Mukund
|
M
|
55
| D
|
| 15013
|Asif
|
M
|
90
| S
|
| 15014
|Helen
|
F
|
74
| B
|
| 15015
|Goody
|
F
|
87
| S
|
+-----------|---------|----------|-----------|-------|
15 rows in set (0.15 sec)
mysql> SELECT * from Activity;
+----- --+------- --|
| Gender | activity |
+--------+-- -------+
|
M
| cricket |
|
F
| hockey |
+--------+----------+
2 rows in set (0.00 sec)
mysql>
Now a MySQL query can be written to join these two tables. This query will select
all the students from table student and will pickup corresponding activity from
Activity table.
mysql> SELECT a.rollno, a.name, b.activity FROM Student a,
Activity b WHERE a.gender = b.gender;
MySQL - 29
MYSQL
+-----------+-----------+--------------+
|
rollno |
name
| activity
+
+-----------+-----------+--------------+
| 15001
| Nidhi
| hockey
|
| 15002
| John
| cricket
|
| 15003
| Mukesh
| cricket
|
| 15004
| Priya R | hockey
|
| 15005
| Ashish Jr| cricket
|
| 15006
| Govindan | cricket
|
| 15007
| Maya
| hockey
|
| 15008
| Priya
| hockey
|
| 15009
| Radha
| hockey
|
| 15010
| Sneha
| hockey
|
| 15011
| Ashish
| cricket
|
| 15012
| Mukund
| cricket
|
| 15013
| Asif
| cricket
|
| 15014
| Helen
| hockey
|
| 15015
| Goody
| hockey
|
+-----------|-----------+--------------|
A MySQL cross join returns all the rows from both the tables. Consider one more table called Sports
, Hours of the Student_db;
MySQL - 30
MySQL - 31
MYSQL
MYSQL CHAPTER-10
Drop Table
To remove all entries from the table the DELETE statement can issued without any
conditions.
DELETE from activity;
Query OK, 0 rows affected (0.00 sec)
However, this does not delete the table. The table still remains, which can be
checked with SHOW TABLES;
mysql> SHOW TABLES;
+---------------------+
| Tables in school_db |
+---------------------+
| student
|
| sports
|
| activity
|
+---------------------+
3 rows in set (0.00 sec)
32
MySQL - 32
MYSQL CHAPTER-11
Concept of Transactions
In the SQL world, the term "transaction" refers to a series of SQL statements which
are treated as a single unit by the RDBMS. Typically, a transaction is used to group
together SQL statements which are interdependent on each other; a failure in even
one of them is considered a failure of the group as a whole. Thus, a transaction is
said to be successful only if *all* the individual statements within it are executed
successfully.
Any RDBMS, which supports transaction must conform to the so-called "ACID rules",
which specify the fundamental principles for truly secure transactions.
The START TRANSACTION or BEGIN statement begins a new transaction. COMMIT
commits the current transaction, making its changes permanent. ROLLBACK rolls
back the current transaction, canceling its changes.
Let's create a sample table, and see how transactions work:
mysql> CREATE TABLE t (f INT);
mysql> ROLLBACK;
Query OK, 0 rows affected (0.01 sec)
Without a COMMIT statement, the insert was not permanent, and was reversed
with the ROLLBACK. Note that the added record was visible during the transaction
from the same connection that added it.
MySQL - 33
MYSQL
Appendix A
In this section, two methods for making backups of MySQL data and database
structures are discussed, namely mysqldump and mysqlhotcopy.
mysqldump
The utility mysqldump provides a rather convenient way to dump existing data and
table structures. Note that while mysqldump is not the most efficient method for
creating backups (mysqlhotcopy is, described next), it does offer a convenient
method for copying data and table structures which could then be used to
repopulate another SQL server, that server not even necessarily being MySQL.
The function mysqldump can be used to backup all databases, several databases,
one database, or just certain tables within a given database.
Using mysqldump to backup just one database:
%>mysqldump [options] db_name
mysqlhotcopy
The mysqlhotcopy utility is a perl script that uses several basic system and SQL
commands to backup a database. More specifically, it will lock the tables, flush the
tables, make a copy, and unlock the tables. Although it is the fastest method
available for backing up a MySQL database, it is limited to backing up only those
databases residing on the same machine as where it is executed.
The function mysqlhotcopy can be executed to backup one database, a number of
databases, or only those databases matching a name specified by a regular
expression. In this section, the syntax involved with each scenario is provided,
followed with a few examples.
Using mysqlhotcopy to backup just one database:
%>mysqlhotcopy [options] db_name /path/to/new_directory
34
MySQL - 34