You are on page 1of 6

#SQL Recap

#1. Connectinon
mysql -u username -h hostname -p password -P port [-e]
#2. Rights
#
MySQL database contains the user rights within the DBMS and are not depe
ndant on the OS
#
#
#
#
#
#
#

Rights scope
mysql.user - Global scope
mysql.db -Database scope
mysql.host - Host scope
mysql.tables_priv - Table scope
mysql.columns_priv - Column scope
mysql.procs_priv - Procedure scope
#1. Create users
CREATE USER 'username'@'hostname' IDENTIFIED BY 'password';
# 2. Grant access and usage
GRANT ALL PRIVILEGES
ON
database_name.table_name --(*.* / *)
TO
'username'@'hostname'
IDENTIFIED BY
(PASSWORD) -- expects password hash(md5/sha)
'password'
(WITH GRANT OPTION);
#full usage rights with optional permission to grant privileges

to other users
GRANT USAGE
ON
database_name.table_name --(*.* / *)
to
'username'@'hostname'
IDENTIFIED BY
(PASSWORD) -- expects password hash (md5/sha)
'password';
#provisions access to DBMS but to no database/table
#the access can be given using GRANT PRIVILEGES later on
# 3. Revoke access
REVOKE ALL PRIVILEGES
ON
database_name.table_name --(*.* / *)
FROM
'username'@'hostname';
#4. Remove usage

DROP USER 'username@hostname', 'username@hostname', 'username@ho


stname';
#executes FLUSH PRIVILEGES
#5. Passwords update/change
SET PASSWORD PASSWORD=PASSWORD('password');
#alternatively an UPDATE query on the users table
UPDATE mysql.user SET PASSWORD=PASSWORD('password') WHERE USER='
username' AND HOST='hostname';
FLUSH PRIVILEGES --removes loaded acces form memory after modifi
cations are made in the database
#3. Show commands
SELECT user(); --shows user
SELECT current_user(); --shows current user
SHOW GRANTS FOR 'username'; --show access rights for current logged in u
ser or a specific user
SHOW DATABASES; --shows all databases
SHOW CREATE DATABASE 'database_name'; --shows the statement for creating
the database
SHOW CHARACTER SET; --shows the character set supported by the current s
erver
SHOW TABLES; --list of tables in the current used database;
SHOW CREATE TABLE 'table_name' --shows the statement for creating the ta
ble
SHOW [COLUMNS || FIELDS] FROM 'table_name' --similar to describe
SHOW ENGINES; --shows the supported storage engines
SHOW INDEX FROM 'table_name';
\! -- runs shell commands
SHOW PROCESSLIST; -- shows current running processes. KILL can be used t
o terminate hogging processes
SHOW STATUS; --show current DBMS status
SHOW TABLE STATUS FROM 'database_name' [LIKE 'value to search %']; --sho
ws table details contained in the database
SHOW TRIGGERS FROM 'database_name' [LIKE 'value to search %']; --shows t
he defined triggers
SHOW PROCEDURE STATUS; --reveals stored procedures
SHOW FUNCTION STATUS; --reveals stored functions

#4. DML (Data Manipulation Language)


