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

SQL Cheet Sheet

Uploaded by

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

SQL Cheet Sheet

Uploaded by

vanaja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

/** SQL CHEET SHEET **/

/**CREATE DATABASE DATABASE NAME **/

CREATE DATABASE myDB;

SHOW DATABASES;

USE myDB;

CREATE TABLE employee(Empid INT, first_name VARCHAR(25), last_name VARCHAR(25),hourlypay


DECIMAL(5,2), hiredate DATE);

SHOW TABLES;

ALTER TABLE employee ADD phoneno VARCHAR(15);

SELECT * FROM employee;

DESCRIBE employee;

ALTER TABLE employee RENAME COLUMN phoneno TO email;

ALTER TABLE employee MODIFY COLUMN email VARCHAR(50);

ALTER TABLE employee MODIFY email VARCHAR(50) AFTER last_name;

INSERT INTO employee

VALUES(1, "Ramu", "Ram", 10.00, "2022-03-02");

ALTER TABLE employee DROP COLUMN email;

ALTER TABLE employee ADD COLUMN job VARCHAR(25) AFTER hourlypay;

INSERT INTO employee

VALUES (2, "Simba", "Cat", 60.00, "2022-03-02"),

(3, "Charlie", "Cute", 70.00, "2024-03-01"),

(4, "Pintu", "Pin", 90.00, "2022-09-19"),

(5, "Tom", "Ram", 100.00, "2024-08-02"),

(6, "Jerry", "Ram", 40.00, "2022-03-02");


INSERT INTO employee (Empid, first_name, last_name)

VALUES(7, "Tiger", "Lion");

SELECT first_name,last_name FROM employee;

SELECT last_name,last_name FROM employee;

/** SQL is case insensitive both will retun the values **/

SELECT * FROM employee WHERE first_name="ramu";

SELECT * FROM employee WHERE first_name="Ramu";

/** logical operators **/

SELECT * FROM employee WHERE hourlypay >= 50;

SELECT * FROM employee WHERE hourlypay <= 50;

SELECT * FROM employee WHERE hourlypay != 50;

/** retreving by comaring to NULL **/

SELECT * FROM employee WHERE hourlypay IS NOT NULL;

SELECT * FROM employee WHERE hourlypay IS NULL;

/** UPDATING DATA **/

UPDATE employee SET hourlypay = 20.00 WHERE Empid=7;

UPDATE employee SET hourlypay = NULL WHERE Empid=7;


DELETE FROM employee;

DELETE FROM employee where Empid=6;

/** Auto commit commit and rollback , autocommit is on by default , if we set to off then we can revert
the check point

to save use COMMIT and when we rollback it will revert to the previous commit**/

COMMIT;

SET AUTOCOMMIT = OFF;

SELECT * FROM employee;

ROLLBACK;

/** getting cureent date and time **/

CREATE TABLE test(my_date DATE,my_time TIME,my_datetime DATETIME);

INSERT INTO test VALUES(CURRENT_DATE(), CURRENT_TIME(), NOW());

INSERT INTO test VALUES(CURRENT_DATE() + 1, CURRENT_TIME(),NOW());

SELECT * FROM test;

CREATE TABLE products ( pid INT, pname VARCHAR(40) UNIQUE,price DECIMAL(4,2));

CREATE TABLE products ( pid INT, pname VARCHAR(40) UNIQUE,price DECIMAL(4,2) DEFAULT 0.00);

ALTER TABLE products ALTER price SET DEFAULT 0;

SELECT * FROM products;

DESCRIBE products;

INSERT INTO products VALUES(100,"Icecream",10);

INSERT INTO products VALUES(100,"cookie",20);

ALTER TABLE products ADD CONSTRAINT UNIQUE(pname);

ALTER TABLE products MODIFY price DECIMAL(4,2) NOT NULL;

/* constraints CHECK , DEFAULT */


CREATE TABLE employee(Empid INT, first_name VARCHAR(25), last_name VARCHAR(25),hourlypay
DECIMAL(5,2), hiredate DATE, CONSTRAINT chk_pay CHECK(hourlypay >=10));

