0% found this document useful (0 votes)
25 views8 pages

Mysql

The document provides an overview of MySQL, a relational database management system, including its commands for user creation, data types, constraints, storage engines, SQL queries, and views. It details how to manage databases and tables, including creating, altering, and deleting them, as well as using foreign keys and different storage engines like InnoDB and MyISAM. Additionally, it covers transaction properties and examples of SQL queries for data retrieval and manipulation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views8 pages

Mysql

The document provides an overview of MySQL, a relational database management system, including its commands for user creation, data types, constraints, storage engines, SQL queries, and views. It details how to manage databases and tables, including creating, altering, and deleting them, as well as using foreign keys and different storage engines like InnoDB and MyISAM. Additionally, it covers transaction properties and examples of SQL queries for data retrieval and manipulation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

MYSQL

CONTENTS

1. Introduction 139

2. Constraints 141

3. SQL Queries 143

4. Views 145
An ISO 9001 : 2000 Recognised Institution

INTRODUCTION TO MYSQL
MySql is a relational database management system (RDBMS) developed by MySql AB later purchased by sun
micro systems. mysql is client and mysqld is server.
To connect to database (mysql -h host_name -p -u user_name)
>mysql –p –u root (note: no semicolon at end of the statement);
Create user and give permissions
mysql> create user ‘username’@’localhost’ identified by ‘password’;
mysql > grant all on databasename.* to ‘username’@’localhost’;
To set password
mysql> SET PASSWORD FOR root@localhost=PASSWORD(‘root’);
To display time ,user and version
mysql> select now(),user(),version();
To execute sql script files
> mysql -p -u username databasename< myscript.sql
To use the database
mysql> use databasename;
To display the tables in database
mysql>show tables ;
To display table structure
mysql>describe tablename;

Set the options files


create c:\my.ini file with following lines
[client]
host = localhost
user = testuser
password = testuser

DATA TYPES
Numeric data types
Type Name Meaning
TINYINT A very small integer
SMALLINT A small integer
MEDIUMINT A medium-sized integer
INT A standard integer
BIGINT A large integer
DECIMAL A fixed-point number
FLOAT A single-precision floating-point number
DOUBLE A double-precision floating-point number

MySQL 139
An ISO 9001 : 2000 Recognised Institution

String data types


Type Name Meaning
CHAR A fixed-length non-binary (character) string
VARCHAR A variable-length non-binary string
BINARY A fixed-length binary string
VARBINARY A variable-length binary string
TINYBLOB A very small BLOB (binary large object)
BLOB A small BLOB
MEDIUMBLOB A medium-sized BLOB
LONGBLOB A large BLOB
TINYTEXT A very small non-binary string
TEXT A small non-binary string
MEDIUMTEXT A medium-sized non-binary string
LONGTEXT A large non-binary string
ENUM An enumeration; each column value may be assigned one enumeration member
SET A set; each column value may be assigned zero or more set Members

Date and Time data types


Type Name Meaning
DATE A date value, in ‘CCYY-MM-DD’ format
TIME A time value, in ‘hh:mm:ss’ format
DATETIME A date and time value, in ‘CCYY-MM-DD hh:mm:ss’ format
TIMESTAMP A timestamp value, in ‘CCYY-MM-DD hh:mm:ss’ format
YEAR A year value, in CCYY or YY format

MySQL 140
An ISO 9001 : 2000 Recognised Institution

CONSTRAINTS
Foreign keys
[CONSTRAINT constraint_name]
FOREIGN KEY [fk_name] (index_columns)
REFERENCES tbl_name (index_columns)
[ON DELETE action]
[ON UPDATE action]

FOREIGN KEY indicates the indexed columns in the child table that must match index values in the parent
table.fk_name is the foreign key ID
REFERENCES names the parent table and the index columns in that table to which the foreign key in the child
table refers.The index_columns part of the REFERENCES clause must have the same number of columns as
the index_columns that follows the FOREIGN KEY keywords
ON DELETE CASCADE causes matching child rows to be deleted when the corresponding parent row is deleted.
In essence, the effect of the delete is cascaded from the parent to the child.This enables you to perform multipletable
deletes by deleting rows only from the parent table and letting InnoDB take care of deleting corresponding rows
from the child table.
Corresponding columns in the parent and child indexes must have compatible types. For example, you cannot
match an INT column with a CHAR column.
Example:
CREATE TABLE parent
(
par_id INT NOT NULL,
PRIMARY KEY (par_id)
) ENGINE = INNODB;

CREATE TABLE child


