0% found this document useful (0 votes)
3 views

MySQL_cheatsheet_withLinks_compressed

This cheat sheet provides an overview of MySQL, a popular open-source RDBMS developed by Oracle, including its properties, data types, and command types such as DDL, DML, DCL, TCL, and DQL. It outlines various commands for managing databases, including creating, altering, and deleting tables, as well as inserting, updating, and querying data. Additionally, it covers constraints, subqueries, and complex queries to enhance data management capabilities.

Uploaded by

bushu khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

MySQL_cheatsheet_withLinks_compressed

This cheat sheet provides an overview of MySQL, a popular open-source RDBMS developed by Oracle, including its properties, data types, and command types such as DDL, DML, DCL, TCL, and DQL. It outlines various commands for managing databases, including creating, altering, and deleting tables, as well as inserting, updating, and querying data. Additionally, it covers constraints, subqueries, and complex queries to enhance data management capabilities.

Uploaded by

bushu khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

CHEAT SHEET

Connect with Alumni


Introduction

1. What is a RDBMS (Relational Database


Management System)?

RDBMS (Relational Database Management System) is a software which allows to manage,


store, fetch and query data stored in the relational database.

2. Introduction of MySQL

• Developed by Oracle
• An open source relational database management system (RDBMS)
• Based on Structured Query Language (SQL)

02 MySQL CheatSheet
3. Properties of MySQL

• Easy to use • Platform Independent


• Secure • Free to download
• Scalable • Client/ Server Architecture
• High Performance • Quick and Reliable

4. Data Types

String Numeric

• CHAR: 0-255, fixed length • TINYINT: Integer(-128 to 127)


• VARCHAR: 0-255, variable length • SMALLINT: Integer( -32768 to 32767)
• TINYTEXT: 0-255, stores string • MEDIUMINT: Integer( -8388608 to 8388607)
• TEXT: 0-65,535, stores string • INT: Integer( -2147483648 to 2147483647)
• BLOB: 0-65,535, stores bytes • BIGINT: Integer( -9223372036854775808 to
• MEDIUMTEXT: 0-16,777,215, stores strings • 9223372036854775807)
• MEDIUMBLOB: 0-16,777,215, stores bytes • FLOAT: Decimal, 23 digits
• LONGTEXT: 0-4,294,967,295, stores strings • DOUBLE: Decimal, 24…53 digits
• LONGBLOB: 0-4,294,967,295, stores bytes • DECIMAL: double stored as string

Date and Time

• DATE: YYYY-MM-DD
• DATETIME: YYYY-MM-DD HH:MM:SS
• TIMESTAMP: YYYY-MM-DD HH:MM:SS
• TIME: HH:MM:SS

03 MySQL CheatSheet
5. Types of commands

COMMANDS

DDL(Data DML(Data DCL(Data


Definition Manipulation Control Language):
Language): Language): Used for granting
Used to create, modify Used for modification permissions
and delete the of data. • GRANT
database structure. • INSERT • REVOKE
• CREATE • UPDATE
• DROP • DELETE
• ALTER
• TRUNCATE
• RENAME

TCL(Transaction DQL(Data Query


Control Language): Language):
Used to control Used to fetch data
transaction execution. from database.
• COMMIT • SELECT
• ROLLBACK
• SAVEPOINT

04 MySQL CheatSheet
02 DDL Commands

1. CREATE

Used to create table in the database.

Syntax Example

CREATE TABLE tableName(


ColumnName1 datatype,
CREATE TABLE Employee(
ColumnName2 datatype, empId int,
…. empName varchar(45),
constraints empDOB date);
)

empId empName empDOB


- - -

2. ALTER

Used to add, delete, or modify columns and to add or delete constraints in an existing
table.

Syntax(Add column) Example(Add column)

ALTER TABLE tableName


ADD columnName datatype;
ALTER TABLE Employee
ADD address varchar(20)

05 MySQL CheatSheet
New column added in the table

empId empName empDOB address


- - - -

