MySQL - Riptutorial

Transcription

MySQL#mysql

Table of ContentsAbout1Chapter 1: Getting started with MySQL2Remarks2Versions2Examples3Getting Started3Information Schema Examples7Processlist7Stored Procedure Searching7Chapter 2: ALTER TABLE8Syntax8Remarks8Examples9Changing storage engine; rebuild table; change file per table9ALTER COLUMN OF TABLE9ALTER table add INDEX9Change auto-increment value10Changing the type of a primary key column10Change column definition10Renaming a MySQL database10Swapping the names of two MySQL databases11Renaming a MySQL table12Renaming a column in a MySQL table12Chapter 3: Arithmetic14Remarks14Examples14Arithmetic Operators14BIGINT14DOUBLE15Mathematical Constants15

Pi15Trigonometry (SIN, COS)15Sine15Cosine15Tangent15Arc Cosine (inverse cosine)16Arc Sine (inverse sine)16Arc Tangent (inverse tangent)16Cotangent16Conversion16Rounding (ROUND, FLOOR, CEIL)17Round a decimal number to an integer value17Round up a number17Round down a number17Round a decimal number to a specified number of decimal places.17Raise a number to a power (POW)18Square Root (SQRT)18Random Numbers (RAND)18Generate a random number18Random Number in a range18Absolute Value and Sign (ABS, SIGN)Chapter 4: BackticksExamplesBackticks usageChapter 5: Backup using amples22Creating a backup of a database or table22Specifying username and password23Restoring a backup of a database or table23

mysqldump from a remote server with compression24restore a gzipped mysqldump file without uncompressing24Backup direct to Amazon S3 with compression24Tranferring data from one MySQL server to another24Backup database with stored procedures and functions25Chapter 6: Change PasswordExamples2626Change MySQL root password in Linux26Change MySQL root password in Windows27Process27Chapter 7: Character Sets and ch CHARACTER SET and COLLATION?28Setting character sets on tables and fields29Chapter 8: ClusteringExamplesDisambiguationChapter 9: Comment Mysql30303031Remarks31Examples31Adding comments31Commenting table definitions31Chapter 10: Configuration and tuning33Remarks33Examples33InnoDB performance33Parameter to allow huge data to insert33Increase the string limit for group concat34Minimal InnoDB configuration34Secure MySQL encryption35

Chapter 11: Connecting with UTF-8 Using Various Programming language.36Examples36Python36PHP36Chapter 12: Converting from MyISAM to InnoDBExamples3838Basic conversion38Converting All Tables in one Database38Chapter 13: Create New User39Remarks39Examples39Create a MySQL User39Specify the password39Create new user and grant all priviliges to schema39Renaming user40Chapter 14: Creating databases41Syntax41Parameters41Examples41Create database, users, and grants41MyDatabase43System Databases43Creating and Selecting a Database44Chapter 15: Customize PS1Examples4545Customize the MySQL PS1 with current database45Custom PS1 via MySQL configuration file45Chapter 16: Data TypesExamples4646Implicit / automatic casting46VARCHAR(255) -- or not46INT as AUTO INCREMENT47

Others47Introduction (numeric)48Integer Types48Fixed Point Types48Decimal49Floating Point Types49Bit Value Type49CHAR(n)50DATE, DATETIME, TIMESTAMP, YEAR, and TIME50Chapter 17: Date and Time Operations52Examples52Now()52Date arithmetic52Testing against a date range53SYSDATE(), NOW(), CURDATE()53Extract Date from Given Date or DateTime Expression53Using an index for a date and time lookup53Chapter 18: Dealing with sparse or missing dataExamplesWorking with columns containg NULL valuesChapter 19: DELETE55555558Syntax58Parameters58Examples58Delete with Where clause58Delete all rows from a table58LIMITing deletes59Multi-Table Deletes59foreign keys60Basic delete61DELETE vs TRUNCATE61Multi-table DELETE61

