mysql. 1 what is mysql used for. *this is a guide that was created from lecture videos and is used to help you gain an understanding of what is mysql used for. MySQL Installation MySQL is an open source database management system. MySQL is owned by Oracle. MySQL uses a client server model and the database runs on a server. MySQL installation can be challenging as it is on a headless server, which is a server without a screen or keyboard and is typically managed remotely. XAMPP is a cross platform package that includes MySQL, Apache and PHP. Install XAMPP on Windows Ensure there are no web servers running -> Install a text editor such as notepad ++ -> download XAMPP -> find the XAMPP control panel xampp-control.exe -> pin this file to your taskbar for easy access -> go into XAMPP control panel and turn on Apache and MySQL -> type localhost in your browser to see XAMPP -> go into phpmyadmin to ensure MySQL is running Install XAMPP on Mac Go into System Preferences: Sharing to uncheck Web Sharing (if it is there) -> install a text editor such as TextWrangler -> download and install XAMPP -> go into Applications and choose XAMPP to drag to your dock -> type in localhost in browser Setup MySQL Users on a Mac Go into XAMPP on browser from localhost -> phpmyadmin -> Users -> create a password for
mysql. 2 the root user -> go into Applications: XAMPP: xamppfiles: phpmyadmin: config.inc.php -> right click and select Get Info for config.php -> add a User and password -> Open the config.inc.php file in a text editor and change the root password under [ password ] = Import databases into MYSQL using phpmyadmin- phpmyadmin -> Import File -> select mysql database to import MySQL Select Statement SELECT statement- SELECT * FROM Album; this is a comment /* this is a multi-line comment */ SELECT * FROM Album WHERE Label = Columbia ; From and Where are clauses SELECT COUNT(*) FROM Album WHERE Label = Columbia ; Count is an example function SELECT Name, Population / 1000000 AS PopMM FROM Country WHERE Population >= 1000000 ORDER BY Population DESC; Population / 1000000 and Population >= 1000000 are expressions SELECT is used to display the result of any query.
mysql. 3 SELECT * FROM Country ORDER BY Name; this code will select all rows from the Country table and order them by the Name column. Instead of using the * to select all columns, you can enter in to select specific columns. You can use AS to rename a column as an alias. You can limit the amount of rows using a LIMIT clause. You can use OFFSET to get rows from a starting point. Selecting columns- SELECT column1 AS C1, column2, column3 FROM Table ORDER BY column2; Sorting results with ORDER BY- SELECT column1 FROM table ORDER BY column1 DESC ORDER BY is used to sort the results of your queries. Filtering results with WHERE- SELECT * FROM table WHERE column2 < 1000000 OR column2 IS NULL ORDER BY column2 DESC; You can also use AND in place of OR. Filtering results with LIKE and IN- the like operator is used to match particular values or patterns in a column SELECT column1, column2, column3, FROM table WHERE column1 LIKE %value% ORDER by column1. The percent sign is a wildcard and will match 0 or more characters in a row. If you want to retrieve the rows where it ends with value then type in %island. LIKE _a will return values that have a as a second character The IN operator is used to select results that match values in a list. SELECT column1, column2, column3 FROM table WHERE column2 IN ( value1, value2 ); Filtering results with regular expressions- Instead of using LIKE, you can use REGXP. SELECT column1, column2, column3 FROM table WHERE column1 REGEXP ^.[a-e].* ORDER BY
mysql. 4 column2; The carrot sign is an anchor for a starting point. The. is referring to the first character, [a-e] is referring to the second character. Refer here to learn about REGEXP: https://dev.mysql.com/doc/refman/8.0/en/regexp.html You may also see RLIKE which was used for MSSQL in legacy systems. It acts the same as REGEXP. MySQL Rows Insert Rows- CREATE TABLE test ( a INT, b TEXT, c TEXT): INSERT INTO test VALUES ( 1, text into b, text into c ); INSERT INTO test ( b, c ) VALUES ( valueb, valuec ) Updating rows- first find the rows you want to update: SELECT * FROM table WHERE column2 = value; -> UPDATE table SET column2 = value to set WHERE column1 = 2; You can set hte value to NULL if necessary. Deleting Rows- DELETE FROM table WHERE column = value; DROP TABLE table; can be used to delete an entire table. Literal strings- use single quotes for literal strings such as SELECT hello, world ; NULL values- NULL distinguishes a result of no value. You can use SELECT * FROM table WHERE column IS NULL // IS NOT NULL MySQL Database Creating a Database
mysql. 5 a database is implemented as a file system directory/folder that has files that represent tables in the database. In a Mac, you will find the database files under Applications: XAMPP: xamppfiles: var: mysql CREATE DATABASE databasename; USE databasename; CREATE TABLE table (a INT, b INT ); INSERT INTO table VALUES ( 1, value ); SELECT * FROM table; DROP DATABASE databasename; Creating a Table a table contains rows and columns for a given set of data. DROP TABLE IF EXISTS test; CREATE TABLE table ( Id INTEGER, name VARCHAR(255), address VARCHAR(255), city VARCHAR(255), state CHAR(2), zip CHAR(10) ); DESCRIBE table; can be used to give you column definitions. You can also use SHOW TABLE STATUS LIKE table ; to see more information regarding a
mysql. 6 table. To see the SQL code used to create a table use SHOW CREATE TABLE test; MySQL Indexes Creating Indexes Indexes are data structures that are used to optimize searches, sequential access and deletions. Use INDEX(column) DROP TABLE IF EXISTS table; CREATE TABLE table ( Id INTEGER, a VARCHAR(255), b VARCHAR(255), INDEX indexname(a, b) ); INSERT INTO TEST ( id, a, b ) VALUES ( 1, one, two ); INSERT INTO TEST ( id, a, b ) VALUES ( 2, two, three ); INSERT INTO TEST ( id, a, b ) VALUES ( 3, three, four ); SELECT * FROM table; DESCRIBE table; SHOW INDEXES FROM table; Define column behaviors using constraints- DROP TABLE IF EXISTS table; CREATE TABLE table (
mysql. 7 A INTEGER NOT NULL DEFAULT 47 (this will place 47 in columns that are not null) B VARCHAR(255) UNIQUE NOT NULL(unique will provide a unique key for a column) ); INSERT INTO TEST ( b ) VALUES ( one ); DESCRIBE table; SELECT * FROM table; MySQL Table Creating an ID Column Primary key will provides an index named primary. There is only one primary key per table. DROP TABLE IF EXISTS table; CREATE TABLE table ( Id INTEGER AUTO_INCREMENT PRIMARY KEY, a VARCHAR(255), b VARCHAR(255) ); INSERT INTO TEST ( a, b ) VALUES ( one, two ); INSERT INTO TEST ( a, b ) VALUES ( two, three ); INSERT INTO TEST ( a, b ) VALUES ( three, four ); SELECT * FROM table; DESCRIBE table; SHOW TABLE STATUS like table ; SHOW CREATE TABLE table; SHOW INDEXES FROM table; You can also use SERIAL instead of INTEGER AUTO_INCREMENT PRIMARY KEY.
mysql. 8 Using foreign key constraints- foreign keys are used as a reference point to have one table refer to another table using a primary key (and the corresponding foreign key) DROP TABLE IF EXISTS lend; DROP TABLE IF EXISTS client; DROP TABLE IF EXISTS book; CREATE TABLE client ( id INT AUTO_INCREMENT PRIMARY KEY, name TEXT ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO client ( name ) VALUES ( Freddy ); INSERT INTO client ( name ) VALUES ( Karen ); INSERT INTO client ( name ) VALUES ( Harry ); SELECT * FROM client; CREATE TABLE book ( id INT AUTO_INCREMENT PRIMARY KEY, title TEXT ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO book ( title ) VALUES ( The Moon is a Harsh Mistress ); INSERT INTO book ( title ) VALUES ( Rendezvous with Rama ); INSERT INTO book ( title ) VALUES ( A Game of Thrones ); SELECT * FROM book; CREATE TABLE lend (
mysql. 9 id INT AUTO_INCREMENT PRIMARY KEY, stamp TIMESTAMP, c_id INT, b_id INT FOREIGN KEY (c_id) REFERENCES client(id) FOREIGN KEY (b_id) REFERENCES book(id) ); INSERT INTO lend ( c_id, b_id ) VALUES ( 1, 1 ); INSERT INTO lend ( c_id, b_id ) VALUES ( 1, 2 ); INSERT INTO lend ( c_id, b_id ) VALUES ( 3, 3 ); INSERT INTO lend ( c_id, b_id ) VALUES ( 2, 5 ); SELECT * FROM lend; Altering a Table CREATE TABLE test ( a VARCHAR(10), b VARCHAR(10), c VARCHAR(10) ); INSERT INTO table VALUES ( one, two, three ); INSERT INTO table VALUES ( two, three, four ); INSERT INTO table VALUES ( three, four, five ); SELECT * FROM table; ALTER TABLE table ADD d VARCHAR(10); ( this will add a column d to table) ALTER Table table DROP d; is used to drop the table ALTER TABLE table ADD d VARCHAR(10) DEFAULT defaultvalue ; MySQL Data Types Numeric types are for representing numerical values. String types are for representing text
mysql. 10 and non-text strings. Date and time types are for representing dates and times. Integer types are various sizes, fixed number of digits and no decimal or fraction. Fixed point types are precise values, fixed decimal point and used for financial applications. Floating point types are approximate values, scales over precision and large or small values. Fixed length character strings are fixed size storage and padded with trailing spaces Variable length character strings are variable length storage, stored with length prefix and trailing spaces are retained. Binary strings are fixed/variable in length, binary sorting/collation and fixed padded with 0x00 BLOB/TEXT are large object storage. BLOB: binary large objects, TEXT: character set/collation Date/Time types are stored as YYYY-MM-DD, can provide timestamps and timezone support ENUM is for single value from list and SET is for several values from list and stored as bitmap The maximum storage per row for MySQL is 65,535. MySQL Numeric types Integer: tinyint, smallint, mediumint, integer, bigint, Fixed point: used for fixed precision values DECIMAL (precision, scale) Floating point: standard IEEE 32-bit floating point number, capable of representing large or small values. REAL is the same as FLOAT type. Float types sacrifice precision for scale. MySQL String Types Character Strings: CHAR(length) for fixed length, VARCHAR (length) for up to a certain length Binary Strings: BINARY(length) works like CHAR, VARBINARY(length) works like VARCHAR Fixed/Variable Length: Large Object Storage: TINYBLOB, TINYTEXT, BLOB, TEXT, MEDIUMBLOB, MEDIUMTEXT,
mysql. 11 LONGBLOB, LONGTEXT MySQL Date and Time Types DATETIME: YEAR-MM-DD HH-MM-SS TIMESTAMP: automatically creates a timestamp on every insert and update Bit type- bit type is designed to conserve as much space as possible DROP TABLE IF EXISTS table; CREATE TABLE table ( Id SERIAL, a BIT(3) b BIT(5) ); Boolean Values DROP TABLE IF EXISTS; CREATE TABLE table ( a BOOL, b BOOL ); INSERT INTO table VALUES ( TRUE, FALSE ); SELECT * FROM table; DESCRIBE table; SHOW CREATE TABLE table; Enumeration Types DROP TABLE IF EXISTS table; CREATE TABLE table ( Id SERIAL, a ENUM( value1, value2, value3 )
mysql. 12 ); INSERT INTO table ( a) VALUES ( value1 ) INSERT INTO table ( a) VALUES ( value2 ) INSERT INTO table ( a) VALUES ( value3 ) SELECT * FROM table; SET works like ENUM except you can have two values within the same row. MySQL Functions String functions- SELECT column1, column2, LENGTH(column3) AS len FROM table WHERE column4 = value ORDER BY len DESC; LENGTH will count the bytes rather than the characters CHAR_LENGTH will count the characters instead of bytes LEFT(column, 3) will get the left 3 characters from the column/ You can use RIGHT or MID also. CONCAT(column1,,, column2) will concatenate the columns together LOCATE( value, columnname) is used to locate a string within another string You can use UPPER and LOWER to change the casing. REVERSE will reverse the value. Numeric Functions DIV MOD / modulus to get a remainder POWER(7, 3) or POW will get you 7 cubed. ABS() is absolute value function SIGN() will return the opposite sign CONV() is used for converting from base to base ROUND() will round a number TRUNCATE() will truncate the digits CEIL() FLOOR() can also be used
mysql. 13 RAND() will provide a random number Date and Time Functions NOW() will give you the current time CURRENT_TIMESTAMP() will give you the current time as well UNIX_TIMESTAMP() will give you a Unix timestamp DAYNAME(NOW()) will give you the current day DAYOFMONTH(NOW()) will give you current month DAYOFWEEK(NOW()); will give you the current day of week DAYOFYEAR(NOW()); will give you the current day of year MONTHNAME(NOW()); will give you the current month name TIME_TO_SEC( 00:30:00 ) will give you current time in seconds SEC_TO_TIME( 00:30:00 ) will give you current seconds in time ADDTIME() 1:00:00, 00:29:45 ) will add time together SUBTIME() 1:00:00, 00:29:45 ) will subtract time together ADDDATE( 2000-01-02, INTERVAL 31 DAY) will add days to calendar date SUBDATE( 2000-01-02, INTERVAL 31 DAY) will subtract days to calendar date Time Zones Ensure time zone support is added to MySQL SHOW VARIABLES LIKE %time_zone% SET time_zone = US/Eastern Formatting Dates SELECT DATE_FORMAT(NOW(), %W, %D of %M, %Y ) You can use %Y-%m-%d %T for a standard date format
mysql. 14 Aggregate Functions SELECT column2, COUNT(column) AS countcolumn FROM table GROUP BY column2 ORDER BY countcolumn DESC You can also use COUNT(DISTINCT column) to count the distinct values in a column SELECT GROUP_CONCAT(column1) FROM table WHERE column2 = value GROUP_CONCAT() is used to group a column and its values SELECT GROUP_CONCAT(DISTINCT column1 ORDER BY column2 SEPARATOR / FROM table SELECT AVG(column1) FROM table WHERE column2 = value. You can also use MIN, MAX, SUM and STD for standard deviation. Flow Control with CASE SELECT CASE WHEN column THEN true ELSE false END AS columnalias CASE WHEN columnb THEN true ELSE false END AS columnaliasb FROM table MySQL Transactions Database Integrity with Transactions CREATE TABLE table1( Id SERIAL, column1 VARCHAR(255), column2 INTEGER NOT NULL ); CREATE TABLE table2( Id SERIAL, column1 VARCHAR(255), column2 INTEGER NOT NULL
mysql. 15 ); INSERT INTO table1 ( column1, column2 ) VALUES ( value, 10 ); INSERT INTO table1 ( column1, column2 ) VALUES ( value, 14 ); INSERT INTO table1 ( column1, column2 ) VALUES ( value, 11 ); START TRANSACTION; INSERT INTO table2 ( column1, column2, column3 ) VALUES ( 1, 5, 500 ); UPDATE table1 SET column2 = ( column2 5 ) WHERE Id = 1; COMMIT; START TRANSACTION; INSERT INTO table1 ( column1, column2 ) VALUES ( value, 24 ); ROLLBACK; Transactions for Performance- START TRANSACTION; INSERT INTO.. INSERT INTO.. INSERT INTO.. INSERT INTO.. COMMIT; Using START TRANSACTION you can drastically improve the query time. MySQL Triggers Updating a Table with a Trigger A trigger is an operation that is performed when a database event occurs. You can use a trigger when you want one table to update when an event occurs on another table.
mysql. 16 CREATE TABLE customercolumn ( id SERIAL, name VARCHAR(255), last_order_id BIGINT ); CREATE TABLE salecolumn ( id SERIAL, item_id BIGINT, VARCHAR(255), customer_id BIGINT, quan INT ); INSERT INTO customercolumn (name) VALUES ( value1 ); INSERT INTO customercolumn (name) VALUES ( value2 ); INSERT INTO customercolumn (name) VALUES ( value3 ); SELECT * FROM customercolumn; CREATE TRIGGER newsaletrigger AFTER INSERT ON salecolumn FOR EACH ROW UPDATE customercolumn SET last_order_id = NEW.id WHERE id = NEW.customer_id INSERT INTO salecolumn ( item_id, customer_id, quan, price ) VALUES (1, 3, 5, 19.5); INSERT INTO salecolumn ( item_id, customer_id, quan, price ) VALUES (2, 3, 5, 15.5); INSERT INTO salecolumn ( item_id, customer_id, quan, price ) VALUES (3, 4, 5, 13.5); SELECT * FROM salecolumn; SELECT * FROM customercolumn; Preventing Automatic Updates with a Trigger DROP TABLE IF EXISTS salecolumn; CREATE TABLE salecolumn ( id SERIAL, item_id BIGINT, quan INT, price DECIMAL(9,2), reconciled INT ); INSERT INTO salecolumn (item_id, customer_id, quan, price, reconciled) VALUES (1, 3, 5, 19.95, 0);
mysql. 17 INSERT INTO salecolumn (item_id, customer_id, quan, price, reconciled) VALUES (2, 2, 3, 14.95, 0); INSERT INTO salecolumn (item_id, customer_id, quan, price, reconciled) VALUES (3, 1, 1, 29.95, 0); SELECT * FROM salecolumn; DELIMITER // CREATE TRIGGER newsaletrigger BEFORE UPDATE ON salecolumn FOR EACH ROW BEGIN IF ( SELECT reconciled FROM salecolum WHERE id = NEW.id ) > 0 THEN SIGNAL SQLSTATE 45000 SET_MESSAGE_TEXT = error: cannot update reconciled row in salescolumn SET x=1; END IF; END DELIMITER // START TRANSACTION; UPDATE salecolumn SET quan + 9 WHERE id = 2; COMMIT; SELECT * FROM salescolumn; Logging transactions with a trigger- DROP TABLE IF EXISTS salecolumn;
mysql. 18 CREATE TABLE salecolumn ( id SERIAL, item_id BIGINT, quan INT, price DECIMAL(9,2), reconciled INT ); CREATE TABLE logcolumn ( id SERIAL, stamp TIMESTAMP, event VARCHAR(255), username VARCHAR(255), tablename VARCHAR(255) table_id BIGINT ); DELIMITER // CREATE TRIGGER stampsalecolumn AFTER INSERT ON salecolumn FOR EACH ROW BEGIN UPDATE customercolumn SET last_order_id = NEW.id WHERE customercolumn.id = NEW.customer_id; INSERT INTO logcolumn (event, username, tablename, able_id) VALUES ( INSERT, TRIGGER, salecolumn, NEW.id); END DELIMITER // INSERT INTO salescolumn (item_id, customer_id price) VALUES (1, 3, 5, 19.95) INSERT INTO salescolumn (item_id, customer_id price) VALUES (2, 2, 3, 13.95) INSERT INTO salescolumn (item_id, customer_id price) VALUES (3, 1, 1, 14.95) SELECT * FROM salescolumn; SELECT * FROM customercolumn; SELECT * FROM logcolumn; MySQL Views Creating a simple subset-
mysql. 19 A subset is a nested select statement. A view is a table created from a select statement and can be used as a data source for another select statement DROP TABLE IF EXISTS table; CREATE TABLE table ( columna VARCHAR(6), columnb VARCHAR(6) ) DEFAULT CHARSET=utf8; INSERT INTO table VALUES ( NY1213, US4567 ); INSERT INTO table VALUES ( AZ1213, FR4567 ); INSERT INTO table VALUES ( CA1213, GB1567 ); SELECT * FROM table; SELECT SUBSTR (table, 1, 2) AS columnstate, SUBSTR(columna, 3) AS scodecolumn, SUBSTR(columnb, 1, 2) AS countrycolumn, SUBSTR(columnb, 3) AS ccodecolumn FROM table; Searching within a Result Set SELECT table1.title AS album, table1.artist, table2.track_number AS seq, table2.title, table2.duration AS secs FROM album as table1 JOIN track AS table2 ON table2.album_id = table1.id WHERE table1.id in ( SELECT DISTINCT album_id FROM table WHERE columnb <= value ); Creating a View You can save a SELECT query as a view. CREATE VIEW viewname AS SELECT column1, column2, column3, column4, column5 DIV 60 AS alias, column5 AS MOD 60
mysql. 20 AS alias2 FROM table; SELECT * FROM viewname (you can then use the view as a table) DIV 60 will make the column in minutes, and MOD 60 will be in seconds. To drop a view use, DROP VIEW viewname; Creating a Joined View CREATE VIEW viewname AS SELECT table1.column1 AS alias1, Table1.column2 AS alias2 Table2.column2 AS alias3, Table2.column3 AS alias4, Table2.column4 DIV 60 AS minutealias, Table2.column4 MOD60 AS secondalias FROM alias3 AS table2 JOIN table1.column6 = table2.column7; SELECT column1, column2, column3, column4, CONCAT_WS( :, minutealias, LPAD(secondalias, 2, 0 )) AS aliasname FROM viewname WHERE column = value ; MySQL Stored Routines A stored routine is a set of SQL statements that are stored on a database server and can be used with a client that has permissions. Stored routines are easy to maintain and traffic is reduced between the client and server as data is being processed on the server. Migration to a different server can be difficult as stored routines can be platform specific.
mysql. 21 Stored procedures can also be difficult to maintain. Stored functions return a value and are used as expressions. You use a create function statement and are only available in scalar context, not aggreagate context. Stored procedures use the call statement and returns a result set or set variables. Stored procedures use the create procedure statement. A procedure is called with the call statement and is used as a complete query. Creating a Stored Function CREATE FUNCTION functionname( seconds INT ) RETURNS VARCHAR(16) DETERMINISTIC RETURN CONCAT_WS( :, seconds DIV 60, LPAD(seconds MOD 60, 2, 0 )); SELECT column1, function(duration) FROM table); Deterministic is the function will always return the same value for the same input. LPAD is a string function that pads the left side of the string Creating a Stored Procedure A stored procedure needs all of its code to be sent to the server at the same time. To do this, change the delimiter from a semicolon to a backslash. DELIMITER // CREATE PROCEDURE procedure_name() BEGIN SELECT * FROM table; END // DELIMITER ;
mysql. 22 CALL procedure_name(); Use DROP PROCEDURE procedure_name; to drop the procedure. CRUD stands for create, read, update and delete and are the four basic functions of any database application. PDO is PHP data objects and is a cross platform database interface for database operations. The PDO interface is object oriented. The interface is built on top of the MySQL C interface. If you would like more information in regards to what is mysql used, for you can visit the official documentation or reach out in the comments. Click to share on Facebook (Opens in new window) Click to share on Twitter (Opens in new window) Click to share on LinkedIn (Opens in new window) Click to share on Reddit (Opens in new window)