ALTER TABLE employee ADD CONSTRAINT chk_pay CHECK(hourlypay >=10);

INSERT INTO employee

VALUES (9, "Simba", "Cat", 12.00, "2022-03-02");

ALTER TABLE employee DROP CHECK chk_pay;

INSERT INTO products (pid,pname) VALUES(106,"chocolate");

INSERT INTO products VALUES (103,"straw",0.00) , (109,"papaer",0.00) , (102,"ketchup",0.00) ;

CREATE TABLE transactions( tid INT, amount DECIMAL(5,2), tdate DATETIME DEFAULT NOW());

INSERT INTO transactions (tid,amount) VALUES(101,23);

/* PRIMARY KEY */

CREATE TABLE transactions( tid INT PRIMARY KEY, amount DECIMAL(5,2), tdate DATETIME DEFAULT
NOW());

ALTER TABLE transactions ADD CONSTRAINT PRIMARY KEY(tid);

SELECT * FROM transactions;

DESCRIBE transactions;

DROP TABLE transactions;

/* auto increment by default pk is set to 1 and it will be auto incaremented*/

CREATE TABLE transactions( tid INT PRIMARY KEY AUTO_INCREMENT , amount DECIMAL(5,2), tdate
DATETIME DEFAULT NOW());

INSERT INTO transactions (amount) VALUES(23);

INSERT INTO transactions (amount) VALUES(232);

INSERT INTO transactions (amount) VALUES(645);

INSERT INTO transactions (amount) VALUES(34);


/* setting a value */

ALTER TABLE transactions AUTO_INCREMENT=1000;

CREATE TABLE transactions( tid INT PRIMARY KEY, amount DECIMAL(5,2), tdate DATETIME DEFAULT
NOW());

/* foreign key */

/* PK in one table used as a referene in another table , THERE WILL BE AL INK CREATED BTETWEEN 2
TABLES */

CREATE TABLE customers(cid INT PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(25),


last_name VARCHAR(25));

INSERT INTO customers (first_name, last_name)

VALUES("tom", "SC"),

("dick", "AN"),

("harry", "DE");

INSERT INTO customers (first_name, last_name)

VALUES("pintu", "SC");

SELECT * FROM customers;

CREATE TABLE transactions( tid INT PRIMARY KEY AUTO_INCREMENT , amount DECIMAL(5,2), cid INT,
FOREIGN KEY(cid) REFERENCES customers(cid));

/*ALTER TABLE transactions DROP CONSTRAINT FOREIGN KEY nameof key from ;*/

INSERT INTO transactions (amount, cid)

VALUES(36,2);

INSERT INTO transactions (amount, cid)

VALUES(13,NULL);

/**** JOINS */

/* INNER JOIN */

SELECT * FROM transactions JOIN customers ON transactions.cid = customers.cid;


SELECT * FROM transactions LEFT JOIN customers ON transactions.cid = customers.cid;

SELECT * FROM transactions RIGHT JOIN customers ON transactions.cid = customers.cid;

/* FUNCTIONS */

SELECT COUNT(tid) as Noof_transaction from transactions;

SELECT MIN(amount) as min_amount from transactions;

SELECT MAX(amount) as max_amount from transactions;

SELECT SUM(amount) as total_amount from transactions;

SELECT AVG(amount) as avg_amount from transactions;

SELECT CONCAT(first_name," ",last_name) as name from employee;

/* logical operators */

UPDATE employee SET job="cook" where Empid=7;

SELECT * FROM employee where hiredate > "2021-01-01" AND job="cook";

SELECT * FROM employee where job="cook" OR job="helper";

SELECT * FROM employee where hiredate > "2021-01-01" AND NOT job="cook";

SELECT * FROM employee where hiredate BETWEEN "2021-01-01" AND "2022-03-02";

SELECT * FROM employee where job IN ("cook" , "doctor");

/* matching wild card */

SELECT * FROM employee where first_name LIKE "s%"; /* starting from s*/

SELECT * FROM employee where first_name LIKE "%r";/* ending from r*/

SELECT * FROM employee where job LIKE "_ook"; /* looks for 1 character folloed by 1 letter */

SELECT * FROM employee where hiredate LIKE "____-03-__";