(par_id INT NOT NULL,
child_id INT NOT NULL,
PRIMARY KEY (par_id, child_id),
FOREIGN KEY (par_id) REFERENCES parent (par_id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE = INNODB;

mysql> INSERT INTO parent (par_id) VALUES(1),(2),(3);


mysql> INSERT INTO child (par_id,child_id) VALUES(1,1),(1,2);
mysql> INSERT INTO child (par_id,child_id) VALUES(2,1),(2,2),(2,3);
mysql> INSERT INTO child (par_id,child_id) VALUES(3,1)

MySQL 141
An ISO 9001 : 2000 Recognised Institution

MYSQL STORAGE ENGINES


Storage Engine Description
ARCHIVE Archival storage (no modification of rows after insertion)
BLACKHOLE Engine that discards writes and returns empty reads
CSV Storage in comma-separated values format
EXAMPLE Example (“stub”) storage engine
Falcon Transactional engine (mysql 6.0)
FEDERATED Engine for accessing remote tables
InnoDB Transactional engine with foreign keys
MEMORY In-memory tables
MERGE Manages collections of MyISAM tables
MyISAM The default storage engine
NDB The engine for MySQL Cluster

The InnoDB Storage Engine


Transaction-safe tables with commit and rollback. Savepoints can be created to enable partial rollback.
· Automatic recovery after a crash.
· Foreign key and referential integrity support, including cascaded delete and update.

The MyISAM Storage Engine


The MyISAM storage engine is the default engine in MySQL, unless you have configured your server otherwise.The
following list describes some of its features:
· MyISAM supports full-text searching through the use of FULLTEXT indexes.
· Mysql > show engines/G lists available engines

MySQL 142
An ISO 9001 : 2000 Recognised Institution

SQL QUERIES
Create database Create database if not exists db_name;
If not exists used to check the whether database already exists .
Drop database Drop database db_name;
Create table Create table table_name ;
Drop table Drop table table_name;
Alter table Alter table tbl_name action [, action] ...
Ex: alter table mytbl modify id int;
Ex: alter table mytbl change id id2 int; (change modifies the column name also);

ALTER TABLE tbl_name RENAME TO new_tbl_name;


RENAME TABLE old_name TO new_name;(to rename multiple columns);
alter table emp add constraint pk_empno primary key(empno);
alter table emp engine=innodb;

SELECT STATEMENT
SELECT select_list # What columns to select
FROM table_list # The tables from which to select rows
WHERE row_constraint # What conditions rows must satisfy
GROUP BY grouping_columns # How to group results
ORDER BY sorting_columns # How to sort results
HAVING group_constraint # What conditions groups must satisfy
LIMIT count; # Row count limit on results

LEFT AND RIGHT (OUTER) JOINS


An inner join shows only rows where a match can be found in both tables. Outer joins show matches, too, but
can also show rows in one table that have no match in the other table.Two kinds of outer joins are left and right
joins. Most of the examples in this section use LEFT JOIN, which identifies rows in the left table that are not
matched by the right table. RIGHT JOIN is the same except that the roles of the tables are reversed.
A LEFT JOIN works like this: You specify the columns to be used for matching rows in the two tables.When a row
from the left table matches a row from the right table, the contents of the rows are selected as an output
row.When a row in the left table has no match, it is still selected for output, but joined with a “fake” row from the
right table that contains NULL in all the columns.
In other words, a LEFT JOIN forces the result set to contain a row for every row selected from the left table,
whether or not there is a match for it in the right table.The left table rows with no match can be identified by the
fact that all columns from the right table are NULL.These result rows tell you which rows are missing from the
right table.That is an interesting and important property, because this kind of problem comes up in many different
contexts.Which customers have not been assigned an account representative? For which inventory items have
no sales been recorded?

MySQL 143
An ISO 9001 : 2000 Recognised Institution

QUERIES USING SAMPLE DATABASE


Which students have no score for a given grade event, and to do this for each grade event. Another way to say
this is that we want to find out which combinations of student and grade event are not present in the score table
SELECT student.name, student.student_id, grade_event.date, grade_event.event_id, grade_event.category
FROM student
INNER JOIN grade_event
LEFT JOIN score ON student.student_id = score.student_id
AND grade_event.event_id = score.event_id
WHERE score.score IS NULL
ORDER BY student.student_id, grade_event.event_id;

Select IDs for grade event rows that correspond to tests (‘T’)
SELECT * FROM score
WHERE event_id IN (SELECT event_id FROM grade_event WHERE category = ‘T’);

Which of the presidents in the president table was born first


SELECT * FROM president
WHERE birth = (SELECT MIN(birth) FROM president);

The presidents who were born in the same city and state as John Adams:
mysql> SELECT last_name, first_name, city, state FROM president
WHERE (city, state) = (SELECT city, state FROM president
WHERE last_name = ‘Adams’ AND first_name = ‘John’);
Students who are absent
SELECT * FROM student
WHERE student_id IN (SELECT student_id FROM absence);

Students with perfect attendance


SELECT * FROM student
WHERE student_id NOT IN (SELECT student_id FROM absence);

There is a pattern here. The subquery statements follow this form:


SELECT * FROM table1
WHERE column1 IN (SELECT column2a FROM table2 WHERE column2b = value);
Such queries can be converted to a join using this form:
SELECT table1.* FROM table1 INNER JOIN table2
ON table1.column1 = table2.column2a WHERE table2.column2b = value;

MySQL 144
An ISO 9001 : 2000 Recognised Institution

VIEWS

Create View
CREATE VIEW vpres AS
SELECT last_name, first_name, city, state FROM president;

Delete data delete from table_name where <condition>

Transactional systems typically are characterized as providing ACID properties. ACID is an acronym for Atomic,
Consistent, Isolated, and Durable, referring to four properties that transactions should have:
Atomicity: The statements a transaction consists of form a logical unit.You can’t have just some of them
execute.
Consistency: The database is consistent before and after the transaction executes. In other words, the
transaction doesn’t make a mess of your database.
Isolation: One transaction has no effect on another.
Durability: When a transaction executes successfully to completion, its effects are recorded permanently in
the database.

Transaction example: set autocommit=off;

CREATE TABLE t (name CHAR(20), UNIQUE (name)) ENGINE = InnoDB;


mysql> START TRANSACTION;
mysql> INSERT INTO t SET name = ‘William’;
mysql> INSERT INTO t SET name = ‘Wallace’;
mysql> COMMIT;
mysql> SELECT * FROM t;

mysql> START TRANSACTION;


mysql> INSERT INTO t SET name = ‘Gromit’;
mysql> INSERT INTO t SET name = ‘Wallace’;
ERROR 1062 (23000): Duplicate entry ‘Wallace’ for key 1
mysql> ROLLBACK;
mysql> SELECT * FROM t;

MySQL 145

You might also like