MySQL Theory and Practice

MySQL Theory and Practice

On ubuntu, mysql hsa its data under /var/lib/mysql.
MySQL Storage Engines
The various storage engines are provided to meet different requirements.
MyISAM is the default storage engine.
MySQL 5.4 supported storage engines: MyISAM, InnoDB, Memory, Merge, Archive, CSV, Federated, Blackhole, Example.
MyISAM
It is the default storage engine and the one that is used the most.
It doesn’t support transaction, row-level locking, nor foreign key.
InnoDB
A transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.
It supports transaction, row-level locking, and foreign key.
Compared with MyISAM, InnoDB is safer, provides better concurrency for tables that get many updates concurrently with reads.
CSV
The CSV storage engine stores data in text files using comma-separated values format.
They exist to allow MySQL to easily exchange data with other applications that make use of CSV files, such as spreadsheets.
They make no use of any sort of indexing and SELECT is not at all efficient, and performs a complete table scan.
Archive
It allows storing large amounts of data without taking up too much space.
It's perfect for storing and retrieving large amounts of seldom-referenced historical, archived, or security audit information.
Memory — Stores all data in RAM for extremely fast access in environments that require quick lookups of reference and other like data
Merge — Allows a MySQL DBA or developer to logically group a series of identical MyISAM tables and reference them as one object. Good for VLDB environments such as data warehousing.
Federated — Offers the ability to link separate MySQL servers to create one logical database from many physical servers. Very good for distributed or data mart environments.
Blackhole — The Blackhole storage engine accepts but does not store data and retrievals always return an empty set. The functionality can be used in distributed database design where data is automatically replicated, but not stored locally.
Example — The Example storage engine is "stub" engine that does nothing. You can create tables with this engine, but no data can be stored in them or retrieved from them. The purpose of this engine is to serve as an example in the MySQL source code that illustrates how to begin writing new storage engines. As such, it is primarily of interest to developers.
Comparing Transaction and Nontransaction Engines

Transaction-safe tables (TSTs) have several advantages over nontransaction-safe tables (NTSTs):
They are safer. Even if MySQL crashes or you get hardware problems, you can get your data back, either by automatic recovery or from a backup plus the transaction log.
It supports atomic operation, you can combine many statements and commit them, all operations are all carried out, or none at all.
Transaction-safe storage engines can provide better concurrency for tables that get many updates concurrently with reads.
Nontransaction-safe tables have several advantages of their own, all of which occur because there is no transaction overhead:
Much faster
Lower disk space requirements
Less memory required to perform updates
Practices
SET storage_engine=MYISAM; //set the default storage engine
CREATE TABLE t (i INT) ENGINE = INNODB;
CREATE TABLE archive_names(firstname CHAR(30), surname CHAR(40), age INT) ENGINE = ARCHIVE;
ALTER TABLE t ENGINE = MYISAM; 
Show engines;
Transaction Isolation Levels
The default isolation level for InnoDB is REPEATABLE READ.
READ UNCOMMITTED
Barely transactional, this setting allows for so-called 'dirty reads', where queries inside one transaction are affected by uncommitted changes in another transaction.
READ COMMITTED
Committed updates are visible within another transaction. This means identical queries within a transaction can return differing results. This is the default in some DBMS's.
REPEATABLE READ
This is the default isolation level for InnoDB tables. Within a transaction, all reads are consistent.
SERIALIZABLE
Updates are not permitted in other transactions if a transaction has run an ordinary SELECT query, i.e. queries are treated as if they had a LOCK IN SHARE MODE.

The default isolation level for SQL SERVER and Oracle is READ COMMITTED.
The default isolation level for SQL DB2, MySQL and PostgreSQL is READ COMMITTED.
Enable/Dsiable Automatic Commits
SET AUTOCOMMIT=1|0;
Read locks for Updating
Use this when we would want to read a record in order to update it, knowing that we are not conflicting with any other connection that is doing the same thing.
SELECT MAX(f) FROM t FOR UPDATE;
Updates or read for updating operations in other transaction wait until the active transaction is complete.
Read locks for sharing - LOCK IN SHARE MODE
It will stop any updates or deletes of the row being read, and if the latest data is still uncommitted, will wait until that transaction is committed before returning any results.
SELECT MAX(f) FROM t LOCK IN SHARE MODE;
SET GLOBAL TRANSACTION ISOLATION LEVEL READ COMMITTED|(READ UNCOMMITTED);   
SELECT @@tx_isolation;
Use EXPLAIN to check query execution plan in MySQL and optimize Queries
EXPLAIN tbl_name // synonymous with DESCRIBE tbl_name or SHOW COLUMNS FROM tbl_name.
EXPLAIN select * from t; // check query execution plan
MySQL Administration
mysqld &
mysql [-h hostname] -u username -p'password'
mysqladmin -u root -p'password' status|shutdown|password new-password
show databases;
use ${database_name}
show tables;
describe|desc ${table_name}
Display the CREATE TABLE statement
SHOW CREATE TABLE Country\G;
Display detailed information about the indexes
SHOW INDEX FROM Country\G;
SQL Example
Creating a MySQL Database
create database bank;
mysql -u root -p
Create the lrngsql database user with full privileges on the bank database
grant all privileges on bank.* to 'lrngsql'@'localhost' identified by 'xyz';
mysql -u lrngsql -p;
use bank;
mysql -u lrngsql -p bank[database name]

INSERT INTO t (id, name) VALUES(1,'Bea'),(2,'Belle'),(3,'Bernice');
SELECT
COUNT(*) AS 'Total Rows',
COUNT(DISTINCT name) AS 'Distinct Values',
COUNT(*) - COUNT(DISTINCT name) AS 'Duplicate Values' FROM t;
Show the Current Transaction Mode
SELECT @@AUTOCOMMIT FROM DUAL;
SET AUTOCOMMIT = 0;
SELECT @@session.tx_isolation FROM DUAL;
Get data in XML format
mysql -u lrngsql -p --xml bank
SELECT now();
SELECT now() FROM dual;
Metadata
SHOW TABLES;
DESC|describle customer;
SHOW TABLE STATUS LIKE 'transaction' \G
MySQL Data Types
Character Data
char(20)    /* fixed-length */
varchar(20) /* variable-length */
Character sets
varchar(20) character set utf8
Set the default character set for your entire database:
create database foreign_sales character set utf8;
Text data
Tinytext[255],Text [65,535],Mediumtext [16,777,215],Longtext [4,294,967,295]
Numeric data
Tinyint,Smallint,Mediumint,Int,Bigint, Float(p,s),Double(p,s)
Temporal Data
Date,Datetime,Timestamp,Year,Time

Resources:
Post a Comment

Labels

Java (159) Lucene-Solr (110) Interview (61) All (58) J2SE (53) Algorithm (45) Soft Skills (36) Eclipse (34) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Nutch2 (18) Tools (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Troubleshooting (11) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Http Client (8) Maven (8) Problem Solving (8) Security (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) Dynamic Languages (5) IDE (5) Lesson Learned (5) Programmer Skills (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Spark (4) System Design (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) How to Interview (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Python (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts