SQL Cheatsheet - 2
SQL Cheatsheet - 2
Mandar Patil
Mandar Patil
Mandar Patil
Mandar Patil
Mandar Patil
Mandar Patil
Mandar Patil
Mandar Patil
Mandar Patil
Mandar Patil
Mandar Patil
What is a Database?
Before we get started with SQL Cheat Sheet, we need to understand what is a database and why do we need SQL. If you want to learn this offline, you can download the SQL basics
cheat sheet any time.
Data is a collection of facts related to any object. For example: - Your name, number, birthday, phone number, email address, etc. is a collection of facts about you.
Therefore, a database is a systematic collection of small units of information (data). For example: - An organized list of all the students of a school along with their data (Name, Phone
Number, Birthday, etc.) is referred to as a database.
Think of an RDBMS as a tool that allows you to play with your data and generate insights or value from the database.
To recap, a database is a collection of data and an RDBMS is a tool that allows you to interact with your data. Therefore, you would need a "language" to communicate with the database
that humans and computers can understand, and that language is known as SQL.
SQL stands for Structured Query Language. As the name suggests, it is a structured language via which you can query the database for performing various tasks such as Storing,
Manipulating, and retrieving data from a database.
SQL is the standard language when it comes to communicating with powerful relational databases such as Oracle, Sybase, Microsoft SQL Server, Access, Ingres, etc. Anything related to
data in relational databases such as creating tables, limiting access to data, sorting, filtering, grouping, etc. is achieved using SQL.
In this SQL cheatsheet, we will be learning everything there is to learn about SQL.
Mandar Patil
SQL v/s MySQL: Difference Between Both
Most beginners usually get confused between the two terms - SQL and MySQL, and sometimes use the two interchangeably. However, there is a clear and vast difference between the
two.
As defined earlier, SQL is a language that allows one to communicate with the database. MySQL on the other hand is an RDBMS in which you can type SQL commands to interact with
the database.
SQL is the language/protocol that is used by relational database management systems to allow users to manipulate data in the database.
MySQL is a database management system that provides users with an interface to connect with databases. MySQL provides users with the ability to create various databases, tables,
stored procedures, functions in their database servers. SQL is the language that is used to perform powerful operations on the database.
In this SQL Cheat Sheet, we would be looking at both SQL and MySQL which would help clarify the difference.
Using SQL, you create Databases, and inside a database, you create various TABLES in which you can add all your data. Using SQL, you can:
and tons of other cool stuff. So, let's see how we can harness this power.
There are various RDBMS that you can use, and it doesn't matter (much) what system you choose as long as it's working for you. Some of the most common RDBMS are:
1. MySQL
2. Oracle
3. Microsoft SQL Server
4. PostgreSQL
5. Heidi SQL
Just install any of the RDBMS that you like from their official website and you should be able to create a database server by simply following their instructions. Once you have a
database server ready, you can get access to a Query Editor where you can type all your SQL queries.
Now, let's get started with our cheat sheet and learn some SQL basics and SQL syntax to get the ball rolling.
For example:- If you have a restaurant management application or implemented E-Delivery solution for smooth operations, you would have a database that contains tables such as:
1. Customers
2. Orders
3. Menu Items
4. Receipts
5. Combox
etc. Each table would contain a specific type of data and various tables could have different types of relations. Using SQL relations, we can combine values from different tables to fetch
the data that we require. (More on relations in a later section)
Mandar Patil
To create a table, we would require two things. Firstly, we would need all the fields that we want to store in a table. Secondly, we want to define the type of data that would enter into a
table.
Let's take the restaurant management application's Customers table as an example. We want to store some information about each of our customers such as their name, Phone Number,
and Postal Code. Now that we are done with the first step, we need to define the data types of these values.
The name of a customer would be of character data type because we need to store alphabetical characters. Similarly, the phone number would be characters again because we would need
to store country code, and special characters such as '+', '()', etc. The postal code would be of type integer because we need to store numbers. Here is how the table would look like:
To identify each customer uniquely, we add an ID to them so that we can use this ID to connect data from various tables. So, the final table structure could look something like this.
To create this table, we would use the CREATE SQL Command followed by the fields as follows:
name varchar(50),
phone varchar(15),
postalCode INT
);
Every RDBMS is different and each RDBMS might have a different data type for working with certain values. The following sections of this SQL Cheat Sheet contain the various types
of MySQL data types.
DEC(size,d)/ An exact fixed-point number with the total number of digits set by the size parameters, and the total number of digits after the decimal point set by
DECIMAL(size,d) the d parameter. For size, the maximum number is 65 and the default is 10, while for d, the maximum number is 30 and the default being 10.
Note: All the numeric data types may have an extra option: UNSIGNED or ZEROFILL. If you add the UNSIGNED/ZEROFILL option, MySQL disallows negative values for the
column.
CRUD is an acronym that stands for Create, Read, Update, and Delete. These are the most fundamental operations that one can perform on any database. For creating any application,
these 4 types of operations are crucial. They are:-
1. INSERT (Create)
2. SELECT (Read)
3. UPDATE (Update)
4. DELETE (Delete)
INSERT
To insert data into any table, we use the INSERT INTO statement. The general syntax for insert is:
VALUES(val1,val2,...);
To insert data into our customer's table, we would use the following statement:
VALUES(1,'Alice','+123456789',123456);
SELECT
To read data from a table, we would use the Select statement where we define the columns that we want to fetch. The general syntax is:
Mandar Patil
If we wanted to select the name and phone number of a customer from our table, we would use:
Also, to read all the columns from our table, we can replace the column names with * as follows:
UPDATE
To update specific column(s) of specific row(s), we make use of the Update statement. The general syntax for an update statement is:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE conditions...;
For example, if we wanted to update the phone number of a customer that has an ID of 2, we would write our query as:
UPDATE customers
SET phone='+2223334445'
WHEREID=2;
We can update multiple columns by adding them to the SET statement and we can target multiple rows by adding them to the WHERE statement. We will look at WHERE in detail in
later sections of this SQL commands cheat sheet.
DELETE
If we wanted to remove some rows from a table, we would use the delete statement. The general syntax is:
WHERE condition...;
Let's say we want to remove all the customers who live in a particular area. So, we simply delete those rows that have a specific area code:
WHERE postalCode=223344;
Keyword Description
ADD Add a new column to an existing table. Eg: ALTER TABLE customers ADD email_address VARCHAR(255);
ALTER TABLE Adds, deletes, or edits columns/constraints in a table. Eg: ALTER TABLE customers DROP COLUMN email_address;
ALTER COLUMN Changes the data type of a table’s column. Eg: ALTER TABLE customers ALTER COLUMN phone varchar(50)
Renames a table or column with an alias value that only exists for the duration of the query. Eg: SELECT name AS customer_name, phone,
AS
postalCode FROM customers;
ASC Used with ORDER BY to return the data in ascending order.
Adds a constraint that limits the value which can be added to a column. Eg: CREATE TABLE Users(firstName varchar(255),age INT,
CHECK
CHECK(age>10));
CREATE
Creates a new database. Eg: CREATE DATABASE my website;
DATABASE
CREATE TABLE Creates a new table. Eg: CREATE TABLE users (id int,firsr_name varchar(255), surname varchar(255), address varchar(255), contact_number int);
Set the default value for a column. Eg: CREATE TABLE products(ID int, name varchar(255) DEFAULT 'Username', from date DEFAULT
DEFAULT
GETDATE());
DELETE Delete values from a table. DELETE FROM users WHERE user_id= 674;
DESC Used with ORDER BY to return the data in descending order.
DROP COLUMN Deletes a column from a table. ALTER TABLE users DROP COLUMN first_name;
Mandar Patil
DROP
Deletes a complete database along with all the tables and data inside. Eg: DROP DATABASE my website;
DATABASE
DROP DEFAULT Removes a default value for a column. Eg: ALTER TABLE products ALTER COLUMN name DROP DEFAULT;
DROP TABLE Delete a table from a database. Eg: DROP TABLE customers;
FROM Specifies which table to select or delete data from. Eg: SELECT * FROM customers;
Used with a WHERE clause as a shorthand for multiple OR conditions. Eg: SELECT * FROM users WHERE country IN('USA', 'United
IN
Kingdom','Russia');
IS NULL Tests for empty (NULL) values. Eg: SELECT * FROM users WHERE phone IS NULL;
IS NOT NULL Opposite of IS NULL. Tests for values that are not null.
LIKE Returns true if the operand value matches a pattern. SELECT * FROM users WHERE first_name LIKE '%son';
ORDER BY Used to sort the resultant data in ascending (default) or descending order.
SELECT
Same as SELECT, except duplicate values are excluded. Eg: SELECT DISTINCT postalCode from customers;
DISTINCT
TOP Used alongside SELECT to return a set number of records from a table. Eg: SELECT TOP 5 * FROM customers;
Used alongside the INSERT INTO keyword to add new values to a table. Eg: INSERT INTO cars (name, model, year) VALUES ('Ford', 'Fiesta',
VALUES
2010);
WHERE Filters result only includes data that meets the given condition. SELECT * FROM orders WHERE quantity > 1;
Operators in SQL
SQL has various operators that allow you to manipulate and compare multiple values. These are very useful and handy while creating queries.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
SQL Comparison Operators
Operator Description
= Equal to
> Greater Than
< Less Than
>= Greater than or equal to
<= Less than or equal to
<> Not Equal to
SQL Compound Operators
Operator Description
+= Add Equals
-= Subtract Equals
*= Multiply Equals
/= Divide Equals
%= Modulo Equals
&= Bitwise AND Equals
^-= Bitwise Exclusive Equals
|*= Bitwise OR Equals
Mandar Patil
SQL Logical Operators
Operator Description
ALL TRUE if all of the subquery values meet the condition
AND TRUE if all the conditions separated by AND is TRUE
ANY TRUE if any of the subquery values meet the condition
BETWEEN TRUE if the operand is within the range of comparisons
EXISTS TRUE if the subquery returns one or more records
IN TRUE if the operand is equal to one of a list of expressions
LIKE TRUE if the operand matches a pattern
NOT Displays a record if the condition(s) is NOT TRUE
OR TRUE if any of the conditions separated by OR is TRUE
SOME TRUE if any of the subquery values meet the condition
SQL Keys
In a database, different tables store different values and these values are related to each other. To identify each row uniquely, we make use of SQL keys. An SQL key is either a single
column (or attribute) or a group of columns that can uniquely identify rows in a table. SQL Keys ensures that there aren't any rows with duplicate values.
However, the most powerful use of keys is to establish relations between multiple tables in a database. To do so, we need to understand Primary Key and Foreign Key. The following
sections of this SQL cheatsheet explain both of these concepts.
Primary Key
It is a key that uniquely identifies a single row in a table. For example, in a customer's table, the ID key can be used as a primary key to uniquely identify a single customer. This key can
then be used to fetch data from multiple tables that have data related to the customer.
Key Points:
1. There can only be One Primary Key for a Table.
2. Primary Key should be unique for Each Row.
3. Primary key cannot have Null Values.
Typically, the primary key in a table is the ID column and is usually paired with the AUTO_INCREMENT keyword to uniquely identify the row. To mark a column as the primary key,
we use the PRIMARY KEY keyword followed by the column/columns that consist of the primary key. For Example: -
Foreign Key
A foreign key is a field in a table that references the PRIMARY KEY of another table. A foreign key is used to link two tables together by establishing a relationship.
The table that contains the foreign key is known as the child table, while the table containing the primary key for the foreign key is known as the parent table.
For example: Let's say we have 3 different tables to manage a restaurant - products, users, and orders. In our products table, we list all our products and in the user's table, we have
details of all our users. When a user places an order, we save the data in the orders table. But, instead of saving the complete details of the product and all the information of the user, we
save their primary keys in the orders table.
CREATE TABLE orders(
order_id INT NOT NULL,
user_id INT,
product_id int,
PRIMARY KEY(order_id),
FOREIGN KEY(user_id) REFERENCES users(id),
FOREIGN KEY(product_id) REFERENCES products(id)
);
Here, we create a primary key for the order ID as it uniquely identifies an order. Also, we create two foreign keys that reference different primary keys.
Mandar Patil
SQL Joins
Once you understand Primary Key and Foreign Key, you can use joins to fetch data by combining multiple tables. Let's take the orders, customers, and products table as an example.
Products:
We can join the orders table with customers and products table to get only the information that we require. Let's say we want to see all the orders with the customer's name, product
name, and product price as follows:
SQL has Different Types of Joins that Help Achieve Different Results:
1. INNER JOIN - Returns any records which have matching values in both tables.
2. LEFT JOIN - Returns all of the records from the first table, along with any matching records from the second table
3. RIGHT JOIN - Returns all of the records from the second table, along with any matching records from the first
4. FULL JOIN - Returns all records from both tables when there is a match
Mandar Patil
5. Count the Filtered Rows
SELECT COUNT(*) FROM users WHERE age>18;
Note: You can use ASC for Ascending Order or DESC for descending order. If nothing is specified, sorting is done in Ascending order(ASC).
Note:- We can use any type of join that we want. The condition via which we want to join the tables needs to be specified after the ON keyword.
SELECT us.userId,us.name,wall.walletId,wall.balance
FROM Users AS us
INNER JOIN Wallets AS wall
Note: - We use the AS keyword to give an alias to a table to make our SELECT statement shorter. We can even eliminate the AS keyword in this case and simply write the Alias after the
table name.
2. Delete a Table
DROP TABLE Users;
6. Rename a Table
ALTER TABLE Users RENAME TO Customers;
7. Rename a Column
ALTER TABLE Users RENAME userName to name;
Conclusion
SQL is a definite requirement when you are trying to build an application of any size and scale. Learning SQL might be tough for beginners, but once you get the hang of it, it's just like
thinking.
Make sure to bookmark this page and download the SQL cheat sheet pdf if you are working with SQL. If you can remember a particular operation or keyword, you can open up this SQL
commands cheat sheet to get all the required information.
Mandar Patil