Chapter 20: Drop Table63Syntax63Parameters63Examples63Drop Table63Drop tables from database64Chapter 21: Dynamic Un-Pivot Table using Prepared StatementExamplesUn-pivot a dynamic set of columns based on conditionChapter 22: ENUMExamples6565656868Why ENUM?68TINYINT as an alternative68VARCHAR as an alternative69Adding a new option69NULL vs NOT NULL69Chapter 23: Error 1055: ONLY FULL GROUP BY: something is not in GROUP BY clause . 71Introduction71Remarks71Examples72Using and misusing GROUP BY72Misusing GROUP BY to return unpredictable results: Murphy's Law72Misusing GROUP BY with SELECT *, and how to fix it.73ANY VALUE()74Chapter 24: Error codesExamples7575Error code 1064: Syntax error75Error code 1175: Safe Update75Error code 1215: Cannot add foreign key constraint761045 Access denied771236 "impossible position" in Replication772002, 2003 Cannot connect78

1067, 1292, 1366, 1411 - Bad Value for number, date, default, etc.78126, 127, 134, 144, 1457813979136679126, 1054, 1146, 1062, 2479Chapter 25: EventsExamples8181Create an Event81Schema for testing81Create 2 events, 1st runs daily, 2nd runs every 10 minutes81Show event statuses (different approaches)82Random stuff to consider83Chapter 26: Extract values from JSON xamples84Read JSON Array value84JSON Extract Operators85Chapter 27: Full-Text search87Introduction87Remarks87Examples87Simple FULLTEXT search87Simple BOOLEAN search87Multi-column FULLTEXT search88Chapter 28: Group By89Syntax89Parameters89Remarks89

Examples89GROUP BY USING SUM Function89Group By Using MIN function90GROUP BY USING COUNT Function90GROUP BY using HAVING90Group By using Group Concat90GROUP BY with AGGREGATE functions91Chapter 29: Handling Time Zones94Remarks94Examples94Retrieve the current date and time in a particular time zone.94Convert a stored DATE or DATETIME value to another time zone.94Retrieve stored TIMESTAMP values in a particular time zone95What is my server's local time zone setting?95What time zone values are available in my server?96Chapter 30: Indexes and Keys97Syntax97Remarks97ConceptsExamples9798Create index98Create unique index98Drop index98Create composite index98AUTO INCREMENT key98Chapter 31: INSERT100Syntax100Remarks100Examples101Basic Insert101INSERT, ON DUPLICATE KEY UPDATE101Inserting multiple rows101

Ignoring existing rows102INSERT SELECT (Inserting data from another Table)102INSERT with AUTO INCREMENT LAST INSERT ID()103Lost AUTO INCREMENT ids104Chapter 32: Install Mysql container with Docker-ComposeExamplesSimple example with docker-composeChapter 33: Joins106106106107Syntax107Examples107Joining Examples107JOIN with subquery ("Derived" table)107Retrieve customers with orders -- variations on a theme108Full Outer Join109Inner-join for 3 tables110Joins visualized111Chapter 34: JOINS: Join 3 table with the same name of id.ExamplesJoin 3 tables on a column with the same nameChapter 35: 14Create simple table with a primary key and JSON field114Insert a simple JSON114Insert mixed data into a JSON field.114Updating a JSON field115CAST data to JSON type115Create Json Object and Array115Chapter 36: Limit and Offset117Syntax117Remarks117

ExamplesLimit and Offset relationship117117LIMIT clause with one argument117LIMITclause with two arguments118OFFSET keyword: alternative syntax119Chapter 37: LOAD DATA INFILE120Syntax120Examples120using LOAD DATA INFILE to load large amount of data to database120Import a CSV file into a MySQL table121Load data with duplicates121LOAD DATA LOCAL121LOAD DATA INFILE 'fname' REPLACE121LOAD DATA INFILE 'fname' IGNORE122Load via intermediary table122import / exportChapter 38: Log files122123Examples123A List123Slow Query Log123General Query Log124Error Log126Chapter 39: Many-to-many Mapping table128Remarks128Examples128Typical schemaChapter 40: MyISAM Engine128129Remarks129Examples129ENGINE MyISAMChapter 41: MySQL Admin129130

Examples130Change root password130Drop database130Atomic RENAME & Table Reload130Chapter 42: MySQL client131Syntax131Parameters131Examples131Base login131Execute commands132Execute command from a string132Execute from script file:133Write the output on a file133Chapter 43: MySQL LOCK TABLE134Syntax134Remarks134Examples134Mysql Locks134Row Level Locking135Chapter 44: Mysql Performance TipsExamples138138Select Statement Optimization138Optimizing Storage Layout for InnoDB Tables138Building a composite index139Chapter 45: MySQL Unions140Syntax140Remarks140Examples140Union operator140Union ALL141UNION ALL With WHERE141Chapter 46: mysqlimport143