/* order by default ASC order/ null will be iaplayed first*/


SELECT * FROM employee ORDER BY first_name;

SELECT * FROM employee ORDER BY first_name DESC;

SELECT * FROM transactions ORDER BY amount,cid; /* null 1,2,3,4,*/

/* limit the no of records to be queries */

SELECT * FROM employee ORDER BY first_name DESC LIMIT 2, 3; /* skips first 2 records in reverse
order ,fetchs the record starting from 3 and display 3,4, and 5 records */

SELECT DISTINCT amount,cid from transactions ORDER BY amount DESC LIMIT 1,1; /* second largest
salary */

/* UNION operator combies the results of the 2 sSELECT * FROM transactions ORDER BY amount
DESC;elect statement UNION DOES NOT ALLOW DUPLICATES , UNIION ALLL DISPLAYES DUPLICATES

UNION needs number of columns to be same in both table */

SELECT * FROM transactions

UNION

SELECT * FROM customers ORDER BY tid;

SELECT * FROM transactions

UNION ALL

SELECT * FROM customers ORDER BY tid;

/* SELF JOIN join same table */

ALTER TABLE customers ADD refid INT;

SELECT * FROM customers;

UPDATE customers SET refid = 2 WHERE cid=3;

SELECT a.cid,a.first_name,a.last_name,b.first_name,b.last_name FROM customers AS a


INNER JOIN customers AS b ON a.refid = b.cid;

SELECT a.cid,a.first_name,a.last_name,b.first_name,b.last_name FROM customers AS a

LEFT JOIN customers AS b ON a.refid = b.cid;

SELECT * FROM employee ORDER BY first_name;

/**self join **/

SELECT a.fist_name,a.last_name, CONCAT(b.first_name," ",b.lastname) from employee a LEFT JOIN


employee as b on a.cid=b.cid;

-- views

-- views are virtul tables based on the result set of an SQL statemet

-- the fields are from the one or more real tables in the DB

-- they are not tabels, but can be interacted with as same as tables

-- if any changes to the mail table then the view gets automatically updated

SELECT * FROM employee;

-- CREATE VIEW view_name AS SELECT col1,col2,col3 from ORIGIONAL_TABLE_NAME;

CREATE VIEW ename AS SELECT first_name,last_name from employee;

SELECT * FROM ename ORDER BY last_name ASC;

-- DROP VIEW view_name;

DROP VIEW empnames;

SELECT * FROM customers;

ALTER TABLE customers ADD COLUMN email VARCHAR(50);

UPDATE customers SET email ='gmail' where cid= 1;


UPDATE customers SET email='gamil' where cid=2;

CREATE VIEW custemail AS SELECT email as cmail from customers;

SELECT * from custemail;

INSERT INTO customers (first_name,last_name,refid,email) VALUES('teddy','jerry',3,'hotmail');

-- INDEX(BTree Data Structure)

-- used to find values within specific column more quickly

-- MYSQL normally searches sequantially

-- The longer the column , the more expemnsive the operation is

-- drawback UPDATE takes more time .

-- advantage SELECT takes more time.

SELECT * FROM transactions;

-- CREATE INDEX indexname ON table_name(culumn_name);

-- multi column indexname ON table_name(culumn_name,col2);

CREATE INDEX lastname_idx ON customers(last_name);

CREATE INDEX name_idx ON customers(first_name,last_name);

-- list index

show INDEXES from customers;

SELECT * from customers where last_name ='tom';

-- droppping index

ALTER TABLE customers DROP INDEX lastname_idx;

-- sub queries

-- a query with in another query


SELECT AVG(hourlypay) FROM employee AS AvgPay;

SELECT first_name,last_name,hourlypay FROM employee;

SELECT first_name,last_name,hourlypay,(SELECT AVG(hourlypay) FROM employee )AS AvgPay FROM


employee;

SELECT first_name,last_name,hourlypay FROM employee WHERE hourlypay > ( SELECT AVG(hourlypay)


FROM employee AS AvgPay);

SELECT first_name,last_name from (SELECT DISTINCT cid FROM transactions WHERE cid IS NOT NULL);