Syntax(Modify column)

ALTER TABLE tableName MODIFY columnName datatype;

Example(Modify column)

ALTER TABLE Employee MODIFY address varchar(50);

Syntax(Rename column)

ALTER TABLE tableName RENAME COLUMN columnName TO newColName ;

Example(Rename column)

ALTER TABLE Employee RENAME COLUMN address TO empAddress;

empId empName empDOB empAddress


- - - -

06 MySQL CheatSheet
Syntax(Drop column) Example(Drop column)

ALTER TABLE tableName


DROP columnName;
ALTER TABLE Employee
DROP empAddress;

Renamed column

empId empName empDOB empAddress


- - - -

Syntax(Add constraint)

ALTER TABLE tableName ADD CONSTRAINT constraint_name PRIMARY


KEY(colName1, colName2) ;

Example(Add constraint)

ALTER TABLE Employee ADD CONSTRAINT emp_prim_key PRIMARY KEY(empId);

Syntax(Drop constraint)

ALTER TABLE tableName DROP CONSTRAINT constraint_name;

07 MySQL CheatSheet
Example(Drop constraint)

ALTER TABLE Employee DROP CONSTRAINT emp_prim_key;

3. TRUNCATE

Used to delete complete data of the table without deleting table structure.

Syntax Example

TRUNCATE TABLE tableName;


TRUNCATE TABLE Employee;

4. DROP

Used to delete table from the database.

Syntax Example

DROP TABLE tableName;


DROP TABLE Employee

08 MySQL CheatSheet
5. RENAME

Used to rename table.

Syntax Example

RENAME TABLE tableName TO newTableName;

RENAME TABLE Employee TO employeeDetails;

09 MySQL CheatSheet
03 Constraints

NOT NULL PRIMARY KEY

Prevents column from accepting Ensures that column does not accept
NULL values. NULL and duplicate values.

Example Example

CREATE TABLE Employee( CREATE TABLE Employee(


empId int NOT NULL, empId int CONSTRAINT emp_id_pk PRIMARY KEY,
empName varchar(45), empName varchar(45),
empDOB date); empDOB date);

CHECK UNIQUE

Limit the values for column. Ensures that column does not have
duplicate values, but allow NULL values.

Example Example

CREATE TABLE Employee(


Allows to accept only
CREATE TABLE Employee(
empId int NOT NULL, empId int CONSTRAINT emp_id_uk UNIQUE,
empName varchar(45), F or M in empGender column.
empDOB date,
empName varchar(45),
empGender char(1) empDOB date);
CONSTRAINT emp_gender_ck1 CHECK(Gender IN('M', 'F')));

10 MySQL CheatSheet
FOREIGN KEY DEFAULT

A field in one table which refers to Used to provide default value to the column,
primary key of another table. which will be used if no value is provided
for that column.

Example Example

CREATE TABLE ComputerDet( CREATE TABLE Employee(


compId int, empId int,
empId FOREIGN KEY REFERENCES Employee(empId), empName varchar(45),
compModel varchar(50)); empDOB date
empDOJ date DEFAULT SYSDATE);
Here empId is primary key
of table Employee.

11 MySQL CheatSheet
04 DML Commands

1. INSERT Command

Used to add data(rows) in a table.

empId empName empDOB


- - -

Syntax 1

INSERT INTO tableName VALUES (col1Value, col2Value, ..);

Example 1

INSERT INTO Employee VALUES(1, ‘John’, ‘2002-09-09’);

empId empName empDOB

1 John 2002-09-09

12 MySQL CheatSheet
Syntax 2

