Yogesh Tyagi
@ytyagi782
All-In-one
SQL Cheatsheet
Commands, Syntax, and
Examples for Every Scenario
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
DML Commands
Data Manipulation Language
Command Description Syntax Example
The SELECT command SELECT column1,
SELECT first_name,
SELECT retrieves data from a column2 FROM
last_name FROM customers;
database. table_name ;
INSERT INTO
The INSERT command table_nane INSERT INTO customers
INSERT adds new records to a (column, column2) (first_name, last_name
table. VALUES VALUES (‘Mary’, ‘Doe’);
(value1, value2);
The UPDATE Command UPDATE table_name
UPDATE employees SET
is Used to modify SET column1 = value1,
UPDATE employee_name ='John Doe',
existing records in a column2=value2
department = 'Marketing’ ;
table. WHERE condition;
DELETE FROM employees
The DELETE command DELETE FROM
WHERE
DELETE removes records from tabte_name WHERE
employee_name = 'John Doe'
a table. condition;
;
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
DDL Commands
Data Definition Language
Command Description Syntax Example
CREATE TABLE emptoyees (
employee_id INT
The CREATE command
CREATE TABLE PRIMARY KEY,
creates a new database
table_name first_name
CREATE and objects, such as a
(column1 datatype1, VARCHAR(59) ,
table, index, view, or
column2 datatype2, last _ name
stored procedure.
VARCHAR(59) ,
age INT );
The ALTER command
ALTER TABLE tane_name
adds, deletes, or ALTER TABLE customers ADO
ALTER ADD column _ name
modifies columns in email VARCHAR(100);
datatype;
an existing table.
The DROP command is
DROP used to drop an existing DROP TABLE table_name; DROP TABLE customers;
table in a database.
The TRUNCATE command
iS used to delete the data TRUNCATE TABLE TRUNCATE TABLE
TRUNCATE
inside a table, but not the table_name; customers;
table itself.
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
DCL Commands
Data Control Language
Command Description Syntax Example
The GRANT command
GRANT SELECT, INSERT ON
is used to give specific GRANT SELECT, INSERT ON
GRANT table_name TO
privileges to users employees TO 'John Doe' ;
user_nane;
or roles.
The REVOKE command is
REVOKE SELECT, INSERT ON REVOKE SELECT, INSERT
used to take away
REVOKE table_name FROM ON employees FROM
privileges previously
user_name ; ‘John Doe' ;
granted to used or roles
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
Querying Data
Commands
Command Description Syntax Example
The SELECT statement is the
SELECT primary command used to SELECT column1, column2 SELECT first_name,
Statement retrieve data from a FROM table_name; last_name FROM customers;
database
The WHERE clause is used to
WHERE SELECT * FROM table_name SELECT * FROM customers
filter rows based on a
Clause WHERE condition; WHERE age > 30;
specified condition.
The ORDER BY clause is
used to sort the result set in SELECT * FROM table_name
ORDER BY , SELECT * FROM products
ascending or descending ORDER BY column_name
Clause ORDER BY price DESC;
order based on a specified ASC| DESC;
column.
The GROUP BY clause
groups rows based on the SELECT column_name,
SELECT category, COUNT(*)
GROUP BY values in a specified COUNT(*)FROM
FROM products GROUP BY
Clause column. It is often used with tabte_name
category;
aggregate functions like GROUP BY column_name;
COUNT, SUM, AVG. etc.
SELECT column_name,
SELECT category, COUNT(*)
The HAVING clause filters COUNT (*) FROM
HAVING FROM products GROUP BY
grouped results based on a table_name
Clause category HAVING
specified condition. GROUP BY column_name
COUNT(*)>5;
HAVING condition;
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
Joining Commands
Command Description Syntax Example
SELECT * FROM table1 SELECT * FROM employees
The INNER JOIN command
INNER JOIN table2 ON INNER JOIN departments ON
INNER JOIN returns rows with matching values
table1. column employees.department_id =
in both tables.
table2. column ; departments.id;
The LEFT JOIN command
LEFT returns all rows from the left table
SELECT * FROM table1 LEFT SELECT * FROM employees LEFT
JOIN table2 ON JOIN departments ON
JOIN/LEFT (first table) and the matching
table1.column employees.department_id =
rows from the right table (second
OUTER JOIN table),
table2. cotumn; departments.id;
The RIGHT JOIN command SELECT *
RIGHT JOIN/ returns all rows from the right
SELECT * FROM table1
FROM employees
RIGHT JOIN table2 ON
RIGHT OUTER table (second table) and the
table1.column
RIGHT JOIN departments
matching rows from the left ON employees.department_id =
JOIN table (first table),
table2.column ;
departments.department_id
SELECT * FROM employees
LEFT JOIN departments ON
FULL JOIN/ The FULL JOIN command SELECT * FROM table1 FULL
employees.employee _ id=
returns all rows when there is a JOIN tabte2 ON
FULL OUTER match in either the left table or table1. column=
departments.employee_id UNION SELECT *
FROM employees RIGHT JOIN departments
JOIN the right table. table2.coIumn;
ON employees. employee_id=
departments.employee-id;
The CROSS JOIN command
combines every row from the
SELECT FROM table1 SELECT * FROM employees
CROSS JOIN first table With every row from
CROSS JOIN table2; CROSS JOIN departments;
the second table, creating a
Cartesian product.
SELECT * FROM employees t1,
SELECT FROM table1 t1,
The SELF JOIN command joins employees t2
SELF JOIN a table with itself.
tablel t2 WHERE t1.column
WHERE t1. employee_id
t2.column;
t2.employee_id;
NATURAL The NATURAL JOIN command
SELECT * FROM table1 SELECT * FROM employees
matches columns with the
NATURAL JOIN table2; NATURAL JOIN departments;
JOIN same name in both tables.
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
Subqueries in SQL
Command Description Syntax Example
The IN command is used
to determine whether a
SELECT column(s) SELECT * FROM customers
value matches any
IN tatte WHERE value IN WHERE city IN (SELECT
value in a subquery
(subquery) ; city FROM suppliers) ;
result. It is often used in
the WHERE clause.
The ANY command is
used to compare a value SELECT * FROM products
SELECT column(s) FROM
to any value returned by WHERE price < ANY (SELECT
ANY table WHERE value < ANY
a subquery. It can be unit_price FROM
(subquery) ;
used with comparison supplier_products) ;
operators like =, >, <, etc.
The ALL command iS
used to compare a value SELECT * FROM orders
SELECT column(s) FROM
to all values returned by WHERE order_amount >ALL
ALL table WHERE value > ALL
a subquery. It can be (SELECT total_amount
(subquery) ;
used with comparison FROM previous_orders) ;
operators like =, >, <, etc.
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
Aggregate Functions
Commands
Command Description Syntax Example
The COUNT command
SELECT SELECT COUNT(age)
counts the number of
COUNT() COUNT(column_name) FROM
rows or non-null values
FROM table_name; employees ;
in a specified column.
The SUM command is
SELECT
used to calculate the SELECT sum(revenue)
SUM() SUM(column_name)
sum of all values in a FROM sales;
FROM table_nane;
specified column.
The AVG command is
used to calculate the SELECT
SELECT AVG(price) FROM
AVG() average (mean) of all AVG(column_name)
products ;
values in a specified FROM table_name;
column,
The MIN command
SELECT
returns the minimum SELECT MIN(price) FROM
MIN() MIN(column_name)
(lowest) value in a products;
FRON table_name;
specified column.
The MAX command
SELECT
retums the maximum SELECT MAX(price) FROM
MAX() MAX(column_name)
(highest) value in a products;
FROM table_name;
specified column.
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
String Functions In SQL
Command Description Syntax Example
The CONCAT command SELECT CONCAT(string1, string2, ) SELECT CONCAT( first_name,
CONCAT() concatenates two or more AS concatenated_string FROM ‘ ‘ , last_name) AS full_name
strings into a single string. table_name; FROM employees;
SELECT SUBSTRING(string SELECT
SUBSTRING()/ The SUBSTRING command FROM start_position [FOR SUBSTRING(product-name
LENGTH() extracts a substring from a string. Length]) AS substring FROM 1 FOR 5) AS
FROM table_name; substring FROM products;
The LENGTH command returns the SELECT SELECT
CHAR_LENGTH()
length (number of characters) of a CHAR_LENGTH(String) AS CHAR_LENGTH(product_name)
/ LENGTH() string length FROM table_name; AS length FROM products;
SELECT UPPER(string) AS SELECT UPPER(first_name)
The UPPER command converts all
UPPER() characters in a string to uppercase.
uppercase_string FROM AS uppercase_first_name
table_name ; FROM employees;
SELECT LOWER(string) AS SELECT LOWER(last_name)
The LOWER command converts all
LOWER() characters in a string to lowercase.
lowercase_string FROM AS lowercase_last_name
table_name; FROM emptoyees;
The TRIM command removes SELECT TRIM([LEADING | TRAILING I SELECT TRIM(TRAILING
specified prefixes or suffixes (or BOTH] characters FROM string) FROM full_name) AS
TRIM() whitespace by default) from a AS trimmed_string FROM trimmed_full_name FROM
string. table_name; customers ;
SELECT
The LEFT command returns a SELECT LEFT(string,
LEFT (product_name, 5)
LEFT() specified number of characters num_characters) AS left_string
AS left_product_name
from the left of a string. FROM table_name;
FROM products;
SELECT
The RIGHT command returns a SELECT RIGHT(string,
RIGHT (order_number, 4) AS
RIGHT() specified number of characters num_characters) AS
right_order_number FROM
from the right of a string. right_string FROM table_name ;
orders ;
SELECT
SELECT REPLACE (string,
The REPLACE command REPLACE (description, 'old_string’ ,
Old_substring , new_substring) AS
REPLACE() replaces occurrences of a
replaced_string FROM table-
'new_string') AS
substring within a string, replaced_description FROM
name;
product_descriptions ;
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
Date and Time SQL Commands
Command Description Syntax Example
The CURRENT_DATE command SELECT CURRENT_DATE() AS
CURRENT_DATE()
returns the current date. current_date;
The CURRENT_TIME command SELECT CURRENT_TIME() AS
CURRENT_TIME()
returns the current time. current_time;
The CURRENT_TIMESTAMP SELECT
CURRENT_
command returns the current CURRENT_TIMESTAMP() AS
TIMESTAMP()
date and time. current_timestamp;
The DATE_PART command
SELECT DATE_PART(‘part', SELECT DATE_PART(‘year’, '2024
extracts a specific part (e.g.,
DATE_PART() date_expression) AS -04-11') AS
year, month, day) from a date or
extracted_part; extracted_part ;
time.
DATE_ADD Example
SELECT
DATE_ADD(‘2024-04-11’ , INTERVAL
The DATE_ADD command adds
SELECT 1 DAY) AS new_date;
DATE_ADD()/ or subtracts a specified number
DATE_ADD (date_expression ,
DATE_SUB() of days, months, or years
INTERVAL value unit) AS new_date ; DATE_SUB Example
to/from a date.
SELECT
DATE_SUB(‘2024-04-11’ INTERVAL 1
DAY) AS new_date;
The EXTRACT command
SELECT EXTRACT(YEAR FROM
extracts a specific part (e.g., SELECT EXTRACT (part FROM
EXTRACT() year, month, day) from a date or date_expression) AS extracted_part;
'2024-04-11') AS
extracted_part ;
time.
SELECT
The TO_CHAR command SELECT
TO_CHAR(‘2024-04-11’,
TO_CHAR() converts a date or time to a TO_CHAR(date_expression,’format')
'YYYY-HH-DD') AS
specified format. AS formatted_date ;
formatted_date;
The TIMESTAMPDIFF command
calculates the difference SELECT SELECT TIMESTAMPDIFF(DAY,
TIMESTAMPDIFF() between two timestamps in a TIMESTAMPDIFF (unit, timestamp1, '2024-04-10' , '2024-04-11') AS
specified unit (e.g., days, hours, timestamp2) AS difference; difference ;
minutes).
SELECT
The DATEDIFF command
SELECT DATEDIFF(date1, DATEDIFF(' 2024-04-11' ,
DATEDIFF() calculates the difference in days
date2) AS difference _ in _ days; '2024-04-10') AS
between two dates.
difference_in_days;
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
Conditional Expressions
Command Description Syntax Example
SELECT SELECT
column1, order_id,
column2, total_amount,
CASE CASE
The CASE statement WHEN condition1 WHEN total_amount
CASE allows you to perform THEN result1 > 1000 THEN 'High Value Order’
Statment conditional logic within a WHEN condition2 WHEN total_amount
query. THEN result2 > 500 THEN ‘Medium value
ELSE Order’ Order’
default_result ELSE 'Low Value
END AS alias END AS order_Status
FROM table_name; FROM orders;
SELECT
name,
The IF function evaluates a SELECT IF (condition,
age ,
condition and returns a true_value,
IF Statement IF(age > 58, ‘Senior’ 'Junior')
value based on the false_value) AS alias
AS
evaluation. FROM table_name;
employee-category
FROM employees;
SELECT
SELECT
The COALESCE function COALESCE(first_name,
COALESCE() COALESCE(va1ue1,
returns the first non-null middle_name) AS
Function value2 , ) AS alias
value from a list of values. preferred_name
FROM table_name;
FROM employees;
The NULLIF function SELECT
SELECT NULLIF (total-amount,
NULLIF() returns null if two NULL IF (expression1,
discounted_amount) AS
Function specified expressions expression2) AS alias
diff_amount FROM orders;
are equal FROM table_name;
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
Set Operations
Command Description Syntax Example
SELECT column1,column
SELECT first_name, last-name
The UNION operator 2
FROM customers
combines the result sets FROM table1
UNION
UNION of two or more SELECT UNION
SELECT first_name, last _ name
statements into a single SELECT column1,
FROM employees;
result set. column2 FROM
table2;
SELECT column1,
cotumn2 FROM
SELECT first_name, last_name
The INTERSECT operator table1
FROM customers
returns the common rows INTERSECT
INTERSECT INTERSECT
that appear in both result SELECT
SELECT first_name, last-name
sets. column1, column2 FROM
FROM employees;
table2 ;
SELECT column1,
The EXCEPT operator SELECT first _ name, last_name
cotumn2 FROM
returns the distinct rows FROM customers
table1
EXCEPT from the left result set that EXCEPT
EXCEPT SELECT
are not present in the right SELECT first_name, last_name
column1, column2 FROM
result FROM employees;
table2 ;
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
Transaction Control Commands
Command Description Syntax Example
BEGIN TRANSACTION;
The COMMIT command is used to SQL statements and changes within the transaction
save all the changes made during INSERT INTO employees (name, age) VALUES ( 'Alice' , 30);
COMMIT the current transaction and make
COMMIT;
UPDATE products SET price = 25.00 WHERE category ='
them permanent, Electronics ;
COMMIT;
BEGIN TRANSACTION;
The ROLLBACK command is used SQL statements and changes within the transaction
to undo all the changes made INSERT INTO employees (name, age) VALUES ('Bob', 35)
ROLLBACK during the current transaction and
ROLLBACK;
UPDATE products SET price = 30.00 WHERE category
discard them. =‘Electronics ‘ ;
ROLLBACK;
BEGIN TRANSACTION;
INSERT INTO employees (name,age) VALUES(‘carol’, 28);
SAVEPOINT before_update;
UPDATE products SET price = 40.00 WHERE category
The SAVEPOINT command is used
SAVEPOINT =‘Electronics’ ;
SAVEPOINT to set a point within a transaction
savepoint_name; SAVEPOINT after_update;
to Which you can later roll back. DELETE FROM customers WHERE age > 60;
ROLLBACK TO before_update;
At this point, the DELETE is rolled back, UPDATE remains.
COMMIT;
BEGIN TRANSACTION;
INSERT INTO employees (name, age) VALUES (‘David’, 42);
SAVEPOINT before_update;
UPDATE products SET price = 50.00 WHERE
The ROLLBACK TO SAVEPOINT category=‘Electronics’ ;
ROLLBACK TO
ROLLBACK TO command is used to roll back to a SAVEPOINT after_update;
SAVEPOINT
DELETE FROM customers WHERE age > 60;
SAVE-POINT specific savepoint Within a
savepoint_name ;
transaction. Rollback to the savepoint before the update
ROLLBACK TO SAVEPOINT before_update;
At this point, the UPDATE is rolled back, but the INSERT
remains.
COMMIT;
BEGIN TRANSACTION;
The SET TRANSACTION command Set the isolation levet to READ COMMITTED
SET TRANSACTION SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
is used to configure properties for
SET [ISOLATION LEVEL SQL statements and Changes within the transaction
the current transaction, such as
TRANSACTION { READ COMMITTED INSERT INTO employees (name, age) VALUES (‘Emily’, 35);
isolation level and transaction UPDATE products SET price = 60.00 WHERE category
$ERIALIZABLE}]
mode. =‘Electronics ;
COMMIT;
https://www.linkedin.com/in/ytyagi782/
Yogesh Tyagi
@ytyagi782
Follow for More