SELECT first_name,last_name,hourlypay FROM employee WHERE hourlypay > ( SELECT AVG(hourlypay)


FROM employee AS AvgPay);

SELECT * FROM transactions WHERE cid IS NULL;

SELECT first_name,last_name FROM customers where cid IN ( SELECT cid FROM transactions WHERE
cid IS NOT NULL);

-- group by

-- aggregate the results based on some column name

-- ofetn used with aggregate function such as SUM(), MAX(), MIN (), AVG(),COUNT()

SELECT * FROM transactions WHERE cid IS NULL;

SELECT SUM(AMOUNT), cid FROM transactions GROUP BY cid;

-- rollup , extenstion of group by clause

-- produces another row and shows the GRAND TOTAL ( super - aggregate value)
SELECT SUM(AMOUNT), cid FROM transactions GROUP BY cid WITH ROLLUP ;

-- ON delete set null - when FK is deleted then replace with NULL

-- on delete cascade - when a FK is deleted then delete a row

-- check SET foreign_key_checks = 0 ; will allow to delete wvwn if there is a FK reference . 1 will not
allow to delete

DELETE FROM customers WHERE cid=4;

CREATE TABLE transactions( tid INT PRIMARY KEY AUTO_INCREMENT , amount DECIMAL(5,2), cid
INT, FOREIGN KEY(cid) REFERENCES customers(cid) ON DELETE SET NULL);

ALTER TABLE transactions ADD CONSTRAINT fk_cid FOREIGN KEY(cid) REFERENCES


customers(cid) ON DELETE SET NULL;

ALTER TABLE transactions ADD CONSTRAINT fk_cid FOREIGN KEY(cid) REFERENCES customers(cid)
ON DELETE CASCADE;

-- stored procedure

-- is a prepared SQL code that you can save if the query is used often .

-- reduces netwek traffic

-- increases perfromance

-- secure , admin can grant permission

-- disadvantage incarese memory usage of every connection

DELIMITER $$

CREATE PROCEDURE get_customers()

BEGIN

SELECT * FROM customers;

END $$
DELIMITER ;

CALL get_customers();

DROP PROCEDURE get_customers;

DELIMITER $$

CREATE PROCEDURE find_customer(IN id INT)

BEGIN

SELECT * FROM customers WHERE cid= id;

END $$

DELIMITER ;

CALL find_customer(2);

DELIMITER $$

CREATE PROCEDURE fname_customer(IN f_name VARCHAR(50), IN l_name VARCHAR(50))

BEGIN

SELECT * FROM customers WHERE first_name= f_name AND last_name=


l_name;

END $$

DELIMITER ;

CALL fname_customer("teddy","jerry");

-- TRIGGER - WHen an event happens do soemthing

CREATE TRIGGER pay_update

BEFORE UPDATE ON employee

FOR EACH ROW

SET NEW.hourlypay = ( NEW.hourlypay * 20);


CREATE TRIGGER job_update

BEFORE UPDATE ON employee

FOR EACH ROW

SET NEW.job = ("promoted");

SHOW TRIGGERS;

select * from employee;

UPDATE employee SET hourlypay= 20 WHERE Empid=1;

CREATE TRIGGER job_update

BEFORE UPDATE ON employee

FOR EACH ROW

SET NEW.job = ("promoted");

SHOW TRIGGERS;

UPDATE expenses SET EXPENSETOTAL = ( select sum(SALARY) FROM EMPLOYEE);

CREATE TRIGGER aftersalary_update

AFTER DELETE ON employee

FOR EACH ROW

UPDATE expenses

SET expensetotal = expensetotal - OLD.salary

WHERE expname = "salaries";

SHOW TRIGGERS;

CREATE TRIGGER aftersalary_update


AFTER INSERT ON employee

FOR EACH ROW

UPDATE expenses

SET expensetotal = expensetotal + NEW.salary

WHERE expname = "salaries";

CREATE TRIGGER aftersalary_update

AFTER UPDATE ON employee

FOR EACH ROW

UPDATE expenses

SET expensetotal = expensetotal + (NEW.salary - OLD.salary)

WHERE expname = "salaries"

You might also like