Skip to content

Commit 721385b

Browse files
committed
MySQL Tutorials
1 parent 42c2ffe commit 721385b

6 files changed

+378
-0
lines changed

mysql-basics.sql

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
2+
01. Import ".sql" file from command prompt
3+
4+
mysql > SOURCE C://database.sql;
5+
6+
02. MySQL Performance Queries
7+
8+
mysql > OPTIMIZE TABLE table_name;
9+
mysql > SHOW TABLE STATUS; //Displays description of the table
10+
mysql > DESC table_name;
11+
mysql > SHOW VARIABLES;
12+
mysql > SHOW STATUS;
13+
mysql > SHOW GLOBAL STATUS;
14+
mysql > SHOW TABLES FROM INFORMATION_SCHEMA;
15+
mysql > EXPLAIN SELECT * FROM table_name
16+
mysql > SHOW TABLE STATUS FROM database_name;
17+
mysql > SHOW FULL PROCESSLIST; //Shows you which threads are running
18+
mysql > SHOW VARIABLES WHERE Variable_name = 'hostname'; //IP Address of the Mysql Host
19+
20+
03. Indexing
21+
22+
mysql > SHOW INDEX FROM table_name;
23+
mysql > ALTER TABLE `table_name` ADD INDEX(`column_name`);
24+
mysql > DROP INDEX index_name ON tbl_name;
25+
26+
04. Table Related Queries
27+
28+
29+
mysql > SELECT max(RIGHT(`field_name`,4)) FROM `table_name`;
30+
mysql > SELECT UCASE(column_name) FROM table_name; // Converts to upper case
31+
mysql > SELECT * FROM TABLE ORDER BY ABS(VALUE - $MYVALUE) LIMIT 1 //Select nearest value
32+
mysql > SELECT sentence, wordcount(sentence) as "Words" from test;
33+
mysql > SELECT * FROM table_name ORDER BY field_name LIMIT 5 OFFSET 5; //Useful in pagination
34+
mysql > SELECT *, COUNT(field_name) FROM table_name GROUP BY field_name HAVING ( COUNT(field_name) > 1 ) //Find duplicate entries
35+
36+
mysql > ALTER TABLE table_name AUTO_INCREMENT =1
37+
mysql > ALTER TABLE `table_name` DROP PRIMARY KEY
38+
mysql > ALTER TABLE `table_name` ENGINE = InnoDB
39+
mysql > ALTER TABLE table_name CHANGE `id` `id` INT( 11 ) NOT NULL AUTO_INCREMENT
40+
mysql > ALTER TABLE `table_name` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST ;
41+
mysql > ALTER TABLE table_name ADD column_name datatype AFTER column_name
42+
mysql > ALTER TABLE table_name DROP COLUMN column_name
43+
mysql > ALTER TABLE table_name MODIFY column_name datatype
44+
mysql > ALTER TABLE table_name CHANGE oldname newname datatype
45+
46+
mysql > RENAME TABLE `table_name_old` TO `table_name_new`
47+
48+
mysql > UPDATE mytable SET city = REPLACE(city, 'ï', 'i') //Update particular character
49+
mysql > UPDATE swap_test SET x=y, y=@temp where @temp:=x; //Swaping field value
50+
mysql > UPDATE table_name SET field_name1=field_name2; //COPYING
51+
mysql > UPDATE table_name SET field_name = UPPER(field_name)
52+
53+
mysql > TRUNCATE TABLE table_name;
54+
mysql > DROP TABLE table_name;
55+
mysql >
56+
57+
05. Date and time
58+
59+
mysql > SHOW VARIABLE LIKE '%time_zone%';
60+
mysql > SELECT NOW(); //Current timestamp
61+
mysql > SELECT DAYNAME(NOW()); //Current day
62+
mysql > SELECT SUBTIME('1:30:00', '00:15:00'); //Subtract time
63+
mysql > SELECT DATE_FORMAT(NOW(), '%W, %D of %M, %Y'); //Date Format
64+
mysql > SELECT TIMEDIFF('2007-10-05 12:10:18','2007-10-05 16:14:59') AS length;
65+
mysql > SELECT * FROM `table_name` WHERE DATE_FORMAT(field_name, "%Y-%m-%d") = '2010-01-01'"
66+
67+
68+
06. MySQL Miscellaneous Queries
69+
70+
mysql > SELECT uuid(); //Use to generate unique id
71+
mysql > SELECT * FROM `TABLENAME` WHERE `field` REGEXP '^-?[0-9]+$' //Get numeric values
72+
mysql > SELECT CONCAT('w3resource','.','com'); //w3resource.com
73+
mysql > CREATE TABLE table_bit (id SERIAL, a BIT(3), b BIT(8), c BIT(16)); //bit datatype
74+
mysql > CREATE TABLE table_enum (id SERIAL, status ENUM('Active', 'Deactive')); //Enum datatype
75+
mysql > SELECT CHAR_LENGTH(field_name) AS Length FROM `table_name`; //Get the length
76+
mysql > SELECT * FROM `table_name` WHERE LENGTH(field_name) < 10
77+
mysql > INSERT INTO table_name (`col1`, `col2`, `col3`, `...`, `coln`) SELECT `col1`, `col2`, `col3`, `...`, `coln` FROM table_name //Copying the previous rows to the next rows
78+
mysql > SELECT COUNT(DISTINCT column) FROM table;
79+
mysql > SELECT field_name, LEFT(field_name, 3), RIGHT(field_name, 3), MID(field_name, 2, 3) FROM `table_name`;
80+
mysql > SELECT CASE WHEN a THEN 'true' ELSE 'false' END AS boolA, CASE WHEN b THEN 'true' ELSE 'false' END AS boolB FROM table_name; //Flow control with CASE
81+
82+
83+

