SQL Cheat Sheet ? – Your Ultimate Guide to Querying Data!
SQL Cheat Sheet ? – Your Ultimate Guide to Querying Data!
What is MySQL?
MySQL is currently the most popular database management system
software used for managing the relational database. It is open-
source database software, which is supported by Oracle
Company. It is fast, scalable, and easy to use database
management system in comparison with Microsoft SQL Server
and Oracle Database. It is commonly used in conjunction
with PHP scripts for creating powerful and dynamic server-side
or web-based enterprise applications.
It is developed, marketed, and supported by MySQL AB, a Swedish
company, and written in C programming language and C++
programming language. The official pronunciation of MySQL is
not the My Sequel; it is My Ess Que Ell. However, you can
pronounce it in your way. Many small and big companies use
MySQL. MySQL supports many Operating Systems
like Windows, Linux, MacOS, etc. with C, C++, and Java
languages.
MySQL is a Relational Database Management System (RDBMS)
software that provides many things, which are as follows:
o It allows us to implement database operations on tables, rows,
columns, and indexes.
o It defines the database relationship in the form of tables
(collection of rows and columns), also known as relations.
o It provides the Referential Integrity between rows or columns of
various tables.
o It allows us to updates the table indexes automatically.
o It uses many SQL queries and combines useful information fr om
multiple tables for the end-users
The acronym CRUD refers to all of the major functions that need
to be implemented in a relational database application to consider
it complete. Each letter in the acronym can be mapped to a
standard SQL statement:
Operation SQ Description
L
Create INSERT INTO inserts new data
into a database
Read (Retrieve) SELECT extracts data from a
database
Update UPDATE updates data in a database
Delete (Destroy) DELETE deletes data from a
database
To show databases:
SHOW DATABASES;
To use databases:
USE emplyeedb;
CREATE TABLE
The CREATE TABLE statement is used to create a table in a database.
Syntax:
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
e.g
1. UPDATE trainer
2. SET email = '[email protected]'
3. WHERE course_name = 'Java';
SELECT DISTINCT
select <column_names>
Example:
Operators
With the WHERE clause, the following operators can be used:
Operat Description
or
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETW Between an inclusive range
EEN
LIKE Search for a pattern
IN If you know the exact value you want to return for at least
one of the columns
Examples:
LIKE Operator
SELECT column_name(s)
Example:
IN Operator
SELECT column_name(s)
BETWEEN Operator
Syntax:
SELECT column_name(s)
Alias
SELECT column_name(s)
MySQL Constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE
TABLE statement) or after the table is created (with the ALTER TABLE
statement).
Here are the most important constraints:
PRIMARY KEY
NOT NULL
UNIQUE
FOREIGN KEY
CHECK
DEFAULT
IDENTITY
1)PRIMARY KEY
2)FOREIGN KEY
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
SCHOOL:
CLASS:
The NOT NULL constraint enforces a column to NOT accept NULL values.
4)UNIQUE
5)CHECK
The CHECK constraint is used to limit the value range that can be placed in
a column.
6)DEFAULT
ALTER TABLE
To change the data type of a column in a table, use the following syntax:
INSERT INTO
The INSERT INTO statement is used to insert a new row in a table. It is
possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be
inserted, only their values:
Example:
'California', '11111111')
The second form specifies both the column names and the values to be
inserted:
UPDATE
The UPDATE statement is used to update existing records in a table. The
syntax is as follows:
Syntax:
Views in SQL
o Views in SQL are considered as a virtual table. A view also contains
rows and columns.
o To create the view, we can select the fields from one or more tables
present in the database.
o A view can either have specific rows based on certain condition or all
the rows of a table.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can
create a view from a single table or multiple tables.
Syntax:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
MySQL JOIN
As the name shows, JOIN means to combine something. In case of
SQL, JOIN means "to combine two or more tables".
In MySQL, JOIN clause is used to combine the records from two or
more tables in a database.
Types of MySQL JOIN
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
Sample Table
EMPLOYEE
PROJECT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both
tables as long as the condition is satisfied. It returns the combination of
all rows from both the tables where the condition satisfies.
Syntax
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching
values from the right table. If there is no matching join value, it will
return NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the
rows of right table and the matched values from the left table. If there is
no matching in both tables, it will return NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right
outer join. Join tables have all the records from both tables. It puts
NULL on the place of matches not found.
Syntax
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
Views
Views are virtual table for easier access to data stored in multiple tables.
Syntax for creating a View:
SCHOOL.SchoolName,
1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database
table. It can work on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the
rows in a specified table. COUNT(*) considers duplicate and Null.
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
PRODUCT_MAST
Example: COUNT()
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
Example: COUNT with WHERE
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
7
Example: COUNT() with DISTINCT
1. SELECT COUNT(DISTINCT COMPANY)
2. FROM PRODUCT_MAST;
Output:
3
Example: COUNT() with GROUP BY
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
Example: COUNT() with HAVING
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670
Example: SUM() with WHERE
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
Example: SUM() with GROUP BY
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Example: SUM() with HAVING
1. SELECT COMPANY, SUM(COST)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;
Output:
Com1 335
Com3 170
3. AVG function
The AVG function is used to calculate the average value of the numeric type.
AVG function returns the average of all non-Null values.
Syntax
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This
function determines the largest value of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This
function determines the smallest value of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10
SET Operators in MySQL
SET operators are special type of operators which are used to combine the
result of two queries.
Operators covered under SET operators are:
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
There are certain rules which must be followed to perform operations using
SET operators in SQL. Rules are as follows:
1. The number and order of columns must be the same.
2. Data types must be compatible.
Let us see each of the SET operators in more detail with the help of examples.
All the examples will be written using the MySQL database.
Consider we have the following tables with the given data.
Table 1: t_employees
Table 2: t2_employees
Table 3: t_students
Table 4: t2_students
1. UNION:
o UNION will be used to combine the result of two select statements.
o Duplicate rows will be eliminated from the results obtained after
performing the UNION operation.
Example 1:
Write a query to perform union between the table t_employees and the table
t2_employees.
Query:
1. mysql> SELECT *FROM t_employees UNION SELECT *FROM t2_emp
loyees;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
a UNION operation with the records fetched by the second SELECT query
from the t2_employees table.
You will get the following output:
Since we have performed union operation between both the tables, so only
the records from the first and second table are displayed except for the
duplicate records.
Example 2:
Write a query to perform union between the table t_students and the table
t2_students.
Query:
1. mysql> SELECT *FROM t_students UNION SELECT *FROM t2_studen
ts;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_students table and perform a
UNION operation with the records fetched by the second SELECT query from
the t2_students table.
You will get the following output:
Since we have performed union operation between both the tables, so only
the records from the first and second table are displayed except for the
duplicate records.
2. UNION ALL
o This operator combines all the records from both the queries.
o Duplicate rows will be not be eliminated from the results obtained after
performing the UNION ALL operation.
Example 1:
Write a query to perform union all operation between the table t_employees
and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees UNION ALL SELECT *FROM t2
_employees;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
UNION ALL operation with the records fetched by the second SELECT query
from the t2_employees table.
You will get the following output:
Since we have performed union all operation between both the tables, so all
the records from the first and second table are displayed, including the
duplicate records.
Example 2:
Write a query to perform union all operation between the table t_students and
the table t2_students.
Query:
1. mysql> SELECT *FROM t_students UNION ALL SELECT *FROM t2_st
udents;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_students table and perform
UNION ALL operation with the records fetched by the second SELECT query
from the t2_students table.
You will get the following output:
ID Name Hometown Percentage Favourite_Subject
Since we have performed union all operation between both the tables, so all
the records from the first and second table are displayed, including the
duplicate records.
3. INTERSECT:
o It is used to combine two SELECT statements, but it only returns the
records which are common from both SELECT statements.
Example 1:
Write a query to perform intersect operation between the table t_employees
and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees INTERSECT SELECT *FROM t2
_employees;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
INTERSECT operation with the records fetched by the second SELECT query
from the t2_employees table.
You will get the following output:
Since we have performed intersect operation between both the tables, so only
the common records from both the tables are displayed.
Example 2:
Write a query to perform intersect operation between the table t_students and
the table t2_students.
Query:
1. mysql> SELECT *FROM t_students INTERSECT SELECT *FROM t2_s
tudents;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_students table and perform a
UNION operation with the records fetched by the second SELECT query from
the t2_students table.
You will get the following output:
ID Name Hometown Percentage Favourite_Subject
Since we have performed intersect operation between both the tables, so only
the common records from both the tables are displayed.
4. MINUS
o It displays the rows which are present in the first query but absent in the
second query with no duplicates.
Example 1:
Write a query to perform a minus operation between the table t_employees
and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees MINUS SELECT *FROM t2_emp
loyees;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
MINUS
operation with the records fetched by the second SELECT query from the
t2_employees table.
Since we have performed a minus operation between both the tables, so only
the Unmatched records from both the tables are displayed.
Triggers
6. After Delete: It is activated after the deletion of data from the table.
8. DELIMITER //
9. mysql> Create Trigger before_insert_empworkinghours
10. BEFORE INSERT ON employee FOR EACH ROW
11. BEGIN
12. IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;
13. END IF;
14. END //