NSERT INTO tableName(col1Name, col2Name,


VALUES (col1Value, col2Value, ..);

Example 2

INSERT INTO Employee(empId, empName, empDOB)


VALUES(2, ’Hannah’, ‘2000-08-07’);

empId empName empDOB

1 John 2002-09-09

2 Hannah 2000-08-07

Example 3

(Inserting multiple records);


INSERT INTO Employee VALUES(3, ’Jim’, ‘2001-07-06’),
(4, ‘Jeffer’, ‘1999-09-02’);

empId empName empDOB

1 John 2002-09-09

2 Hannah 2000-08-07

3 Jim 2001-07-06

4 Jeffer 1999-09-02

13 MySQL CheatSheet
2. UPDATE

Used to modify existing data(row) of a table.

Syntax

UPDATE tableName SET col1Name= newCol1Val, col2Name= newCol2Val, .. WHERE conditions;

Example 1

(Updating Single Column):


UPDATE Employee SET empName = ‘Jimmy’ WHERE empId = 3;

empId empName empDOB

1 John 2002-09-09

2 Hannah 2000-08-07

3 Jimmy 2001-07-06

4 Jeffer 1999-09-02

Example 2

UPDATE Employee SET empName = ‘Jiya’, empDOB = ‘2000-09-08’ WHERE empId = 4;

14 MySQL CheatSheet
empId empName empDOB

1 John 2002-09-09

2 Hannah 2000-08-07

3 Jimmy 2001-07-06

4 Jiya 2000-09-08

3. DELETE

Used to delete existing data from the table.

Syntax 1 Example 1

DELETE FROM tableName WHERE condition;


DELETE FROM Employee where empId = 4;

empId empName empDOB empId empName empDOB

1 John 2002-09-09 1 John 2002-09-09

2 Hannah 2000-08-07 2 Hannah 2000-08-07

3 Jimmy 2001-07-06 3 Jimmy 2001-07-06

4 Jiya 2000-09-08

Example 2(Deleting all the data(rows) of the table)

DELETE FROM Employee;

15 MySQL CheatSheet
empId empName empDOB

1 John 2002-09-09
empId empName empDOB
2 Hannah 2000-08-07

3 Jimmy 2001-07-06

4 Jiya 2000-09-08

05 DQL Command(SELECT)

empId empName empDOB

1 John 2002-09-09

2 Hannah 2000-08-07

3 Jimmy 2001-07-06

4 Jiya 2000-09-08

1. SELECT

Used to fetch data from the table.

Syntax

SELECT col1Name, col2Name, .. FROM tableName WHERE condition;

16 MySQL CheatSheet
2. FETCHING ALL Data

‘*’ is used to fetch all the data of the table.

Syntax Example

SELECT * FROM tableName;


SELECT * FROM Employee;

empId empName empDOB

1 John 2002-09-09

2 Hannah 2000-08-07

3 Jimmy 2001-07-06

4 Jiya 2000-09-08

3. SELECTING ALL COLUMNS

Syntax

SELECT col1Name, col2Name, .. FROM tableName;

Example

SELECT empId, empName, empDOB FROM Employee;

17 MySQL CheatSheet
empId empName empDOB

1 John 2002-09-09

2 Hannah 2000-08-07

3 Jimmy 2001-07-06

4 Jiya 2000-09-08

4. SELECTING SOME COLUMNS

Syntax

SELECT col1Name, col2Name, .. FROM tableName;


empId empName

1 John

Example 2 Hannah

3 Jimmy

SELECT empId, empName FROM Employee; 4 Jiya

5. USING AS ALIAS

Used to give a temporary name for the table or column.

Example

SELECT empId as Employee_Id, empName as Employee_Name FROM Employee;

18 MySQL CheatSheet
Employee_Id Employee_Name

1 John

2 Hannah

3 Jimmy

4 Jiya

6. USING WHERE

Used to specify condition for fetching data.

Syntax

SELECT col1Name, col2Name, .. FROM tableName WHERE condition;

Example

SELECT empId, empName FROM Employee where empId = 1;

empId empName

1 John

19 MySQL CheatSheet
06 Other commands

TCL Commands DCL Commands

Can used with insert, update and delete command only. Used to grant and takeback permissions from the user.

COMMIT GRANT
Save the transaction to the database Gives privileges to the user.
Syntax: COMMIT; Syntax: GRANT SELECT, UPDATE ON tableName
TO someUser, anotherUser;

ROLLBACK REVOKE
Used to undo the transactions that are not saved in
Takeback privileges from the user
the database
Syntax: REVOKE SELECT, UPDATE ON tableName
Syntax: ROLLBACK; FROM user1, user2;

SAVEPOINT
Used to rollback transactions to certain point instead
of rollback complete transaction
Syntax: SAVEPOINT savepointName;

07 Subqueries / Complex Queries


Employee Manager

empId empName empSal empDept mrgId mrgName mrgSal

1 John 2300 CSE 1 Steve 2400

2 Hannah 2100 CSE 2 Jim 2200

3 Herry 2500 ECE 3 Alia 2300

20 MySQL CheatSheet
1. Subqueries
• Query inside query • Can be used with HAVING, WHERE,
• Enclosed in parenthesis. SELECT and FROM clause.

2. ALL Keyword

• Returns Boolean result.


• Returns true if all the subquery values meets the specified condition.
• Can be used with HAVING, WHERE and SELECT clause.

Syntax(With WHERE)

SELECT columnName(s) from tableName WHERE columnName comparison_operator ALL


(SELECT columnName from tableName where condition(s));

Example(With WHERE and HAVING Clause)

SELECT empId, empName, empSal FROM Employee


WHERE empSal > ALL (SELECT mgrSal from Manager);

empId empName empSal

3 Herry 2500

Syntax(With HAVING)

SELECT columnName(s) from tableName HAVING columnName comparison_operator ALL


(SELECT columnName from tableName where condition(s));

21 MySQL CheatSheet
Example(With WHERE and HAVING Clause)

SELECT empId, empName, empSal FROM Employee


HAVING empSal > ALL (SELECT avg(mgrSal) from Manager);

empId empName empSal

3 Herry 2500

Syntax(with SELECT Clause)

SELECT ALL columnName(s) from tableName;

Example(With WHERE and HAVING Clause)

SELECT ALL empId FROM Employee;

empId

22 MySQL CheatSheet
3. ANY Keyword

• Returns Boolean result.


• Returns true if any of the subquery value meets the specified condition.

Syntax

SELECT columnName(s) from tableName WHERE columnName comparison_operator


ANY (SELECT columnName from tableName where condition(s));

Example

SELECT empId, empName, empSal FROM Employee WHERE empSal > ANY
(SELECT mgrSal from Manager);

empId empName empSal

1 John 2300

3 Herry 2500

4. CORRELATED SUBQUERY

• A subquery in which inner query is dependent on outer query for its execution.
• The inner query executes for every selected record of the outer query.

23 MySQL CheatSheet
Example

SELECT empId, empName, empSal FROM Employee E1 WHERE empSal >


(SELECT AVG(empSal) FROM Employee E2 WHERE E2.empDept = E1. empDept);

empId empName empSal

1 John 2300

5. EXISTS OPERATOR

• Checks existence of at least record in sub query.


• Returns true if subquery return one or more records.

Syntax

SELECT columnName1, columnName2, … FROM tableName WHERE EXISTS


(SELECT columnName FROM tableName WHERE condition);

Example

SELECT empId, empName, empSal FROM Employee WHERE EXISTS


(SELECT mgrSal FROM Manager AND Employee.empSal > mgrSal);

empId empName empSal

1 John 2300

3 Herry 2500

24 MySQL CheatSheet
6. SUBQUERY IN SELECT

• Subquery in select returns single row and single column


• Subquery in SELECT should be aliased.

Example

SELECT empId, empName, (SELECT avg(empSal) from Employee) as avgSal FROM Employee;

empId empName empSal

1 John 2300.0000

2 Hannah 2300.0000

3 Herry 2300.0000

7. SUBQUERY IN FROM

• Subquery in FROM should be aliased.

Example

SELECT * FROM (SELECT empId, empName, empSal FROM Employee) empDetails;

empId empName empSal

1 John 2300

2 Hannah 2100

3 Herry 2500

25 MySQL CheatSheet
08 Functions

PRODUCT
Id Name Price

1 Bag 12.76

2 Gloves 30.98

3 Pen 10.87

AGGREGATE FUNCTIONS

Operate on multiple rows and returns MIN() COUNT() MAX()


single row.

Aggregate functions

AVG() SUM()

SUM()

Return sum of values.

Syntax Example

SUM()
SELECT SUM(Price) FROM Product;

26 MySQL CheatSheet
SUM(Price)

54.61

MAX()

Return maximum value among all the values.

Syntax Example

MAX()
SELECT MAX(Price) FROM Product;

MAX(Price)

30.98

MIN()

Return minimum value among all the values.

Syntax Example

MIN()
SELECT MIN(Price) FROM Product;

MIN(Price)

10.87

27 MySQL CheatSheet
AVG()

Return averageof values.

Syntax Example

AVG()
SELECT AVERAGE(Price) FROM Product;

AVERAGE(Price)

18.203333333333333

COUNT()

Return number or rows.

Syntax Example

COUNT()
SELECT COUNT(Id) FROM Product;

COUNT(Id)

28 MySQL CheatSheet
SOME OTHER FUNCTIONS

NUMERIC FUNCTIONS CHARACTER FUNCTIONS

• ABS(VALUE): Returns absolute of value • UPPER(VALUE): Returns value after converting it

• ROUND(VALUE, DIGITS): Returns rounded value into upper case.

to the specified digits. • LOWER(VALUE): Returns value after converting it

• CEIL(VALUE): Returns ceil of value. into lowercase

• FLOOR(VALUE): Returns floor of value • CONCAT(VALUE1, VALUE2): Combines value1

and value2.

• LENGTH(VALUE): Returns length of value.

CONVERSION FUNCTION

• TO_CHAR(VALUE, FORMAT): Converts date/number to string.

• TO_DATE(VALUE, FORMAT): Converts string to date.

09 Some other Clauses


Student

Id Name Class Age

1 John I 7

2 Steve II 8

3 Jahanvi I 6

29 MySQL CheatSheet
1. ORDER BY Clause

Sorts rows in ascending/descending based on the specified column values.

Syntax

SELECT column1, column2, … FROM table_name WHERE condition GROUP BY column1,


column2, … HAVING condition ORDER BY column1, column2, … asc|desc;

Example

SELECT Id, Name, Age FROM Student ORDER BY Age;

Id Name Age

3 Jahanvi 6

1 John 7

2 Steve 8

2. GROUP BY Clause

Group rows on the basis of the value of the one or more specified columns.

Syntax

SELECT column1, column2, … FROM table_name WHERE condition GROUP BY column1,


column2, … ORDER BY column1, column2, …;

30 MySQL CheatSheet
Example

SELECT count(Id), Class FROM Student GROUP BY class;

Count(Id) Class

2 I

1 II

3. HAVING Clause

Used to apply condition on the rows grouped by the GROUP BY Clause.

Syntax

SELECT column1, column2, … FROM table_name WHERE condition GROUP BY column1,


column2, … HAVING condition ORDER BY column1, column2, …;

Example

SELECT count(id), class FROM Student GROUP BY class HAVING count(id)>1

Count(Id) Class

2 I

31 MySQL CheatSheet
4. DISTINCT Clause

Retrieves unique data and remove duplicate ones.

Syntax

SELECT DISTINCT column1, column2, … FROM table_name WHERE condition;

Example

SELECT DISTINCT class FROM Student;

Class

II

5. LIKE Clause

Used in WHERE clause for pattern matching( % -> zero or more characters, _ ->
single character)

Syntax

SELECT column1, column2, … FROM table_name WHERE columnName LIKE pattern;

32 MySQL CheatSheet
Example

SELECT Id, Name from Student WHERE Name LIKE ‘J%’;

Id Name

1 John

3 Jahanvi

Example

SELECT Id, Name from Student WHERE Name LIKE ‘J_hn’;

Id Name

1 John

10 Combining tables

UNION JOIN

Used to combine data of two or more result sets of Join can combine the data of multiple tables.
SELECT Statement.

33 MySQL CheatSheet
Types of Join
SELF JOIN RIGHT JOIN FULL JOIN

CROSS JOIN INNER JOIN LEFT JOIN

Employee Manager

empId empName empSal mgrId mgrId mgrName mgrSal

1 John 2300 2 1 Steve 2400

2 Hannah 2100 NULL 2 Jim 2200

3 Herry 2500 1 3 Alia 2300

1. SELF JOIN

Joining table with itself.

Example

SELECT emp.empId, emp.empName, mgr.empId mgrId, mgr.empName mgrName


FROM Employee emp INNER JOIN Employee mgr ON emp.mgrId = mgr.empId;

empId empName mgrId mrgName

3 Herry 1 John

1 John 2 Hannah

34 MySQL CheatSheet
2. RIGHT JOIN

Returns all the records from the right table and matching record from left table.

Example

SELECT emp.empId, emp.empName, mgr.mgrId, mgr.mgrName FROM Employee


emp RIGHT OUTER JOIN Manager mgr ON emp.mgrId = mgr.mgrId;

empId empName mgrId mrgName

3 Herry 1 Steve

1 John 2 Jim

NULL NULL 3 Alia

3. LEFT JOIN

Returns all the records from the lefttable and matching record from right table.

Example

SELECT emp.empId, emp.empName, mgr.mgrId, mgr.mgrName FROM Employee


emp LEFT OUTER JOIN Manager mgr ON emp.mgrId = mgr.mgrId;

empId empName mgrId mrgName

1 John 2 Jin

2 Hannah NULL NULL

3 Herry 1 Steve

35 MySQL CheatSheet
4. FULL JOIN

Returns matched as well as unmatched records of both the table.

Example

SELECT emp.empId, emp.empName, mgr.mgrId, mgr.mgrName FROM Employee emp


LEFT OUTER JOIN Manager mgr ON emp.mgrId = mgr.mgrId
UNION
SELECT emp.empId, emp.empName, mgr.mgrId, mgr.mgrName FROM Employee emp
RIGHT OUTER JOIN Manager mgr ON emp.mgrId = mgr.mgrId;

empId empName mgrId mrgName

1 John 2 Jim

2 Hannah NULL NULL

3 Herry 1 Steve

NULL NULL 3 Alia

5. CROSS JOIN

Combines each row from first table with each row each row of second table.

Example

SELECT emp.empId, emp.empName, mgr.mgrId, mgr.mgrName FROM Employee


emp CROSS JOIN Manager mgr;

36 MySQL CheatSheet
empId empName mgrId mrgName

3 Herry 1 Steve

2 Hannah 1 Steve

1 John 1 Steve

3 Herry 2 Jim

2 Hannah 2 Jim

1 John 2 Jim

3 Herry 3 Alia

2 Hannah 3 Alia

1 John 3 Alia

6. INNER JOIN

Returns matching record of both the tables.

Example

SELECT emp.empId, emp.empName, mgr.mgrId, mgr.mgrName FROM Employee


emp INNER JOIN Manager mgr ON emp.mgrId = mgr.mgrId;

empId empName mgrId mrgName

3 Herry 1 Steve

1 John 2 Jim

37 MySQL CheatSheet
11 Transactions

Introduction to Transactions Transactions - ACID Properties

Atomicity: Either complete transaction


• Transaction is a logical unit of one or more SQL

Statements.
A executes or none.

• All Statements of a transaction will execute in


Integrity: Transaction executes independently
atomic manner.
I
Transaction
Commit succeeded Consistency: Transaction must move database
Begin
Transaction C from one consistent state to another

Rollback Transaction
failed Durability: Transaction is permanently saved
D after commit, changes not lost even in system
failure.

Commit Rollback

Save all the transaction operations to the database. Used to undo the transactions that are not saved in
the database

38 MySQL CheatSheet

You might also like