SQL Cheat Sheet
SQL Cheat Sheet
SQL Features
SQL allows us to interact with the databases and bring out/manipulate data within
them. Using SQL, we can create our own databases and then add data into these
databases in the form of tables.
To get started with using SQL, we first need to install some Database Management
System server. After installing the RDBMS, the RDBMS itself will provide all the
required tools to perform operations on the database and its contents through
SQL. Some common RDBMS which is highly in use are:
Oracle
MySQL
PostgreSQL
Heidi SQL
To install any RDBMS, we just need to visit their official website and install the
setup file from there, by following the instructions available there. With the server
setup, we can set up a Query Editor, on which we can type our SQL Queries.
2. Tables
All data in the database are organized efficiently in the form of tables. A database
can be formed from a collection of multiple tables, where each table would be used
for storing a particular kind of data and the table by themselves would be linked
with each other by using some relations.
Example:
The above example is for a table of students and stores their Name, Phone, and
Class as data. The ID is assigned to each student to uniquely identify each student
and using this ID, we can relate data from this table to other tables.
SQL-Create Table:
We use the CREATE command to create a table. The table in the above example can
be created with the following code:
SQL-Delete Table:
3. SQL DataTypes
To allow the users to work with tables effectively, SQL provides us with various
datatypes each of which can be useful based on the type of data we handle.
The above image is a chart that shows all the datatypes available in SQL along with
some of their examples.
The next section describes various most popular SQL server datatypes categorised
under each major division.
String Datatypes:
The table below lists all the String type datatypes available in SQL, along with their
descriptions:
Datatype Description
CHAR(size) A fixed-length string containing numbers, letters or special
characters. Length may vary from 0-255.
VARCHAR(size) Variable-length string where the length may vary from 0-65535.
Similar to CHAR.
TEXT(size) Can contain a string of size up to 65536 bytes.
TINY TEXT Can contain a string of up to 255 characters.
MEDIUM TEXT Can contain a string of up to 16777215 characters.
LONG TEXT Can contain a string of up to 4294967295 characters.
BINARY(size) Similar to CHAR() but stores binary byte strings.
VARBINARY(size) Similar to VARCHAR() but stores binary byte strings.
BLOB(size) Holds blobs up to 65536 bytes.
TINYBLOB It is used for Binary Large Objects and has a maximum size of
255bytes.
MEDIUMBLOB Holds blobs up to 16777215 bytes.
LONGBLOB Holds blobs upto 4294967295 bytes.
ENUM(val1,val2,…) String object that can have only 1 possible value from a list of
size at most 65536 values in an ENUM list. If no value is inserted,
a blank value is inserted.
SET(val1,val2,…) String object with 0 or more values, chosen from a list of
possible values with a maximum limit of 64 values.
Numeric Datatypes:
The table below lists all the Numeric Datatypes in SQL along with their descriptions:
Datatype Description
BIT(size) Bit-value type, where size varies from 1 to 64. Default value: 1
INT(size) Integer with values in the signed range of -2147483648 to
2147483647 and values in the unsigned range of 0 to
4294967295.
TINYINT(size) Integer with values in the signed range of -128 to 127 and values
in the unsigned range of 0 to 255.
SMALLINT(size) Integer with values in the signed range of -32768 to 32767 and
values in the unsigned range of 0 to 65535.
MEDIUMINT(size) Integer with values in the signed range of -8388608 to 8388607
and values in the unsigned range of 0 to 16777215.
BIGINT(size) Integer with values in the signed range of 9223372036854775808
to 9223372036854775807 and values in the unsigned range of 0
to 18446744073709551615.
BOOLEAN Boolean values where 0 is considered as FALSE and non-zero
Datatype Description
values are considered TRUE.
FLOAT (p) The floating-point number is stored. If the precision parameter is
set between 0 to 24, the type is FLOAT() else if it lies between 25
to 53, the datatype is DOUBLE().
DECIMAL(size,d) Decimal number with a number of digits before decimal place set
by size parameter, and a number of digits after the decimal point
set by d parameter. Default values: size = 10, d = 10. Maximum
Values: size = 65, d = 30.
Date/Time Datatypes:
Datatype Description
DATE Stores date in YYYY-MM-DD format with dates in the range of
‘1000-01-01’ to ‘9999-12-31’.
TIME(fsp) Stores time in hh:mm:ss format with times in the range of ‘-
838:59:59’ to ‘838:59:59’.
DATETIME(fsp) Stores a combination of date and time in YYYY-MM-DD and
hh:mm:ss format, with values in the range of ‘1000-01-01 00:00:00’
to ‘9999-12-31 23:59:59’.
TIMESTAMP(fsp) It stores values relative to the Unix Epoch, basically a Unix
Timestamp. Values lie in the range of ‘1970-01-01 00:00:01’ UTC to
‘2038-01-09 03:14:07’ UTC.
YEAR Stores values of years as a 4digit number format, with a range lying
between -1901 to 2155.
You can download a PDF version of Sql Cheat Sheet.
Download PDF
4. SQL Commands
SQL Commands are instructions that are used by the user to communicate with the
database, to perform specific tasks, functions and queries of data.
Example:
Example:
Example:
DROP TABLE STUDENT;
TRUNCATE: Used to delete all the rows from the table, and free up the
space in the table.
Example:
Example:
In the above example, we insert the values “Scaler” and “DSA” in the columns Name
and Subject in the STUDENT table.
Example:
UPDATE STUDENT
SET User_Name = 'Interviewbit'
WHERE Student_Id = '2'
In the above example, we update the name of the student, whose Student_ID is 2,
to the User_Name = “Interviewbit”.
Example:
In the above example, the query deletes the row where the Name of the student is
“Scaler” from the STUDENT table.
In the above example, we grant the rights to SELECT and UPDATE data from the
table TABLE_1 to users - USER_1 and USER_2.
Example:
In the above example we revoke the rights to SELECT and UPDATE data from the
table TABLE_1 from the users- USER_1 and USER_2.
Example:
In the above database, we delete the row where AGE of the students is 16, and then
save this change to the database using COMMIT.
ROLLBACK: It is used to undo transactions which are not yet been saved.
Example:
By using ROLLBACK in the above example, we can undo the deletion we performed
in the previous line of code, because the changes are not committed yet.
Example:
SAVEPOINT SAVED;
DELETE FROM STUDENTS
WHERE AGE = 16;
ROLLBACK TO SAVED;
In the above example, we have created a savepoint just before performing the
delete operation in the table, and then we can return to that savepoint using the
ROLLBACK TO command.
5. Data Query Language: It is used to fetch some data from a database. The
command belonging to this category is:
SELECT Name
FROM Student
WHERE age >= 18;
SELECT Name
FROM Student
In the first example, we will only select those names in the Student table, whose
corresponding age is greater than 17. In the 2nd example, we will select all the
names from the Student table.
5. SQL Constraints
Constraints are rules which are applied on a table. For example, specifying valid
limits or ranges on data in the table etc.
Example:
2. UNIQUE: Specifies that this column can have only Unique values, i.e the values
cannot be repeated in the column.
Example:
In the above example, we create a table Student and declare the ID column to be
unique using the UNIQUE constraint.
3. Primary Key: It is a field using which it is possible to uniquely identify each row
in a table. We will get to know about this in detail in the upcoming section.
4. Foreign Key: It is a field using which it is possible to uniquely identify each row
in some other table. We will get to know about this in detail in the upcoming
section.
Example:
Here, in the above query, we add the CHECK constraint into the table. By adding
the constraint, we can only insert entries that satisfy the condition AGE < 20 into
the table.
6. DEFAULT: It specifies a default value for a column when no value is specified for
that field.
Example:
In the above query, we set a default value of 2 for the CLASS attribute. While
inserting records into the table, if the column has no value specified, then 2 is
assigned to that column as the default value.
Create: INSERT
Read: SELECT
Update: UPDATE
Delete: DELETE
SQL Syntax:
SQL Syntax:
Example:
The above example will insert into the student table having the values 1, Scaler,
+1234-5678 and 12 to the columns ID, name, phone and class columns.
SQL Syntax:
Example:
The above example allows the user to read the data in the name and class columns
from the student table.
SQL Syntax:
UPDATE name_of_table
SET column1=value1,column2=value2,...
WHERE conditions...;
Example:
UPDATE customers
SET phone = '+1234-9876'
WHEREID = 2;
The above SQL example code will update the table ‘customers’ whose ID is 2 with
the new given phone number.
DELETE:
The Delete command is used to delete or remove some rows from a table. It is the
‘D’ component of CRUD.
SQL Syntax:
Example:
The above SQL example code will delete the row from table student, where the
class = 11 conditions becomes true.
The below table lists some important keywords used in SQL, along with their
description and example.
Clauses are in-built functions available in SQL and are used for filtering and
analysing data quickly allowing the user to efficiently extract the required
information from the database.
The below table lists some of the important SQL clauses and their description with
examples:
9. SQL Operators
Operators are used in SQL to form complex expressions which can be evaluated to
code more intricate queries and extract more precise data from a database.
There are 3 main types of operators: Arithmetic, Comparision and Logical operators,
each of which will be described below.
Arithmetic Operators:
Arithmetic Operators allows the user to perform arithmetic operations in SQL. The
table below shows the list of arithmetic operators available in SQL:
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
Bitwise Operators:
Bitwise operators are used to performing Bit manipulation operations in SQL. The
table below shows the list of bitwise operators available in SQL:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
Relational Operators:
Relational operators are used to performing relational expressions in SQL, i.e those
expressions whose value either result in true or false. The table below shows the list
of relational operators available in SQL:
Operator Description
= Equal to
Operator Description
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
Compound Operators:
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
&= AND equals
|= OR equals
^= XOR equals
Logical Operators:
Operator Description
ALL Returns True if all subqueries meet the given condition.
AND Returns True if all the conditions turn out to be true
ANY True if any of the subqueries meet the given condition
BETWEEN True if the operand lies within the range of the conditions
EXISTS True if the subquery returns one or more records
IN Returns True if the operands to at least one of the operands in a given list
of expressions
LIKE Return True if the operand and some given pattern match.
NOT Displays some record if the set of given conditions is False
OR Returns True if any of the conditions turn out to be True
SOME Returns True if any of the Subqueries meet the given condition.
A database consists of multiple tables and these tables and their contents are
related to each other by some relations/conditions. To identify each row of these
tables uniquely, we make use of SQL keys. A SQL key can be a single column or a
group of columns used to uniquely identify the rows of a table. SQL keys are a
means to ensure that no row will have duplicate values. They are also a means to
establish relations between multiple tables in a database.
Types of Keys:
Properties:
Only a single primary key for a table. (A special case is a composite key,
which can be formed by the composition of 2 or more columns, and act as a
single candidate key.)
The primary key column cannot have any NULL values.
The primary key must be unique for each row.
Example:
The above example creates a table called STUDENT with some given
properties(columns) and assigns the ID column as the primary key of the table.
Using the value of ID column, we can uniquely identify its corresponding row.
2. Foreign Key: Foreign keys are keys that reference the primary keys of some
other table. They establish a relationship between 2 tables and link them up.
Example: In the below example, a table called Orders is created with some given
attributes and its Primary Key is declared to be OrderID and Foreign Key is declared
to be PersonId referenced from the Person's table. A person's table is assumed to
be created beforehand.
Amongst these, the Primary and Foreign keys are most commonly used.
The SQL Server has many builtin functions some of which are listed below:
The table below lists some of the String functions in SQL with their description:
Name Description
ASCII Returns ASCII values for a specific character.
CHAR Returns character based on the ASCII code.
CONCAT Concatenates 2 strings together.
SOUNDEX Returns similarity of 2 strings in terms of a 4 character code.
DIFFERENCE Compares 2 SOUNDEX values and returns the result as an integer.
SUBSTRING Extracts a substring from a given string.
TRIM Removes leading and trailing whitespaces from a string.
UPPER Converts a string to upper-case.
SQL Server Numeric Functions:
The table below lists some of the Numeric functions in SQL with their description:
Name Description
ABS Returns the absolute value of a number.
ASIN Returns arc sine value of a number.
AVG Returns average value of an expression.
COUNT Counts the number of records returned by a SELECT query.
EXP Returns e raised to the power of a number.
FLOOR Returns the greatest integer <= the number.
RAND Returns a random number.
SIGN Returns the sign of a number.
SQRT Returns the square root of a number.
Name Description
SUM Returns the sum of a set of values.
SQL Server Date Functions:
The table below lists some of the Date functions in SQL with their description:
Name Description
CURRENT_TIMESTAMP Returns current date and time.
DATEADD Adds a date/time interval to date and returns the new date.
DATENAME Returns a specified part of a date(as a string).
DATEPART Returns a specified part of a date(as an integer).
DAY Returns the day of the month for a specified date.
GETDATE Returns the current date and time from the database.
SQL Server Advanced Functions:
The table below lists some of the Advanced functions in SQL with their description:
Name Description
CAST Typecasts a value into specified datatype.
CONVERT Converts a value into a specified datatype.
IIF Return a value if a condition evaluates to True, else some other value.
ISNULL Return a specified value if the expression is NULL, else returns the
expression.
ISNUMERIC Checks if an expression is numeric or not.
SYSTEM_USER Returns the login name for the current user
USER_NAME Returns the database user name based on the specified id.
Joins are a SQL concept that allows us to fetch data after combining multiple tables
of a database.
INNER JOIN: Returns any records which have matching values in both tables.
Example:
SELECT orders.order_id,
products.product_name,customers.customer_name,products.price
FROM orders
INNER JOIN products ON products.product_id = order.product_id
INNER JOIN customers on customers.customer_id = order.customer_id;
NATURAL JOIN: It is a special type of inner join based on the fact that the
column names and datatypes are the same on both tables.
Syntax:
Example:
In the above example, we are merging the Customers and Orders table shown
above using a NATURAL JOIN based on the common column customer_id.
RIGHT JOIN: Returns all of the records from the second table, along with
any matching records from the first.
Example:
LEFT JOIN: Returns all of the records from the first table, along with any
matching records from the second table.
Example:
The top few entries of the resultant table will appear as shown in the below image.
FULL JOIN: Returns all records from both tables when there is a match.
Example:
Table Customers:
Table Orders:
We will get the following table as the result of the outer join.
13. Triggers in SQL
Syntax:
Example:
Here, we create a new Trigger called trigger1, just before we perform an INSERT
operation on the Student table, we calculate the percentage of the marks for each
row.
Some common operations that can be performed on triggers are:
DROP: This operation will drop an already existing trigger from the table.
o Syntax:
DROP TRIGGER trigger name;
SHOW: This will display all the triggers that are currently present in the
table.
o Syntax:
SHOW TRIGGERS IN database_name;
SQL procedures are stored in SQL codes, which can be saved for reuse again and
again.
Syntax:
EXEC procedure_name;
Example:
Insertion or ‘Injection’ of some SQL Query from the input data of the client to the
application is called SQL Injection. They can perform CRUD operations on the
database and can read to vulnerabilities and loss of data.
The above image shows an example of SQL injections, through the use of 2 tables -
students and library.
into the Database server, where his query is used to JOIN the tables - students and
library. Joining the 2 tables, the result of the query is returned from the database,
using which the hacker gains access to the information he needs thereby taking
advantage of the system vulnerability. The arrows in the diagram show the flow of
how the SQL Injection causes the vulnerability in the database system, starting from
the hacker’s computer.
Conclusion
Databases are growing increasingly important in our modern industry where data is
considered to be a new wealth. Managing these large amounts of data, gaining
insights from them and storing them in a cost-effective manner makes database
management highly important in any modern software being made. To manage any
form of databases/RDBMS, we need to learn SQL which allows us to easily code and
manage data from these databases and create large scalable applications of the
future, which caters to the needs of millions.
Useful Resources
SQL MCQ
1.
Primary key
Candidate key
Foreign key
None
2.
DELETE
ORDER BY
SELECT
WHERE
3.
Referential integrity
Entity integrity
Domain integrity
None
4.
DROP
DELETE
ERASE
REMOVE
5.
ADD
SUM
TOTAL
COUNT
6.
READ UNCOMMITTED.
WRITE UNCOMMITTED.
READ COMMITTED.
WRITE COMMITTED.
7.
What will be the output of the following code snippet using SQL Loops?
SELECT Name, ID
FROM Student, Courses