MySQL is a fully open-source Relational Database Management System. It uses Structured Query Language (SQL) to manage the database. With only a few SQL statements, we can interact with MySQL using a simple programming language. SQL is a large group of statements that may be classified as sublanguages, typically: a data query language (DQL), a data definition language (DDL), a data control language (DCL), and a data manipulation language (DML). SQL includes data query, data manipulation (insert, update, and delete), data definition (schema creation and modification), and data access control.
MySql is platform flexible,i.e. can run on Windows, Linux and Mac. It can be easily used in both small-scale and large-scale businesses. SQL is largely based on Relational Algebra and Tuple Relational Calculus. Sun Microsystems (now Oracle Corporation) acquired MySQL AB, the Swedish company that owned and sponsored MySQL.
MySQL has stand-alone users that can interact with a MySQL database using SQL, but in more frequent instances, MySQL is used with other programs to create applications that require relational database expertise. LAMP is an acronym for Linux, Apache, MySQL, PHP/Python, and Perl/Python.LEMP is a stack which uses Linux, Nginx Server, MySQL, and PHP. Django Stack uses JS, Python, Django, and MySQL. MySQL is a component of this software stack.
MySQL is password encrypted which implies it is secure and lightweight. We can also implement a client /server architecture in MySQL. Transactions can be committed, rolled back and provides crash recovery. It also provides high performance, high flexibility, and high productivity.
INSTALLING MySQL
On Windows
- Download the MYSQL installer from here: Install MySQL Installer. Execute the installer with administrator privileges.
- Choose the appropriate setup type. Preferably Developer Default.
- Complete the installation. This setup installs multiple MySQL products and the MySQL server is one of them.
On Linux
- For distros that use apt (Debian based) run: sudo apt install mysql-server.
- For distros that use yum, run : sudo yum install mysql-shell.
- For distros that use dnf, run : sudo dnf install mysql-shell.
1. MYSQL COMMAND LINE COMMANDS
COMMAND | MEANING | SYNTAX |
---|---|---|
mysql | Allows user to connect to the MySQL CLI |
|
exit | Exits the MySQL CLI |
|
clear | Clears the MySQL shell |
|
create user | Creates a new user |
|
show user | Shows all user who have access to the MySQL Client |
|
drop user | To delete an existing user |
|
grant all privileges | Assigns privileges to a MySQL user |
|
show grants | Displays the privileges that are assigned to a MySQL user |
|
revoke all privileges | Revokes all privileges assigned to a MySQL user |
|
mysqldump | Creates a backup of a set of SQL statements that can be used to recreate the original database object definitions and table data. |
|
2. MYSQL DATABASE COMMANDS (DATA DEFINITION LANGUAGE;DDL)
COMMAND | MEANING | SYNTAX |
---|---|---|
show database | Shows all the databases available in MySQL server. |
|
create database | Creates a new database if it does not exist. |
|
drop database | To delete an existing database permanently. |
|
alter database | Changes or modifies the characteristics of an existing database. |
|
use database | Allow you to use a particular database or change from the current database to another database. |
|
3. MySQL Table commands(DDL)
COMMAND | MEANING | SYNTAX |
---|---|---|
show tables | Shows all tables within the current database. |
|
create table | Creates a new table in the current database. |
|
alter table (add column) | Adds a new column to an existing table. |
|
alter table (drop column) | Deletes a column from an existing table. |
|
alter table (alter column) | Alters an existing column in an already existing table. |
|
alter table(add primary key) | Alters or adds primary key to an existing table. |
|
alter table(drop primary key) | Drops an existing primary key in a table. |
|
alter table(add foreign key) | Creates a foreign key on an existing table. |
|
alter table(drop foreign key) | Deletes an existing foreign key in an already existing table. |
|
rename table | Changes the name of an existing table. |
|
drop table | Deletes the entire table along with its definition. |
|
truncate table | Remove all records in a MySQL table. |
|
describe table | Displays all the columns of an existing table. |
|
describe table column | Displays all the values stored in a particular column. |
|
4. MySQL DML(Data Manipulation Language) Commands
COMMAND | MEANING | SYNTAX |
---|---|---|
select * | Displays all rows in a table. |
|
select * (multiple tables) | Displays all the rows of the cartesian product of the two tables |
|
select columns | Select particular columns from table(s) |
|
select with condition | Displays rows based on a particular condition |
|
select with multiple conditions(AND) | Displays rows only when both the conditions are satisfied. |
|
select with multiple conditions(OR) | Displays rows only when either of the conditions are satisfied. |
|
select with condition(NOT) | Displays rows based on negation of a particular condition. |
|
select with group by | Displays rows that have same values into summary rows |
|
select with having | Used instead of where for aggregate functions. |
|
select distinct | Display all unique rows discarding duplicate ones. |
|
order by | Used to sort results in ascending order or descending order |
|
column alias | Changes the output of the name of the column. |
|
like | Used to search for a specific pattern. |
|
insert record | Adds a new row to an existing table. |
|
insert record(multiple) | Adds multiple records into an existing table. |
|
delete | Deletes all records in a table. |
|
delete with where | Deletes specific records |
|
between | Selects values in a given range |
|
in | Used instead of multiple OR operators. |
|
exists | Tests for existence of a certain record. Returns a boolean value. |
|
update table | Modifies data in existing tables. |
|
inner join | Selects records that have the same values in two same or distinct tables. |
|
left join | Selects all the records from the left table and matching records from the right table. |
|
right join | Selects all the records from the right table and matching records from the left table. |
|
cross join | Selects rows from cartesian product of both the tables. |
|
full outer join | Selects all records with a match on table1 or table2. |
|
union | Combines the result of two select statements. |
|
union all | Similar to Union but allows duplicate values |
|
concat() | Combines two or more columns together. |
|
5. MySQL DATA TYPES
In MySQL just like other programming languages, each column, local variable, expression, and parameter has a related data type. A data type is an attribute that specifies the type of data that the object can hold.
- String Data Types
DATATYPE | DETAILS |
---|---|
CHAR(size) | Stores Alpha Numeric and special characters. Size varies from 0 to 255 characters. |
VARCHAR(size) | Can contain letters, numbers, and characters that are of variable length (size). The size parameter specifies the column length in characters; it can be from 0 to 65535. |
BINARY(size) | Similar to CHAR(). But it stores binary strings. |
VARBINARY(size) | Similar to Binary() but the length is variable. |
TINYBLOB | For Binary Large Objects. Max size=255 bytes. |
TINYTEXT | Holds string of max length 255 characters. |
TEXT(Size) | Stores a string of max length 65535 bytes. |
BLOB | Stores Binary Large Objects up to 65535 bytes of data. |
MEDIUMTEXT | Stores 2^8 times the characters as compared to TINYTEXT. |
MEDIUMBLOB | Stores 2^8 times bytes as compared to TINYBLOB. |
LONGTEXT | Stores 2^8 times the characters as compared to MEDIUMTEXT. |
LONGBLOB | Stores 2^8 times bytes as compared to MEDIUMBLOB. |
ENUM(val1, val2, val3, ...) | Stores only one value, which can be chosen from a range of possible values. An ENUM list can contain at most 65535 values. A value that is inserted that is not in the list will be replaced with a blank value. The values are arranged in the order you specify them. |
SET(val1, val2, val3, ...) | Stores a string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list |
- Numeric Data Types
DATATYPE | DETAILS |
---|---|
BIT(size) | Stores a bit-value. The size parameter specifies the number of bits per value . The value is represented as a number of bits. The size parameter can hold a value from 1 to 64. The default value for size is 1. |
TINYINT(size) | Stores very small int values. Signed ranges from -128 to 127. Unsigned ranges from 0 to 255. Size defines the maximum display width of 255. |
BOOL | Zero is considered as false and one is considered as true. |
BOOLEAN | Same as BOOL. |
SMALLINT(size) | Stores a small integer. Signed ranges from -32768 to 32767. Unsigned ranges from 0 to 65535. Size defines the maximum display width of 255. |
MEDIUMINT(size) | Stores a medium valued integer. Signed ranges from -8388608 to 8388607. Unsigned ranges from 0 to 16777215. Size defines the maximum display width of 255. |
INT(size) | Stores a medium integer. Signed ranges from -2147483648 to 2147483647. Unsigned ranges from 0 to 4294967295. Size defines the maximum display width of 255. |
INTEGER(size) | Same as INT(size) |
BIGINT(size) | Stores a large valued integer. Signed ranges from -9223372036854775808 to 9223372036854775807. Unsigned ranges from 0 to 18446744073709551615. Size defines the maximum display width of 255. |
FLOAT(size, d) | Stores a floating point(decimal number). The number of digits is specified in size. The number of digits after the decimal point is specified by the value d. |
FLOAT(p) | Stores a floating point(decimal number. If p value is between 0 and 24, the data type becomes FLOAT() else the data type becomes DOUBLE() |
DOUBLE(size, d) | Stores a normal-size floating point (decimal)number. The number of digits is specified in size. The number of digits after the decimal point is specified by the value d. |
DECIMAL(size, d) | An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0. |
- Date and Time Data Types
DATATYPE | DETAILS |
---|---|
DATE | Stores a date in the format: YYYY-MM-DD. Supports a range between '1000-01-01' to '9999-12-31' |
DATETIME(fsp) | Combination of date and time in the format: YYYY-MM-DD hh:mm:ss. Supports a range between '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. |
TIMESTAMP(fsp) | Stores a time stamp in the format YYYY-MM-DD hh:mm:ss UTC. Supports a range between '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. |
TIME(fsp) | Stores time in the format hh:mm:ss. Supports a range between '-838:59:59' to '838:59:59' |
YEAR | Stores a year in four-digit format. Supports a range between 1901 to 2155 (includes 0000). |
6. MySQL AGGREGATE FUNCTIONS
A function that performs an arithmetic operation on a set of values and returns a single value is called an aggregate function.
COMMAND | FUNCTION | SYNTAX |
---|---|---|
count() | Returns the number of rows, (including NULL) |
|
sum() | Returns sum of all non NULL values. |
|
avg() | Returns average of all non NULL values. |
|
min() | Returns minimum value in the set. |
|
max() | Returns maximum value in the set. |
|
groutp_concat() | Concatenates values from multiple rows into one field. |
|
7. INDEXES AND VIEWS IN MySQL
An Index retrieves data much faster than otherwise. Indexes speed up the query/search. A user cannot view an Index. Updating a table with an index takes more time because both table and index have to be updated.
The view is a virtual table which takes the result of an SQL query. Users can access a View. They have rows and columns similar to a table.
COMMAND | FUNCTION | SYNTAX |
---|---|---|
create index | Creates a new index from an existing table. Allows duplicate values. |
|
create index unique | Similar to creating an index. But only allows unique values. |
|
drop index | Deletes an existing index. |
|
rebuild index | Used to rebuild one or all indexes in a table if corrupted. |
|
create view | Creates a view if it doesn’t exist. |
|
update view | Creates or edits an existing view. |
|
rename view | Changes the name of the view. |
|
drop view | Deletes an existing view. |
|
drop views | Deletes multiple views. |
|
show views | Displays all views in a database. |
|
8. TRIGGERS IN MYSQL
Triggers are DBMS objects which are associated with tables. Triggers are fired when any one of the DML statements (INSERT, DELETE or UPDATE) is activated.
There are two types of triggers,
- Row Level Triggers: A trigger is an instruction that causes a row to trigger to be fired once for each row affected by an insert, update, or delete statement. The row trigger is fired automatically.
- Statement Level Trigger: Trigger is fired once regardless of the number of DML statements.
There are six types of triggers, namely,
- Before Insert: Activated before insertion.
- After Insert: Activated after insertion.
- Before Update: Activated before updating.
- After Update: Activated after updating.
- Before Delete: Activated before deletion.
- After Delete: Activated after deletion.
COMMAND | FUNCTION | SYNTAX |
---|---|---|
create trigger | Creates a new trigger on an existing table. |
|
drop trigger | Deletes an existing trigger. | > DROP TRIGGER TRIGGERNAME; |
show all triggers | Displays all the triggers in the database. | > SHOW TRIGGERS FROM | IN DATABASE_NAME WHERE SEARCH_CONDITION; |
9. STORED PROCEDURES AND FUNCTION
Procedures are reusable SQL codes that we store in a database. We can directly call procedures instead of writing the query again and again.
Functions are reusable code, which runs certain SQL commands and returns an appropriate value.
- Syntax to create a new procedure.
DELIMITER $$
CREATE PROCEDURE procedurename(parameterlist)
BEGIN
body;
END $$
DELIMITER ;
- Syntax to create a new function
DELIMITER $$
CREATE FUNCTION functionname(parameterlist)
RETURNS datatype
NOT DETERMINISTIC
BEGIN
%statements%
END $$
DELIMITER ;
COMMAND | FUNCTION | SYNTAX |
---|---|---|
drop procedure | Deletes an existing procedure. | > DROP PROCEDURE PROCEDURENAME; |
show all procedures | Displays all the stored procedures in the database. | > SHOW PROCEDURE STATUS LIKE ‘%PATTERN’ | WHERE CONDITION; |
drop function | Deletes an existing stored function. | > DROP FUNCTION FUNCTIONNAME; |
show stored functions | Displays all the stored functions. | > SHOW FUNCTION STATUS LIKE ‘%PATTERN’ | WHERE CONDITION; |
10. INBUILT FUNCTIONS IN MySQL
- STRING FUNCTIONS
Function | Description |
---|---|
ASCII | Returns the ASCII value of a character |
CHAR_LENGTH | Returns the length of a string. |
CHARACTER_LENGTH | Returns the length of a string |
CONCAT | Concatenates two or more expressions. |
CONCAT_WS | Concatenates with a separator. |
FIELD | Returns the index of value in a list. |
FIND_IN_SET | Returns the index of a string within a list. |
FORMAT | Changes the format/representation. |
INSERT | Inserts a string within a string at a given index. |
INSTR | Returns the index of the first occurrence of a string in another one. |
LCASE | Converts an entire string to lowercase. |
LEFT | Extracts a length of characters from the left of a string. |
LENGTH | Returns the string length in bytes. |
LOCATE | Returns the location of the first occurrence of a substring in a given string |
LOWER | Converts an entire string to lowercase. |
LPAD | Left-pads a string with a given string. |
LTRIM | Removes spaces from the left of a string. |
MID | Extracts a substring from a string at a given position. |
POSITION | Returns the location of the first occurrence of a substring in a given string |
REPEAT | Repeats the string the number of times the user specifies. |
REPLACE | Replaces occurrences of a substring in a string with another substring. |
REVERSE | Reverses the string. |
RIGHT | Extracts a length of characters from the right of a string. |
RPAD | Right-pads a string with a given string. |
RTRIM | Removes spaces from the right of a string. |
STRCMP | Checks whether two strings are equal. |
SUBSTR | Extracts a substring from a string at a position mentioned by the user. |
SUBSTRING | Same as substr. |
TRIM | Trims leading and trailing spaces from a string as specified by the user. |
UCASE | Converts an entire string to uppercase. |
UPPER | Converts an entire string to uppercase. |
- NUMERIC FUNCTIONS
Function | Description |
---|---|
ABS | Returns the absolute value. |
ACOS | Returns the cosine inverse. |
ASIN | Returns the sine inverse. |
ATAN | Returns the tan inverse of one or two numbers. |
ATAN2 | Returns the tan inverse of two numbers. |
AVG | Returns the mean value. |
CEIL | Returns the smallest integer that is greater than or equal to the number |
CEILING | Returns the smallest integer that is greater than or equal to the number |
COS | Returns the cosine. |
COT | Returns the cotangent. |
COUNT | Returns the number of records returned by a query. |
DEGREES | Converts angle in Radians to Degrees. |
DIV | Integer division |
EXP | Returns e raised to the power of value mentioned. |
FLOOR | Returns the largest integer that is less than or equal to a number |
GREATEST | Returns the largest value in the list. |
LEAST | Returns the smallest value in the list. |
LN | Calculates logarithm to the base e. |
LOG | Calculates logarithm to the base e. |
LOG10 | Calculates logarithm to the base 10. |
LOG2 | Calculates logarithm to the base 2. |
MAX | Returns the largest value in a set. |
MIN | Returns the least value in a set. |
MOD | Returns the remainder after division of two numbers. |
PI | Returns value of π |
POW | Used for exponents. |
POWER | Used for exponents. |
RADIANS | Converts angle in Degree to Radians. |
RAND | Generates a random number. |
ROUND | Rounds the number to the nearst decimal place. |
SIGN | Returns the sign of a number |
SIN | Returns the sine. |
SQRT | Returns the root of a number. |
SUM | Calculates the sum of a set. |
TAN | Returns the tangent. |
- MYSQL DATE FUNCTION
Function | Description |
---|---|
ADDDATE | Adds a date interval and return the value. |
ADDTIME | Adds a time interval and then returns the value. |
CURDATE | Returns today’s date |
CURRENT_DATE | Same as CURDATE |
CURRENT_TIME | Returns the time at the moment |
CURRENT_TIMESTAMP | Returns date and time at the moment. |
CURTIME | Returns time at the moment. |
DATE | Picks up the date from an expression of Date/Time. |
DATEDIFF | Returns number of days between two given dates. |
DATE_ADD | Similar to ADDDATE |
DATE_FORMAT | Changes the format in which Date is displayed. |
DATE_SUB | Subtracts a time interval and returns the value. |
DAY | Returns the weekday for today. |
DAYNAME | Returns the weekday name for any date. |
DAYOFMONTH | Used to retrieve the index of the day of the month of any date. |
DAYOFWEEK | Used to retrieve the index of the weekday of any date. |
DAYOFYEAR | Used to retrieve the index of the day of a year of any date. |
EXTRACT | Extracts a part of any date. |
HOUR | Returns the “hours” in a given time. |
LAST_DAY | Return the last day of the given month. |
LOCALTIME | Returns the date and time at the moment. |
LOCALTIMESTAMP | Similar to LOCALTIME. |
MAKEDATE | Returns a date based on the year and the no. of days you specify. |
MAKETIME | Returns a time based on the hours , minutes and seconds you specify. |
MICROSECOND | Returns the microseconds in a given time. |
MINUTE | Returns the minutes in a given time. |
MONTH | Returns the month on a given date. |
MONTHNAME | Same as MONTH but returns the name of the month. |
NOW | Returns date and time at the moment. |
PERIOD_ADD | Adds a specific number of months. |
PERIOD_DIFF | Return the difference between two time periods. |
SECOND | Return the seconds in a given time. |
SEC_TO_TIME | Returns time in seconds. |
STR_TO_DATE | Formats the date based on a particular string. |
SUBDATE | Same as DATE_SUB. |
SUBTIME | Subtracts a time interval. |
SYSDATE | Returns the date/time reflected by the system. |
TIME | Returns the time from a date/time value. |
TIME_FORMAT | Time is displayed based on a certain format. |
TIME_TO_SEC | Returns time in seconds. |
TIMEDIFF | Returns the difference between two date-time values. |
TO_DAYS | Returns the number of days between amy date and "0000-00-00" |
- ADVANCED MYSQL FUNCTION
Function | Description |
---|---|
BIN | Returns binary value of a given number. |
BINARY | Converts a given string to a binary string. |
CAST | Converts data from one data type to another. |
COALESCE | Returns the first non-null value in a set or list. |
CONV | Converts a number from one number-base system to another |
CONVERT | Similar to CAST in working |
CURRENT_USER | Returns the user name and host name for the MySQL account that is currently used. |
DATABASE | Returns the name of the database currently in use. |
IF | IF condition statement. |
SESSION_USER | Returns the current MySQL user name and host name. |
SYSTEM_USER | Similar to SESSION_USER. |
USER | Similar to SESSION_USER. |
VERSION | Returns the current version of the MySQL server installed. |
CONCLUSION
By going through this cheat sheet, you would have got a decent understanding/revision of MySQL. More than memorizing syntax, do pay attention to practising them and solving problems.
MYSQL MCQ
What is the default date and time format in MySQL?
Which of the following in-built functions is the same as LOG?
Which one of these doesn’t have a syntaxical error?
Triggers can be used by which of the following?
If I want records of all distinct tables, what join do I use?
Which of the following year(s) is not supported in the YEAR data type.
Choose the correct syntax.
In which of the following stacks, MySQL is not used.
Choose the right syntax for MySQL backup.
Which of the following is the correct function definition in MySQL?:
A:
DELIMITER $$
CREATE FUNCTION functionname(parameter1,parameter2……)
RETURNS datatype
BEGIN
%statements%
END
DELIMITER ;
B:
DELIMITER $$
CREATE FUNCTION functionname(parameterlist)
RETURNS datatype
BEGIN
%statements%
END
DELIMITER $$;
C:
DELIMITER $$
CREATE FUNCTION functionname(parameter1,parameter2……)
BEGIN
%statements%
END
DELIMITER$$ ;
D.
DELIMITER $$
CREATE FUNCTION functionname(parameterlist)
RETURNS datatype
BEGIN
%statements%
END $$
DELIMITER ;
Which of the following is not a type of table partitioning?
Choose the right syntax to generate Statistics of a table with Histogram of columns.
Choose the write option which describes Table Constraints aptly
What does A in ACID stand for?
File extension not supported by MySQL.
0 Comments