mysql-engines.sql

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/**
2+
3+
InnoDB: The default storage engine in MySQL 8.0. InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL
4+
that has commit, rollback, and crash-recovery capabilities to protect user data. InnoDB row-level locking
5+
(without escalation to coarser granularity locks) and Oracle-style consistent nonlocking reads increase multi-user
6+
concurrency and performance. InnoDB stores user data in clustered indexes to reduce I/O for common queries based on primary keys.
7+
To maintain data integrity, InnoDB also supports FOREIGN KEY referential-integrity constraints.
8+
9+
MyISAM: These tables have a small footprint. Table-level locking limits the performance in read/write workloads,
10+
so it is often used in read-only or read-mostly workloads in Web and data warehousing configurations.
11+
12+
Memory: Stores all data in RAM, for fast access in environments that require quick lookups of non-critical data. This engine
13+
was formerly known as the HEAP engine. Its use cases are decreasing; InnoDB with its buffer pool memory area provides a
14+
general-purpose and durable way to keep most or all data in memory, and NDBCLUSTER provides fast key-value lookups for huge distributed data sets.
15+
16+
CSV: Its tables are really text files with comma-separated values. CSV tables let you import or dump data in CSV format, to exchange
17+
data with scripts and applications that read and write that same format. Because CSV tables are not indexed, you typically keep
18+
the data in InnoDB tables during normal operation, and only use CSV tables during the import or export stage.
19+
20+
Archive: These compact, unindexed tables are intended for storing and retrieving large amounts of seldom-referenced historical, archived,
21+
or security audit information.
22+
23+
Blackhole: The Blackhole storage engine accepts but does not store data, similar to the Unix /dev/null device. Queries always return an empty
24+
set. These tables can be used in replication configurations where DML statements are sent to slave servers, but the master server does not keep its own copy of the data.
25+
26+
NDB: This clustered database engine is particularly suited for applications that require the highest possible degree
27+
of uptime and availability.
28+
29+
Merge: Enables a MySQL DBA or developer to logically group a series of identical MyISAM tables and reference them as one object.
30+
Good for VLDB environments such as data warehousing.
31+
32+
Federated: Offers the ability to link separate MySQL servers to create one logical database from many physical servers. Very good for
33+
distributed or data mart environments.
34+
35+
Example: This engine serves as an example in the MySQL source code that illustrates how to begin writing new storage engines.
36+
It is primarily of interest to developers. The storage engine is a “stub” that does nothing. You can create tables with this engine, but no data can be stored in them or retrieved from them.
37+
38+
39+
**/
40+
41+
mysql > SHOW ENGINES\G;
42+
43+
//*************************** 1. row ***************************
44+
Engine: PERFORMANCE_SCHEMA
45+
Support: YES
46+
Comment: Performance Schema
47+
Transactions: NO
48+
XA: NO
49+
Savepoints: NO
50+
*************************** 2. row ***************************
51+
Engine: InnoDB
52+
Support: DEFAULT
53+
Comment: Supports transactions, row-level locking, and foreign keys
54+
Transactions: YES
55+
XA: YES
56+
Savepoints: YES
57+
*************************** 3. row ***************************
58+
Engine: MRG_MYISAM
59+
Support: YES
60+
Comment: Collection of identical MyISAM tables
61+
Transactions: NO
62+
XA: NO
63+
Savepoints: NO
64+
*************************** 4. row ***************************
65+
Engine: BLACKHOLE
66+
Support: YES
67+
Comment: /dev/null storage engine (anything you write to it disappears)
68+
Transactions: NO
69+
XA: NO
70+
Savepoints: NO
71+
*************************** 5. row ***************************
72+
Engine: MyISAM
73+
Support: YES
74+
Comment: MyISAM storage engine
75+
Transactions: NO
76+
XA: NO
77+
Savepoints: NO
78+
...
79+
**/