#1. Select
SELECT * FROM 'table_name'; --returns records for all the columns and ro
ws
SELECT 'column1','column2','columnn' FROM 'table_name'; --returns record
s for the specified columns and rows
SELECT * FROM 'table_name' WHERE 'column1' LIKE 'value%'; --search for p
atterns
SELECT * FROM 'table_name' WHERE 'column1'='value%'; --search for known
column value
SELECT * FROM 'table_name' ORDER BY 'column1','column2' [ASC | DESC]; -ordering the results based on columns
SELECT * FROM 'table_name' WHERE 'column1'='value' AND 'column2'='value'
; -- show contents filtered by AND condition
SELECT * FROM 'table_name' WHERE 'column1'='value' OR 'column2'='value';
--show contents filtered by OR condition
SELECT COUNT(*) FROM 'table_name'; -- select using COUNT function
SELECT * FROM 'table_name' LIMIT [3|5]; --returns records for all the co
lumns and limits the rows
SELECT * INTO OUTFILE 'filename' FROM 'table_name'; -- generates a file
in the database folder TAB delimited
SELECT * INTO OUTFILE 'filename' FIELDS DELIMITED BY ',' LINES DELIMITED
BY '\n' FROM 'table_name';
SELECT CONCAT('column1',' ','column2') AS 'column' FROM 'table_name'; -concatenation
SELECT CONCAT_WS(' ','column1','column2') AS 'column' FROM 'table_name';
--concatenation
#2. Insert
INSERT INTO 'table_name' ('column1', 'column2', 'columnn') VALUES ('val1
','val2','valn'); --insertion into table
INSERT INTO 'table_name' VALUES ('val1', 'val2', 'valn') --values must c
ontain all the necessary columns
INSERT INTO 'table_name' SET 'column1'='val1', 'column2'='val2'; --value
s for certain columns
INSERT INTO 'table_name' ('column1', 'column2', 'columnn') SELECT 'col1'
,'col2','coln') FROM 'table_name'; --values from select
#3. Update
UPDATE 'table_name' SET 'column'='val' [LIMIT x]; --updates all records
on the column, no condition applied
UPDATE 'table_name' SET 'column1'='val1', 'column2'='val2' WHERE 'column
3' [= | LIKE] 'value3'; -- update records with condition applied
#4. Delete
DELETE FROM 'table_name'; --removes all values form table
DELETE FROM 'table_name ' WHERE 'column1' [= | LIKE] 'val1' --removes re
cords with condition
#5. DDL (Data definition language)
#1. Alter
ALTER TABLE 'table_name' RENAME 'new_table_name'; --changes the table_na
me

ALTER TABLE 'table_name' ADD 'column' [/*describe column attributes*/] A


FTER 'column'; --adds column
ALTER TABLE 'table_name' DROP 'column'; --drops column
ALTER TABLE 'table_name' ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT, AD
D PRIMARY KEY (id);
ALTER TABLE 'table_name' MODIFY 'column' [/*describe column attributes*/
]
ALTER TABLE 'table_name' ADD UNIQUE ('column');
ALTER VIEW 'view_name' ('col1','col2') AS SELECT 'col1', 'col2' FROM 'ta
ble_name';
#2. Data types
#1. Numeric (UNSIGNED)
TINYINT -- 0-255 - 8-bit field;
SMALLINT -- 0-65535 - 16-bit field;
MEDIUMINT -- 0-16777215 - 24-bit field;
INT -- 0-4294967296 - 32-bit field;
BIGINT -- 0-18446744073709551616 - 64-bit field;
FLOAT -- up to 24 digits - 32-bit field - Single precisi
on
FLOAT -- up to 25-53 digits - 64-bit field - Double prec
ision
DOUBLE -- 64-bit - it executes rounding
DECIMAL(M,D) -- M=total number of digits before decimal
point, D=decimal points - 32/64-bites
BIT --based on binary values
#2. String
CHAR/NCAHR --255 character - 8-bit character lengths -IT TRUNCATES VALUES that are over the limit and removes trailing spaces
VARCHAR --16-bit field
TINYTEXT/TINYBLOB -- 255 characters - 8-bit
TEXT/BLOB -- 65535 - 16-bit
MEDIUMTEXT/MEDIUMBLOB -- 16777215 - 24-bit
LONGTEXT/LONGBLOB -- 4294967296 - 32-bit
BINARY(255)/VARBINARY(65535) --binary
ENUM(0-65535) --16-bits of elements
#3. Date and time
DATE --YYYY-MM-DD
DATETIME --YYYY-MM-DD HH:MM:SS
TIMESTAMP -- YYYY-MM-DD HH:MM:SS (1970-2037) -- timestam
p of last operation on record
YEAR --year
#Date rules years:
#2 digit 70-69 => 1970-2069
#4 digit 1901-2155
#3. Create
CREATE DATABASE IF NOT EXISTS 'database_name' CHARACTER SET = 'c
harset_name' COLLATE = 'collation_name'; --creates a database
CREATE TABLE IF NOT EXISTS 'table_name'(
'column' int(11) NOT NULL AUTO_INCREMENT,
'column2' varchar(20) default NULL UNIQUE,
'column3' enum('Y','N') default NOT NULL
'column3' decimal(7,2) default NOT NULL,
PRIMARY KEY ('column')
)ENGINE=MyISAM DEFAULT CHARSET='charset'; --creates a custom tab

