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.
The following functionalities can be performed on a database using SQL:
Create or Delete a Database.
Create or Alter or Delete some tables in a Database.
SELECT data from tables.
INSERT data into tables.
UPDATE data in tables.
DELETE data from tables.
Create Views in the database.
Execute various aggregate functions.
To get started with using SQL, we first need to install some Database Management
System server. A er 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
Numeric Datatypes:
The table below lists all the Numeric Datatypes in SQL along with their descriptions:
Datatype Description
Date/Time Datatypes:
The datatypes available in SQL to handle Date/Time operations effectively are called
the Date/Time datatypes. The below table lists all the Date/Time variables in SQL
along with their description:
Datatype Description
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.
Types of SQL Commands:
The above image broadly shows the different types of SQL commands available in
SQL in the form of a chart.
1. Data Definition Language(DDL): It changes a table’s structure by adding, deleting
and altering its contents. Its changes are auto-committed(all changes are
automatically permanently saved in the database). Some commands that are a part
of DDL are:
CREATE: Used to create a new table in the database.
Example:
Example:
DROP: Used to delete the structure and record stored in the table.
Example:
TRUNCATE: Used to delete all the rows from the table, and free up the space in
the table.
Example:
In the above example, we insert the values “Scaler” and “DSA” in the columns Name
and Subject in the STUDENT table.
UPDATE: Used to update value of a table’s column.
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”.
DELETE: Used to delete one or more rows in a table.
Example:
In the above example, the query deletes the row where the Name of the student is
“Scaler” from the STUDENT table.
3. Data Control Language(DCL): These commands are used to grant and take back
access/authority (revoke) from any database user. Some commands that are a part of
DCL are:
Grant: Used to grant a user access privileges to a database.
Example:
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.
Revoke: Used to revoke the permissions from an user.
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.
4. Transaction Control Language: These commands can be used only with DML
commands in conjunction and belong to the category of auto-committed
commands. Some commands that are a part of TCL are:
COMMIT: Saves all the transactions made on a database.
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.
SAVEPOINT: Used to roll transaction back to a certain point without having to
roll back the entirity of the transaction.
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: It is used to retrieve selected data based on some conditions which are
described using the WHERE clause. It is to be noted that the WHERE clause is
also optional to be used here and can be used depending on the user’s needs.
Example: With WHERE clause,
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.
The valid constraints in SQL are:
1. NOT NULL: Specifies that this column cannot store a NULL value.
Example:
In the above example, we create a table STUDENT, which has some attributes it has
to store. Among these attributes we declare that the columns ID and NAME cannot
have NULL values in their fields using NOT NULL constraint.
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.
5. CHECK: It validates if all values in a column satisfy some particular condition or
not.
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.
Example:
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.
SELECT: We use the select statement to perform the Read ( R ) operation of
CRUD.
SQL Syntax:
Example:
The above example allows the user to read the data in the name and class columns
from the student table.
UPDATE: Update is the ‘U’ component of CRUD. The Update command is used to
update the contents of specific columns of specific rows.
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.
AS Renames a
table/column
SELECT name AS
with an alias
student_name, phone
existing only
FROM student;
for the query
duration.
ASC Used in
conjunction SELECT column1,
with ORDER column2, … FROM
BY to sort table_name ORDER BY
data in column1, column2, …
ascending ASC;
order.
DESC Used in
conjunction SELECT column1,
with ORDER column2, … FROM
BY to sort table_name ORDER BY
data in column1, column2, …
descending DESC;
Page 22 © Copyright by Interviewbit
SQL Cheat Sheet
8. Clauses in SQL
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:
GROUP SELECT
BY Groups rows that have COUNT(StudentID),
the same values into State FROM
summary rows. Students GROUP
BY State;
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 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
Compound Operators:
Compound operators are basically a combination of 2 or more arithmetic or
relational operator, which can be used as a shorthand while writing code. The table
below shows the list of compound operators available in SQL:
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
|= OR equals
^= XOR equals
Logical Operators:
Logical operators are used to combining 2 or more relational statements into 1
compound statement whose truth value is evaluated as a whole. The table below
shows the SQL logical operators with their description:
Operator Description
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.
Super Key: It is a group of single or multiple keys which identifies row of a table.
Candidate Key: It is a collection of unique attributes that can uniquely identify
tuples in a table.
Alternate Key: It is a column or group of columns that can identify every row in
a table uniquely.
Compound Key: It is a collection of more than one record that can be used to
uniquely identify a specific record.
Composite Key: Collection of more than one column that can uniquely identify
rows in a table.
Surrogate Key: It is an artificial key that aims to uniquely identify each record.
Amongst these, the Primary and Foreign keys are most commonly used.
Name Description
Name Description
Name Description
Name Description
Example:
Consider the following tables,
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:
Let us define an Orders table first,
LEFT JOIN: Returns all of the records from the first table, along with any
matching records from the second table.
Example:
Consider the below Customer and Orders table,
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 Orders:
We will get the following table as the result of the outer join.
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.
Syntax:
SHOW: This will display all the triggers that are currently present in the table.
Syntax:
EXEC procedure_name;
Example:
The above image shows an example of SQL injections, through the use of 2 tables -
students and library.
Here the hacker is injecting SQL code -
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 so ware 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.