stored-routines.sql

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
2+
/***
3+
A stored routine is a set of SQL statements that are stored on the database server and can be used by any client
4+
with permission to use them. This provides a number of benefits.
5+
6+
1. Database operations are normalized so various applications will operate uniformly, even when written in different
7+
languages and operating on different platforms.
8+
9+
2. Stored routines are easy to maintain, because they're all in one place rather than distributed among different applications.
10+
11+
3. Traffic is reduced between the client and server, because data is processed on the server.
12+
13+
4. security is enhanced by allowing clients to run with reduced permissions while still being able to perform necessary
14+
database operations.
15+
16+
There are also some disadvantages.
17+
18+
1. Migration to a different server platform can be difficult as stored routines tend to use a lot of platform specific
19+
features and codes.
20+
21+
2. stored procedures can be difficult to debug and maintain.
22+
23+
There are two different kinds of stored routines.
24+
25+
a) Stored functions return a value, and are used in the context of an expression.
26+
27+
b) Stored procedures are called separately, using the call statement, and may return result sets or set variables.
28+
29+
***/
30+
31+
32+
33+
---Example - 01 : Stored Functions
34+
35+
DROP FUNCTION IF EXISTS track_len;
36+
37+
CREATE FUNCTION track_len(seconds INT)
38+
RETURNS VARCHAR(16) DETERMINISTIC
39+
RETURN CONCAT_WS(':', seconds DIV 60, LPAD(seconds MOD 60, 2, '0' ));
40+
41+
SELECT title, track_len(duration) FROM track;
42+
43+
SELECT a.artist AS artist,
44+
a.title AS album,
45+
t.title AS track,
46+
t.track_number AS trackno,
47+
track_len(t.duration) AS length
48+
FROM track AS t
49+
JOIN album AS a
50+
ON a.id = t.album_id
51+
ORDER BY artist, album, trackno
52+
;
53+
54+
55+
56+
---Example - 02 : Stored Procedures
57+
58+
DROP PROCEDURE IF EXISTS list_albums;
59+
60+
DELIMITER //
61+
CREATE PROCEDURE list_albums ()
62+
BEGIN
63+
SELECT * FROM album;
64+
END
65+
//
66+
67+
DELIMITER ;
68+
CALL list_albums();
69+
70+
71+
---Example - 03 : Stored Procedures with parameter
72+
73+
DROP PROCEDURE IF EXISTS list_albums;
74+
75+
DELIMITER //
76+
CREATE PROCEDURE list_albums (a VARCHAR(255))
77+
BEGIN
78+
SELECT a.artist AS artist,
79+
a.title AS album,
80+
t.title AS track,
81+
t.track_number AS trackno,
82+
track_len(t.duration) AS length
83+
FROM track AS t
84+
JOIN album AS a
85+
ON a.id = t.album_id
86+
WHERE a.artist LIKE a
87+
ORDER BY artist, album, trackno
88+
;
89+
END //
90+
91+
DELIMITER ;
92+
CALL list_albums('%hendrix%');
93+
94+
95+
---Example - 03 : Drop Stored Procedures & Stored Functions
96+
97+
DROP FUNCTION IF EXISTS track_len;
98+
DROP PROCEDURE IF EXISTS total_duration;