le in the used database


CREATE TABLE IF NOT EXISTS 'table_name' LIKE 'old_table_name'; -creates a duplicate tabe structure in the used database
CREATE TEMPORARY TABLE IF NOT EXISTS 'table_name'(
'column' int(11) NOT NULL AUTO_INCREMENT,
'column2' varchar(20) default NULL UNIQUE,
'column3' enum('Y','N') default NOT NULL
'column3' decimal(7,2) default NOT NULL,
PRIMARY KEY ('column')
)ENGINE=MyISAM DEFAULT CHARSET='charset'; --creates a temporary
table in the used database
CREATE INDEX 'index_name' ON 'table_name' ('column1','column2','
columnn'); --up to 16 columns supported for MyISAM
CREATE VIEW 'view_name' ('col1','col2','col3') AS SELECT 'col1',
'col2', 'col3' FROM 'table_name';
CREATE OR REPLACE VIEW 'view_name' ('col1','col2') AS SELECT 'co
l1','col2' FROM 'table_name';
RENAME TABLE 'table_name' TO 'new_table_name','table_name' TO 'n
ew_table_name'; --renames a table
#4. DROP
#Hierarchy
#Database
#Tables
#Indexes
DROP
DROP
DROP
DROP
DROP
DROP
DROP

DATABASE 'database_name';
TABLE 'table_name';
INDEX 'index_name' ON 'table_name';
INDEX 'table_name.index_name' --MSSQL
TRIGGER 'trigger_name' ON 'table_name';
PROCEDURE 'proedure_name' ON 'table_name';
FUNCTION 'function_name' ON 'table_name';

#5. Triggers
#Single Trigger
CREATE TRIGGER 'trigger_name' 'trigger_time' 'trigger_event' ON 'table_n
ame' FOR EACH ROW 'trigger_statement';
--trigger_time = before/after
--trigger_event=insert/update/delete
--trigger_statement= standard SQL statement
#Multiple Trigger
DELIMITER |
CREATE TRIGGER 'trigger_name' 'trigger_time' 'trigger_event' ON
'table_name'
FOR EACH ROW BEGIN
'statement1';
'statement2';
'statement3';
END;|

DELIMITER ;
#6. Routines
#1. Stored procedures
--are associated with DB's not the entire DBMS
--implicitly execute 'use database_name'
CALL 'database_name.routine_name'();
CALL 'routine_name'('optional_parameters');
CREATE PROCEDURE 'procedure_name'(['proc_parameter',...]) SELECT
* FROM 'table_name';
CREATE PROCEDURE 'procedure_name' (OUT variable_name INT)
SELECT COUNT(*) INTO variable_name FROM 'table_name';
CALL 'database_name.procedure_name'(@total);
--proc_parameter= will accept [IN | OUT | INOUT variable_name va
riable_type]
#Execute multiple stored procedures
DELIMITER |
CREATE PROCEDURE 'database_name.procedure_name'()
BEGIN
SELECT COUNT(*) FROM 'table_name';
SELECT * FROM 'table_name';
END; |
DELIMITER;
#2. Functions
CREATE FUNCTION 'function_name' ('func_parameter[....]') RETURNS
'data_type'
RETURN 'function_operations';
CREATE FUNCTION stored_function_hello_world (arg1 CHAR(10)) RETU
RNS CHAR(20)
RETURN CONCAT('Hello ',arg1);
CREATE FUNCTION GET_AGE (arg1 date) RETURNS INT(2)
RETURN DATEDIFF(NOW(),arg1)/365;

You might also like