title | description | created | updated |
---|---|---|---|
My SQL |
MySQL cheatsheet contains most commonly used commands which are helpful while working with MySQL. |
2020-05-28 |
2020-05-28 |
mysql -u [username] -p [database];
- To exit from mysql command-line client
exit;
system clear;
CREATE DATABASE [IF NOT EXISTS] db_name;
USE db_name;
DROP DATABASE [IF EXISTS] db_name;
SHOW DATABASE;
SHOW TABLES;
- To Create a new Table in database
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
....);
- ALTER is used to add, delete, or modify columns in an existing table.
ALTER TABLE Table_name ADD column_name datatype;
- TRUNCATE removes all rows from a table
TRUNCATE table table_name;
- DROP statement destroys the objects like an existing database, table, index, or view.
DROP TABLE table_name;
RENAME TABLE table_name1 to new_table_name1;
--Line1;
/* Line1,
Line2 */
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
Note: Column names are optional.
SELECT column1, column2, ...
FROM table_name
[where condition];
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
DELETE FROM table_name where condition;
- It is used to give access to users to the database
GRANT privileges ON object TO user;
- It is used to remove the granted permissions
REVOKE privileges ON object FROM user;
- It is used for storing the changes made by the user.
COMMIT;
- Used for reverting changes of the transaction
ROLLBACK;
- Marking a point of transaction to which easy rollback is possible.
SAVEPOINT savepoint_name;
ROLLBACK TO savepoint_name;
How to delete a savepoint:
RELEASE SAVEPOINT savepoint_name;
CREATE INDEX index_name on table_name(column_name);
- To Create Unique index:
CREATE UNIQUE INDEX index_name on table_name(column_name);
DROP INDEX index_name ON table_name;
Creating a View:
CREATE VIEW View_name AS
Query;
SELECT * FROM View_name;
ALTER View View_name AS
Query;
DROP VIEW View_name;
CREATE TRIGGER trigger_name trigger_time trigger_event
ON tbl_name FOR EACH ROW [trigger_order] trigger_body
/* where
trigger_time: { BEFORE | AFTER }
trigger_event: { INSERT | UPDATE | DELETE }
trigger_order: { FOLLOWS | PRECEDES } */
DROP TRIGGER [IF EXISTS] trigger_name;
SHOW TRIGGERS;
SHOW TRIGGERS LIKE pattern;
CREATE PROCEDURE sp_name(p1 datatype)
BEGIN
/*Stored procedure code*/
END;
CALL sp_name;
DROP PROCEDURE sp_name;
SELECT * FROM TABLE1 INNER JOIN TABLE2 where condition;
SELECT * FROM TABLE1 LEFT JOIN TABLE2 ON condition;
SELECT * FROM TABLE1 RIGHT JOIN TABLE2 ON condition;
SELECT select_list from TABLE1 CROSS JOIN TABLE2;
When an MYSQL statement is processed, a memory area is created known as context area. A cursor is a pointer to this context area.
Explict cursors are used when you are exceuting a SELECT statement query that will return more than one row.
DECLARE cursor_name CURSOR FOR SELECT_statement;
OPEN cursor_name;
FETCH cursor_name INTO variables list;
CLOSE cursor_name;