Parameters143Remarks143Examples143Basic usage143Using a custom field-delimiter144Using a custom row-delimiter144Handling duplicate keys144Conditional import145Import a standard csv145Chapter 47: NULLExamples146146Uses for NULL146Testing NULLs146Chapter 48: One to Many147Introduction147Remarks147Examples147Example Company Tables147Get the Employees Managed by a Single Manager148Get the Manager for a Single Employee148Chapter 49: ORDER BY149Examples149Contexts149Basic149ASCending / DESCending149Some tricks149Chapter 50: Partitioning151Remarks151Examples151RANGE Partitioning151LIST Partitioning152HASH Partitioning153

Chapter 51: Performance Tuning154Syntax154Remarks154Examples154Add the correct index154Set the cache correctly155Avoid inefficient constructs155Negatives155Have an INDEX155Don't hide in function156OR156Subqueries156JOIN GROUP BY157Chapter 52: Pivot queries158Remarks158Examples158Creating a pivot queryChapter 53: PREPARE Statements158160Syntax160Examples160PREPARE, EXECUTE and DEALLOCATE PREPARE Statements160Construct and execute160Alter table with add column161Chapter 54: Recover and reset the default root password for MySQL 5.7 162Introduction162Remarks162Examples162What happens when the initial start up of the server162How to change the root password by using the default password162reset root password when " /var/run/mysqld' for UNIX socket file don't exists"163Chapter 55: Recover from lost root passwordExamples165165

Set root password, enable root user for socket and http accessChapter 56: Regular Expressions165166Introduction166Examples166REGEXP / RLIKE166Pattern 166Pattern **166NOT REGEXP167Regex Contain167Any character between [ ]167Pattern or 167Counting regular expression matches167Chapter 57: Replication169Remarks169Examples169Master - Slave Replication Setup169Replication Errors172Chapter 58: Reserved Words174Introduction174Remarks174Examples179Errors due to reserved wordsChapter 59: Security via GRANTsExamples179181181Best Practice181Host (of user@host)181Chapter 60: s183

SELECT by column name183SELECT all columns (*)184SELECT with WHERE185Query with a nested SELECT in the WHERE clause185SELECT with LIKE (%)185SELECT with Alias (AS)187SELECT with a LIMIT clause187SELECT with DISTINCT188SELECT with LIKE( )189SELECT with CASE or IF189SELECT with BETWEEN190SELECT with date range191Chapter 61: Server Information192Parameters192Examples192SHOW VARIABLES example192SHOW STATUS example192Chapter 62: SSL Connection SetupExamples194194Setup for Debian-based systems194Generating a CA and SSL keys194Adding the keys to MySQL194Test the SSL connection195Enforcing SSL195References and further reading:Setup for CentOS7 / RHEL7196196First, log on to dbserver196END OF SERVER SIDE WORK FOR NOW.198still on the client here199NOW WE ARE READY TO TEST THE SECURE CONNECTION200We're still on appclient here200