transaction.sql

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
-- Exmaple - 01
2+
3+
CREATE TABLE widgetInventory (
4+
id SERIAL,
5+
description VARCHAR(255),
6+
onhand INTEGER NOT NULL
7+
);
8+
9+
CREATE TABLE widgetSales (
10+
id SERIAL,
11+
inv_id INTEGER,
12+
quan INTEGER,
13+
price INTEGER
14+
);
15+
16+
INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'rock', 25 );
17+
INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'paper', 25 );
18+
INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'scissors', 25 );
19+
20+
21+
START TRANSACTION;
22+
INSERT INTO widgetSales ( inv_id, quan, price ) VALUES ( 1, 5, 500 );
23+
UPDATE widgetInventory SET onhand = ( onhand - 5 ) WHERE id = 1;
24+
COMMIT;
25+
26+
SELECT * FROM widgetInventory;
27+
SELECT * FROM widgetSales;
28+
29+
START TRANSACTION;
30+
INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'toy', 25 );
31+
ROLLBACK;
32+
SELECT * FROM widgetInventory;
33+
SELECT * FROM widgetSales;
34+
35+
36+
---Example - 02 INSERT Query using Transaction
37+
38+
CREATE TABLE test (
39+
id SERIAL,
40+
data VARCHAR(256)
41+
);
42+
43+
-- Insert 1,000 times ...
44+
INSERT INTO test ( data ) VALUES ( 'this is a good sized line of text.' );
45+
46+
47+
--- Insert 1000 times using Transaction
48+
START TRANSACTION;
49+
50+
INSERT INTO test ( data ) VALUES ( 'this is a good sized line of text.' );
51+
COMMIT;

triggers.sql

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
-- Example - 01: Updating a table with a trigger
2+
3+
4+
CREATE TABLE widgetCustomer ( id SERIAL, name VARCHAR(255), last_order_id BIGINT );
5+
CREATE TABLE widgetSale ( id SERIAL, item_id BIGINT, customer_id BIGINT, quan INT, price DECIMAL(9,2) );
6+
7+
INSERT INTO widgetCustomer (name) VALUES ('Bob');
8+
INSERT INTO widgetCustomer (name) VALUES ('Sally');
9+
INSERT INTO widgetCustomer (name) VALUES ('Fred');
10+
11+
SELECT * FROM widgetCustomer;
12+
13+
CREATE TRIGGER newWidgetSale AFTER INSERT ON widgetSale
14+
FOR EACH ROW
15+
UPDATE widgetCustomer SET last_order_id = NEW.id WHERE id = NEW.customer_id
16+
;
17+
18+
INSERT INTO widgetSale (item_id, customer_id, quan, price) VALUES (1, 3, 5, 19.95);
19+
INSERT INTO widgetSale (item_id, customer_id, quan, price) VALUES (2, 2, 3, 14.95);
20+
INSERT INTO widgetSale (item_id, customer_id, quan, price) VALUES (3, 1, 1, 29.95);
21+
SELECT * FROM widgetSale;
22+
SELECT * FROM widgetCustomer;

view.sql

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---Example - 01 : Creating a View
2+
3+
SELECT id, album_id, title, track_number, duration DIV 60 AS m, duration MOD 60 AS s
4+
FROM track;
5+
6+
CREATE VIEW trackView AS
7+
SELECT id, album_id, title, track_number, duration DIV 60 AS m, duration MOD 60 AS s
8+
FROM track;
9+
SELECT * FROM trackView;
10+
11+
12+
13+
---Exmaple - 02 : Joined view
14+
15+
SELECT a.artist AS artist,
16+
a.title AS album,
17+
t.title AS track,
18+
t.track_number AS trackno,
19+
t.duration DIV 60 AS m,
20+
t.duration MOD 60 AS s
21+
FROM track AS t
22+
JOIN album AS a
23+
ON a.id = t.album_id
24+
;
25+
26+
27+
CREATE VIEW joinedAlbum AS
28+
SELECT a.artist AS artist,
29+
a.title AS album,
30+
t.title AS track,
31+
t.track_number AS trackno,
32+
t.duration DIV 60 AS m,
33+
t.duration MOD 60 AS s
34+
FROM track AS t
35+
JOIN album AS a
36+
ON a.id = t.album_id
37+
;
38+
39+
SELECT * FROM joinedAlbum;
40+
SELECT * FROM joinedAlbum WHERE artist = 'Jimi Hendrix';
41+
42+
43+
---Example - 03 : Drop View
44+
45+
DROP VIEW IF EXISTS joinedAlbum;

0 commit comments

Comments
 (0)