Chapter 63: Stored routines (procedures and ate a Function202Create Procedure with a Constructed Prepare203Stored procedure with IN, OUT, INOUT parameters204Cursors205Multiple ResultSets207Create a function207Chapter 64: String operations208Parameters208Examples210Find element in comma separated list210STR TO DATE - Convert string to date210LOWER() / LCASE()211REPLACE()211SUBSTRING()211UPPER() / UCASE()211LENGTH()212CHAR LENGTH()212HEX(str)212Chapter 65: Table Creation213Syntax213Remarks213Examples213Basic table creationSetting defaultsTable creation with Primary Key213214214Defining one column as Primary Key (inline definition)215Defining a multiple-column Primary Key215Table creation with Foreign Key216

Cloning an existing table216CREATE TABLE FROM SELECT217Show Table Structure217Table Create With TimeStamp Column To Show Last Update218Chapter 66: Temporary TablesExamples219219Create Temporary Table219Drop Temporary Table219Chapter 67: Time with subsecond precision221Remarks221Examples221Get the current time with millisecond precision221Get the current time in a form that looks like a Javascript timestamp.221Create a table with columns to store sub-second time.222Convert a millisecond-precision date / time value to text.222Store a Javascript timestamp into a TIMESTAMP column222Chapter 68: TransactionExamples223223Start Transaction223COMMIT , ROLLBACK and AUTOCOMMIT224Transaction using JDBC Driver226Chapter 69: TRIGGERS230Syntax230Remarks230FOR EACH ROW230CREATE OR REPLACE TRIGGER230Examples231Basic Trigger231Types of triggers231Timing231Triggering event232

Before Insert trigger example232Before Update trigger example232After Delete trigger example232Chapter 70: UNION234Syntax234Remarks234Examples234Combining SELECT statements with UNION234ORDER BY234Pagination via OFFSET235Combining data with different columns235UNION ALL and UNION235Combining and merging data on different MySQL tables with the same columns into unique row236Chapter 71: UPDATE237Syntax237Examples237Basic Update237Updating one row237Updating all rows237Update with Join Pattern238UPDATE with ORDER BY and LIMIT238Multiple Table UPDATE239Bulk UPDATE239Chapter 72: Using VariablesExamples241241Setting Variables241Row Number and Group By using variables in Select Statement242Chapter 73: VIEW244Syntax244Parameters244Remarks244

Examples245Create a View245A view from two tables246Updating a table via a VIEW246DROPPING A VIEW246Credits248

AboutYou can share this PDF with anyone you feel could benefit from it, downloaded the latest versionfrom: mysqlIt is an unofficial and free MySQL ebook created for educational purposes. All the content isextracted from Stack Overflow Documentation, which is written by many hardworking individuals atStack Overflow. It is neither affiliated with Stack Overflow nor official MySQL.The content is released under Creative Commons BY-SA, and the list of contributors to eachchapter are provided in the credits section at the end of this book. Images may be copyright oftheir respective owners unless otherwise specified. All trademarks and registered trademarks arethe property of their respective company owners.Use the content presented in this book at your own risk; it is not guaranteed to be correct noraccurate, please send your feedback and corrections to info@zzzprojects.comhttps://riptutorial.com/1

Chapter 1: Getting started with MySQLRemarksMySQL is an open-source Relational Database Management System (RDBMS) that is developedand supported by Oracle Corporation.MySQL is supported on a large number of platforms, including Linux variants, OS X, andWindows. It also has APIs for a large number of languages, including C, C , Java, Lua, .Net,Perl, PHP, Python, and Ruby.MariaDB is a fork of MySQL with a slightly different feature set. It is entirely compatible withMySQL for most applications.VersionsVersionRelease 015.62013-02-01https://riptutorial.com/2

VersionRelease Date5.72015-10-01ExamplesGetting StartedCreating a database in MySQLCREATE DATABASE mydb;Return value:Query OK, 1 row affected (0.05 sec)Using the created database mydbUSE mydb;Return value:Database ChangedCreating a table in MySQLCREATE TABLE mytable(idint unsigned NOT NULL auto increment,usernamevarchar(100) NOT NULL,emailvarchar(100) NOT NULL,PRIMARY KEY(id));CREATE TABLE mytablewill create a new table called mytable.creates the id column, this type of field will assign aunique numeric ID to each record in the table (meaning that no two rows can have the same id inthis case), MySQL will automatically assign a new, unique value to the record's id field (startingwith 1).id int unsigned NOT NULL auto incrementReturn value:Query OK, 0 rows affected (0.10 sec)Inserting a row into a MySQL tableINSERT INTO mytable ( username, email )https://riptutorial.com/3

VALUES ( "myuser", "myuser@example.com" );Example return value:Query OK, 1 row affected (0.06 sec)The varchar a.k.a strings can be also be inserted using single quotes:INSERT INTO mytable ( username, email )VALUES ( 'username', 'username@example.com' );Updating a row into a MySQL tableUPDATE mytable SET username "myuser" WHERE id 8Example return value:Query OK, 1 row affected (0.06 sec)The int value can be inserted in a query without quotes. Strings and Dates must be enclosed insingle quote ' or double quotes ".Deleting a row into a MySQL tableDELETE FROM mytable WHERE id 8Example return value:Query OK, 1 row affected (0.06 sec)This will delete the row having id is 8.Selecting rows based on conditions in MySQLSELECT * FROM mytable WHERE username "myuser";Return value: ---- ---------- --------------------- id username email ---- ---------- --------------------- 1 myuser myuser@example.com ---- ---------- --------------------- 1 row in set (0.00 sec)https://riptutorial.com/4

Show list of existing databasesSHOW databases;Return value: ------------------- Databases ------------------- information schema mydb ------------------- 2 rows in set (0.00 sec)You can think of "information schema" as a "master database" that provides access to databasemetadata.Show tables in an existing databaseSHOW tables;Return value: ---------------- Tables in mydb ---------------- mytable ---------------- 1 row in set (0.00 sec)Show all the fields of a tableDESCRIBE databaseName.tableName;or, if already using a database:DESCRIBE tableName;Return value: ----------- ---------------- -------- --------- ------------------- ------- Field Type Null Key Default Extra ----------- ---------------- -------- --------- ------------------- ------- fieldname fieldvaluetype NO/YES keytype defaultfieldvalue ----------- ---------------- -------- --------- ------------------- ------- Extramay contain auto increment for example.https://riptutorial.com/5

Keyrefers to the type of key that may affect the field. Primary (PRI), Unique (UNI) .n row in set (0.00 sec)Where n is the number of fields in the table.Creating userFirst, you need to create a user and then give the user permissions on certain databases/tables.While creating the user, you also need to specify where this user can connect from.CREATE USER 'user'@'localhost' IDENTIFIED BY 'some password';Will create a user that can only connect on the local machine where the database is hosted.CREATE USER 'user'@'%' IDENTIFIED BY 'some password';Will create a user that can connect from anywhere (except the local machine).Example return value:Query OK, 0 rows affected (0.00 sec)Adding privilegesGrant common, basic privileges to the user for all tables of the specified database:GRANT SELECT, INSERT, UPDATE ON databaseName.* TO 'userName'@'localhost';Grant all privileges to the user for all tables on all databases (attention with this):GRANT ALL ON *.* TO 'userName'@'localhost' WITH GRANT OPTION;As demonstrated above, *.* targets all databases and tables, databaseName.* targets all tables ofthe specific database. It is also possible to specify database and table like sodatabaseName.tableName.WITH GRANT OPTIONshould be left out if the user need not be able to grant other users privileges.Privileges can be eitherALLor a combination of the following, each separated by a comma (non-exhaustive com/6

CREATEDROPNoteGenerally, you should try to avoid using column or table names containing spaces or usingreserved words in SQL. For example, it's best to avoid names like table or first name.If you must use such names, put them between back-tick delimiters. For example:CREATE TABLE table ( first name VARCHAR(30));A query containing the back-tick delimiters on this table might be:SELECT first name FROM table WHERE first name LIKE 'a%';Information Schema ExamplesProcesslistThis will show all active & sleeping queries in that order then by how long.SELECT * FROM information schema.PROCESSLIST ORDER BY INFO DESC, TIME DESC;This is a bit more detail on time-frames as it is in seconds by defaultSELECT ID, USER, HOST, DB, COMMAND,TIME as time seconds,ROUND(TIME / 60, 2) as time minutes,ROUND(TIME / 60 / 60, 2) as time hours,STATE, INFOFROM information schema.PROCESSLIST ORDER BY INFO DESC, TIME DESC;Stored Procedure SearchingEasily search thru all StoredProceduresfor words and wildcards.SELECT * FROM information schema.ROUTINES WHERE ROUTINE DEFINITION LIKE '%word%';Read Getting started with MySQL online: artedwith-mysqlhttps://riptutorial.com/7

Chapter 2: ALTER TABLESyntax ALTER [IGNORE] TABLE tbl name [alter specification [, alter specification] .][partition options]Remarksalter specification: table options ADD [COLUMN] col name column definition [FIRST AFTER col name ] ADD [COLUMN] (col name column definition,.) ADD {INDEX KEY} [index name] [index type] (index col name,.) [index option] . ADD [CONSTRAINT [symbol]] PRIMARY KEY [index type] (index col name,.) [index option]. ADD [CONSTRAINT [symbol]] UNIQUE [INDEX KEY] [index name] [index type](index col name,.) [index option] . ADD FULLTEXT [INDEX KEY] [index name] (index col name,.) [index option] . ADD SPATIAL [INDEX KEY] [index name] (index col name,.) [index option] . ADD [CONSTRAINT [symbol]] FOREIGN KEY [index name] (index col name,.)reference definition ALGORITHM [ ] {DEFAULT INPLACE COPY} ALTER [COLUMN] col name {SET DEFAULT literal DROP DEFAULT} CHANGE [COLUMN] old col name new col name column definition [FIRST AFTER col name] LOCK [ ] {DEFAULT NONE SHARED EXCLUSIVE} MODIFY [COLUMN] col name column definition [FIRST AFTER col name] DROP [COLUMN] col name DROP PRIMARY KEY DROP {INDEX KEY} index name DROP FOREIGN KEY fk symbol DISABLE KEYS ENABLE KEYS RENAME [TO AS] new tbl name RENAME {INDEX KEY} old index name TO new index name ORDER BY col name [, col name] . CONVERT TO CHARACTER SET charset name [COLLATE collation name] [DEFAULT] CHARACTER SET [ ] charset name [COLLATE [ ] collation name] DISCARD TABLESPACE IMPORT TABLESPACE FORCE {WITHOUT WITH} VALIDATION ADD PARTITION (partition definition) DROP PARTITION partition names DISCARD PARTITION {partition names ALL} TABLESPACE IMPORT PARTITION {partition names ALL} TABLESPACE TRUNCATE PARTITION {partition names ALL} COALESCE PARTITION number REORGANIZE PARTITION partition names INTO (partition definitions) EXCHANGE PARTITION partition name WITH TABLE tbl name [{WITH WITHOUT} VALIDATION] ANALYZE PARTITION {partition names ALL} CHECK PARTITION {partition names ALL} OPTIMIZE PARTITION {partition names ALL} REBUILD PARTITION {partition names ALL} REPAIR PARTITION {partition names ALL} REMOVE PARTITIONINGhttps://riptutorial.com/8

UPGRADE PARTITIONINGindex col name: col name [(length)] [ASC DESC]index type: USING {BTREE HASH}index option: KEY BLOCK SIZE [ ] value index type WITH PARSER parser name COMMENT 'string'table options: table option [[,] table option] . (seepartition options: (seeCREATE TABLE options)CREATE TABLE options)Ref: MySQL 5.7 Reference Manual / . / ALTER TABLE Syntax / 14.1.8 ALTER TABLE SyntaxExamplesChanging storage engine; rebuild table; change file per tableFor example, if t1 is currently not an InnoDB table, this statement changes its storage engine toInnoDB:ALTER TABLE t1 ENGINE InnoDB;If the table is already InnoDB, this will rebuild the table and its indexes and have an effect similarto OPTIMIZE TABLE. You may gain some disk space improvement.If the value of innodb file per table is currently different than the value in effect when t1 was built,this will convert to (or from) file per table.ALTER COLUMN OF TABLECREATE DATABASE stackoverflow;USE stackoverflow;Create table stack(id user int NOT NULL,username varchar(30) NOT NULL,password varchar(30) NOT NULL);ALTER TABLE stackALTER TABLE stackALTER TABLE stackALTER TABLE stackcolumnALTER TABLE stackexisting columnADD COLUMN submit date NOT NULL; -- add new columnDROP COLUMN submit; -- drop columnMODIFY submit DATETIME NOT NULL; -- modify type columnCHANGE submit submit date DATETIME NOT NULL; -- change type and name ofADD COLUMN mod id INT NOT NULL AFTER id user; -- add new column afterALTER table add INDEXTo improve performance one might want to add indexes to columnshttps://riptutorial.com/9

ALTER TABLE TABLE NAME ADD INDEX index name ( column name )altering to add composite (multiple column) indexesALTER TABLE TABLE NAME ADD INDEX index name ( col1 , col2 )Change auto-increment valueChanging an auto-increment value is useful when you don't want a gap in an AUTO INCREMENTcolumn after a massive deletion.For example, you got a lot of unwanted (advertisement) rows posted in your table, you deletedthem, and you want to fix the gap in auto-increment values. Assume the MAX value ofAUTO INCREMENT column is 100 now. You can use the following to fix the auto-incrementvalue.ALTER TABLE your table name AUTO INCREMENT 101;Changing the type of a primary key columnALTER TABLE fish data.fish DROP PRIMARY KEY;ALTER TABLE fish data.fish MODIFY COLUMN fish id DECIMAL(20,0) NOT NULL PRIMARY KEY;An attempt to modify the type of this column without first dropping the primary key would result inan error.Change column definitionThe change the definition of a db column, the query below can be used for example, if we havethis db schemausers (firstname varchar(20),lastname varchar(20),age char(2))To change the type of age column from char to int, we use the query below:ALTER TABLE users CHANGE age age tinyint UNSIGNED NOT NULL;General format is:ALTER TABLE table name CHANGE column name new column definitionRenaming a MySQL databasehttps://riptutorial.com/10

There is no single command to rename a MySQL database but a simple workaround can be usedto achieve this by backing up and restoring:mysqladmin -uroot -p password create new name mysqldump -uroot -p password --routines old name mysql -uroot -pmypassword new name mysqladmin -uroot -p password drop old name Steps:1. Copy the lines above into a text editor.2. Replace all references to old name , new name and password ( optionally root to use adifferent user) with the relevant values.3. Execute one by one on the command line (assuming the MySQL "bin" folder is in the pathand entering "y" when prompted).Alternative Steps:Rename (move) each table from one db to the other. Do this for each table:RENAME TABLE old db . name TO new db . name ;You can create those statements by doing something likeSELECT CONCAT('RENAME TABLE old db.', table name, ' TO ','new db.', table name)FROM information schema.TABLESWHERE table schema 'old db';Warning. Do not attempt to do any sort of table or database by simply moving files around on thefilesystem. This worked fine in the old days of just MyISAM, but in the new days of InnoDB andtablespaces, it won't work. Especially when the "Data Dictionary" is moved from the filesystem intosystem InnoDB tables, probably in the next major release. Moving (as opposed to just DROPping) aPARTITION of an InnoDB table requires using "transportable tablespaces". In the near future, therewon't even be a file to reach for.Swapping the names of two MySQL databasesThe following commands can be used to swap the names of two MySQL databases ( db1 and db2 ):mysqladmin -uroot -p password create swaptempmysqldump -uroot -p password --routines db1 mysql -uroot -p password swaptempmysqladmin -uroot -p password drop db1 mysqladmin -uroot -p password create db1 mysqldump -uroot -p password --routines db2 mysql -uroot -p password db1 mysqladmin -uroot -p password drop db2 mysqladmin -uroot -p password create db2 mysqldump -uroot -p password --routines swaptemp mysql -uroot -p password db2 mysqladmin -uroot -p password drop swaptemphttps://riptutorial.com/11

Steps:1. Copy the lines above into a text editor.2. Replace all references to db1 , db2 and password ( optionally root to use a differentuser) with the relevant values.3. Execute one by one on the command line (assuming the MySQL "bin" folder is in the pathand entering "y" when prompted).Renaming a MySQL tableRenaming a table can be done in a single command:RENAME TABLE old name TO new name ;The following syntax does exactly the same:ALTER TABLE old name RENAME TO new name ;If renaming a temporary table, the ALTERTABLEversion of the syntax must be used.Steps:1. Replace old name and new name in the line above with the relevant values. Note: If thetable is being moved to a different database, the dbname.tablename syntax can be used for oldname and/or new name .2. Execute it on the relevant database in the MySQL command line or a client such as MySQLWorkbench. Note: The user must have ALTER and DROP privileges on the old table andCREATE and INSERT on the new one.Renaming a column in a MySQL tableRenaming a column can be done in a single statement but as well as the new name, the "columndefinition" (i.e. its data type and other optional properties such as nullability, auto incrementingetc.) must also be specified.ALTER TABLE table name CHANGE old name new name column definition ;Steps:1. Open the MySQL command line or a client such as MySQL Workbench.2. Run the following statement: SHOW CREATE TABLE table name ; (replacing table name with therelevant value).3. Make a note of the

Chapter 42: MySQL client 131 Syntax 131 Parameters 131 Examples 131 Base login 131 Execute commands 132 Execute command from a string 132 Execute from script file: 133 Write the output on a file 133 Chapter 43: MySQL LOCK TABLE 134 Syntax 134 Remarks 134 Examples 134 Mysql Locks 134 Row Level Locking 135 Ch