A Quick Guide For SQL by Prince Verma and Heer Mehta
A Quick Guide For SQL by Prince Verma and Heer Mehta
Prince Verma
Heer Mehta
Edignite NGO
Contents
Title Page
Preface
Introduction
Create, Show and Delete A Database
Create and Describe a Table
Inserting and Displaying a Table
Editing a table
Editing Columns of a Table
Various Clauses in SQL commands
Logical and Conditional keywords in SQL
Aggregate Functions for values in a table
Indexing
Foreign Key Constraint
Joins in SQL
Unions in SQL
String Functions in SQL
Date Functions
Time Functions
Regular Expressions
Interview Questions in SQL
Conclusion and Ending Note
Annexure 1
Annexure 2
Annexure 3
About The Author
Preface
SQL, though a simple and easy to learn language, has a demand in today's market. It is an essential skill for many
job profiles, especially for one in Data Analytics. With increasing popularity of SQL and IT, there is a vast majority
of Youth switching to the IT Sector, especially in the field of Data Analytics.
With increasing number of people willing to join this field, many of them find difficult to get into it (especially ones
which belong to Non-Technical background). So, witnessing this, we decided to write this guide, that can help all
the beginners in this field towards their journey of learning SQL.
Although containing limited commands, this book comprises of all the basic fundamentals that you require to excel
your career in SQL. It also contains 20 Interview Questions at the end to give you a better knowledge and
understanding of the language, as well as help you crack SQL interview.
With all the commands explained in simple language, this book can help you set the foundations of SQL, and take a
step further in getting into Data Analytics.
Introduction
In today's world there's a lot of Data which is generated everyday. All of this data can only become useful when
organised, stored, and analysed properly.
With increasing data, there came a need to find a better solution for storing, organising, and managing it. This is
when the concept of Database Management System arised.
To explain in brief, Database Management System, is a software that efficiently stores and organizes our data.
('manages' our data). Apart from storage and organization, it provides us with several functionalities to analyse our
data, and find relationship between different data points. So what is SQL then? SQL is a standardized language for
managing our data, that is, for database management system.
SQL (Structured Query Language) is used to store, organize, manage, and analyses the data in form of relational
(table-based) databases. Thus in the coming chapters you'll learn about this language and various commands in it.
Create, Show and Delete A Database
The first step towards storing data in SQL is creating a Database. Database is analogous to an excel file which
stores different tables of same category (tables being analogous to sheets in SQL).
For creating a Database, we use CREATE DATABASE command. So the syntax of the command is
CREATE DATABASE database_name;
Let us understand this with an example. Suppose we want to create a database to store employees of a company, we
would first create a database, as given below:-
CREATE DATABASE employee_details;
Where ‘employee_detials’ is the name of the Database.
Now, since we may create several databases, we can see them by the following command.
SHOW DATABASES;
Which may give you the following result: -
where we employee_details is the database created by us, and others are the prebuilt databases of the system
software (MySQL in this case).
We will now further look at deleting or dropping a database. To drop a database, we use the command: -
DROP DATABASE database_name;
So, if we want to drop employee_details database, then we would type: -
DROP DATABASE employee_details;
Create and Describe a Table
After creation of a database, we can create multiple tables into the database for organizing our data.
To create a table in a database, we need to describe its name, column name, and datatype of each column as given
below: -
Here, emp_id, emp_name, and emp_dept are names of columns, and INT, VARCHAR(55), VARCHAR(100) are
the datatypes.
Now that, we have created our table, we can describe it by using: -
DESC tablename;
Taking example of ‘employees’ table, we can know about properties of its each column, by: -
DESC employees;
Here Field and Type columns show names and datatype of the columns respectively. From the remaining ones,
'Null' shows if value of the corresponding column can be null and 'Default' shows the default value of that column.
By default, values for the columns is set as NULL. So, to make the insertion of values for a column mandatory,
we write NOT NULL after the declaration of datatype. And, to set the default value of a column, we write
DEFAULT=value just after NOT NULL/ datatype declaration.
Let's look at an example. Assuming that we need to store data of employees in marketing department, majority of
which are living in an imaginary city named 'Magmoor'.
So making all fields mandatory and setting the default value of mktng_city as 'Magmoor', we can create a table as
per the command shown below: -
We can notice over here that field nktng_id should be mandatory and unique for each employee, and can work as a
unique indentifier for each employee. Thus this feild in SQL is a 'Primary Key' which uniquely identifies each and
every record in a table. To set the Primary key , we can write the command as given in the example below: -
Over here, when declaring a field as Primary Key, we don't need to specify it as 'NOT NULL'. A Primary Key is a
mandatory and unique field, which is specified as NOT NULL by default.
There are some fields in a table which increase by one, on insertion of every record. For eg: - Sr. No. in many
tables, mktng_id in case of this table. We can set them to increase automatically by setting auto-increment for them.
Thus,after setting NOT NULL, PRIMARY KEY, DEFAULT, and AUTO_INCREMENT, our description of table
would look like one given in the below image: -
Inserting and Displaying a Table
Moving further, we have created our table, marketing_dept. Now, we need to insert data into the table, which can be
done with the following command.
In this command, column1...column3 are the names of the columns and value1...value3 are their corresponding
values.
In case we are giving values of all columns, that too in sequential order, we don't need to specify column names. So,
for example if we have only three columns, column1, column2, column3 in order, our command can go like this: -
INSERT INTO table_name VALUES (value1, value2, value3), (value1, value2, value3), (value1, value2, value3),
…;
Let us now look at the case of default, and auto-increment. So, when one of our column has auto-increment, we
need not give its value when inserting records in to it. Taking example of previously made table , marketing_dept,
our command can be something like this: -
Here, we will get no errors, even when mktng_id was a unique and mandatory field . As in insertion of first record,
its corresponding mktng_id was set as 1, and increased by one on insertion of further records.
Now, we can also insert a record without a city. When we don't give the value of mktng_city, it will be set to the
default value. So, following command can be executed, when we don't know the exact value of a default column.
Here also we don't get any errors as, the value of mktng_city was set as 'Magmoor'.
We would now look at displaying the table. We can display the records of a table by the following command: -
The result of the above command would be as given in the image below: -
(We can see over here that, the mktng_id values have been automatically given, and even in case of fourth record
the default value of mktng_city has been given)
Here * represents all the columns of that table. But if we want only specific columns, we can mention them in
place of * , separating them by a comma. Something like this: -
Suppose now, we want to change the designation of Person1 to Senior Manager. This can be done with the update
command which has following syntax.
We can also delete a record (record of Person3, for example) using the Delete command. The syntax of the
command is as given below: -
After updating a value and deleting one, our table would look like: -
We can also truncate a table (delete all the records from a table), using the following command: -
Let us first see how to delete a column of a table. The following syntax is used to delete the column of a table: -
So, in case of a previously made table, employees, if we want to drop emp_dept column, our command would look
like this: -
So, if we want to add mktng_id after emp_id into out table, we can write: -
Now, to Rename or Change a columns we can use the following syntaxes respectively: -
Here, if we just want to change the name of the column, we can use 'RENAME' command. But in case of changing
the definition of the column (changing the datatype, as an example), we need to use 'CHANGE' command.
Taking an example of employees table, if we just want to rename, emp_name to emp_fullname, we can type: -
Now if we want to change the datatype of emp_id from 'INT' to 'VARCHAR(10)', as well as change the name to id
we can need to write: -
So here, we have got the details of orders placed in a month from different persons.
Now, we will look at the clauses used with the select statement one by one.
We have already looked upon the first clause that is 'FROM'. It tells compiler from which table we want a set of
data. Let us look at the output of command given below: -
Now comest the ORDER BY clause, which is used to arrange the records in ascending/ descending order of a
particular column. It can be used as shown below: -
SELECT * FROM table_name ORDER BY column_name ASC/DESC;
Here ASC/ DESC stand for ascending or descending order respectively. If we don't give the ascending/descending
argument, then the records are ordered as per the ascending order.
In our orders table, we can arrange the records as per in descending order of total price, as given below: -
Taking an example of orders table, let us print top five orders, starting at fifth record. (Offset no - 4).
SELECT cost_name, order_tprice FROM orders ORDER BY order_tprice DESC LIMIT 4,5;
Here, we can see that the counting of records has started from fifth one. Just the next record after the offset number.
We will now look at GROUP BY and HAVING Clause. We can use GROUP BY clause to collect and show data in
groups of a particular value.
So, if we want to look how many times value for a particular column has occurred, we can execute a command with
following syntax: -
SELECT column_name, COUNT(*) FROM table_name GROUP BY category;
Here COUNT(*) represents the number of records. So, to look at number of orders by a single person we can
execute the following command and look at the result following it: -
Now, if we only want to get the number of occurrences satisfying a condition we use HAVING clause.
For example, if we want list of only those costumers, who have ordered more than once, then we can write: -
Here, we get only the list of costumers who have ordered more than once, as given below: -
We can now look at WHERE Clause, which is use to filter the records according to the conditions. We have already
seen the use of WHERE Clause in update statement, and will now see the syntax of SELECT command with
WHERE Clause. So, the syntax is: -
Here with the WHERE Clause we use some conditional operators (==, >, <, >=, etc) and Logiacal Operators like
&&, || etc.
So, if we want a list of orders, whose total price is more than 500, then we can write: -
Which gives,
Logical and Conditional keywords in SQL
In this chapter, we will look at some logical amd conditional keywords that can be used with the WHERE Clause
for better filtration of Data.
So, first two keywords are AND and OR, which filter the data satisfying both the conditions and either of the two
conditions respectively.
The syntax for AND/ OR keyword with WHERE Clause would be: -
Here AND filters the data satisfying both the conditions and OR filters the data satisfying either of the two
conditions.
Below are the examples of AND and OR, in case of orders table, along with the output: -
Output:-
Output:-
The next comes is IN Clause, which is used to filter the data where value of a particular column is present in the list
given by us. The syntax of the command is: -
We can get a clear idea of IN keyword from the following example, where we want those records whose total price
is in the list of (865,866,867,868): -
Output
Now we would look at BETWEEN keyword, which is similar to IN. But unlike IN, it provides a range of numbers.
The use of BETWEEN can directly be understood using the below example, where we are filtering the records with
total price between 500 and 1000.
SELECT * FROM orders WHERE order_tprice BETWEEN 500 AND 1000;
Output:-
We will now see the syntax of IS NULL/ IS NOT NULL, which is used to filter the data where particular column
values corresponding to their records are/ are not NULL.
So the syntax is : -
We may not see much time difference when a record is searched by indexed and non-indexed column, in case of
records less than 100. But it becomes significant as data grows to thousands of records.
Here, columns which are PRIMARY/ FORIEGN KEYS are already indexed and we don't need to index them
separately.
So, for example in orders table if we frequently search a record by name of the costumer, then we can index
cost_name column.
The syntax of adding an index at the time of creation of table, and in case if the table is already created is
respectively,
This command will give the following output when we describe the table: -
Here we can see MUL, meaning multiple, in the Key column corresponding to cost_name. We have thus indexed
our cost_name column.
Foreign Key Constraint
A Foriegn Key Constraint acts as a link between two tables. We can say that a foriegn key of one (child) is primary
key of another table(parent). To better understand the concept let us have following costumers table comprising of
id, name and age of costumers, having cost_id as the Primary Key.
Now that we have cost_id as a Primary Key in costumers table, let us add a cost_id corresponding to cost_name in
orders table as given below.
(Here the cost_id column was added using ALTER command and values of cost_id were added using UPDATE
command).
We can now see in the updated table the cost_id corresponding to each cost_name. So, cost_id can act as a link
between orders and costumers table. Thus it can be Foriegn key of orders table.
This was about foriegn key using example of costumers and orders table. But still the cost_id in orders table has
not been declared as the foriegn key.
To add a foreign key, we either need to declare it at the time of creation of table or after the table has been created.
Following are the syntaxes for adding a Foriegn Key at the time of creation of table and in case the table is already
created respectively: -
and
To set the Foriegn Key in orders table, we would need to execute the following command: -
ALTER TABLE orders ADD CONSTRAINT cost_to_orders FOREIGN KEY(cost_id) REFERENCES
costumers(cost_id);
Upon describing the table, it will give the following output.
We join two tables on a common column, to get the data from both of them. Generally its primary key of one table
acting as a foreign key in another table.
For eg, in our case orders and costumers tables can be joined on cost_id.
There are four types of Joins in MySQL. But before understanding types of joins, let us add one record in orders
table for a PersonX, where cost_id is NULL and similarly a record of PersonI in costumers table. (Thus both the
tables will consist of a record, which is not there in other).
Costumers: -
Orders:-
The first one is Inner Join. As given in the figure below, it displays all the common data from both the tables.
The SQL syntax for an Inner Join is: -
Thus, for inner join between costumers and orders, we need to write,
SELECT orders.cost_id, orders.cost_name, order_tprice, cost_age FROM orders INNER JOIN costumers ON
orders.cost_id = costumers.cost_id;
So, in the output we can see that the records for PersonX in orders table and PersonI in costumers table have been
excluded, as they are not common between both the tables.
Now talking about left join, it displays all the records from the left table as well as ones which are common between
left and right table. The concept of left join is shown in the following Venn diagram.
So, the syntax of left join is similar to INNER join. We just need to replace 'INNER' with 'LEFT'.
We can thus directly write the following command to have left join between costumers and orders table.
SELECT costumers.cost_name, costumers.cost_id, order_tprice, cost_age FROM costumers LEFT JOIN orders
ON costumers.cost_id = orders.cost_id;
Here, we can see that order_tprice for PersonI is NULL, as there is no record of PersonI in orders table. Thus left
join displays all the data from left table (here costumers) and only includes the common data in case of right table
(here, orders);
Let us now talk about Right Join. In Right Join all the records from the right table are displayed and all the records
common between both the tables are displayed. So the records in the left table, which are not common between both
the tables are excluded.
The syntax of Right Join is also similar to that of Left/ Inner Join, just need to replace LEFT/INNNER with RIGHT.
So, we can apply Right Join on our tables, with the following command: -
SELECT costumers.cost_name, costumers.cost_id, order_tprice, cost_age FROM costumers RIGHT JOIN orders
ON costumers.cost_id = orders.cost_id;
Which will give the following output: -
Over here, the values of cost_name, cost_id, cost_age are NULL, as they correspond to the record of PersonX,
which is not present in the left (costumers) table. So, we have a record from the orders table, that is not present
in the costumers table. However, the record of PersonI from costumers table is excluded, as this is a Right Join.
Unions in SQL
Unions in SQL are used to stack the records of two different tables one over other.
To understand this concept let us make two tables in a separate database named student.
class9
class10
So, if we want to stack records of class9 table and class10 one over other, we use UNION/ UNION ALL.
The syntax of UNION/ UNION ALL is: -
Thus, if we want to stack sname, and spercent from both the tables, then we would execute the following command:
-
Here, the difference between UNION and UNION ALL is that UNION removes the duplicate values.
So in case of UNION only one Student1 record will be present in the output.
In case of UNION
These are some of the string functions in SQL. Other important string functions are given in Annexure I, at the end
of this book.
Date Functions
Similar to string functions, there are several Date Functions in SQL. In this chapter, we will look at some of them.
The format of date in SQL is YYYY-DD-MM, which will be the standard formates used in all functions.
These are some of the date functions, we generally use. Other important date functions are given in Annexure
III. Do go through it once for better understanding of Date Functions.
Time Functions
Similar to String, and Date functions, we have a number of Time Functions in SQL. So, let us list out some of them
. (The format of time in SQL is HH:MM:SS). The time functions are as given below: -
Below are some examples of how can regular expressions be used to search for strings with specific patterns: -
Here we can see that a regular expression (String after REGEXP) is a combination of lower and upper case letters,
numbers, and meta-characters. These meta-characters have different uses in Regular Expression. The use of all
these characters is given in Annexure III. These can be used with combination of letters and numbers to find
patterns in strings.
Interview Questions in SQL
1. What is the difference between relational and non-relational DBMS. Explain with examples.
-- A Relational Database Management System is used for storing structured data or data that can be converted into a
tabular format, for eg: - SQL. Whereas Non Relational Database Management System is used for storing non-
structural data, for eg: - MongoDB.
11. What is the difference between IN operator and BETWEEN operator in SQL?
--IN operator is used to select the records whose values exist in a set/ list of values, while BETWEEN operator is
used to select the records whose values exist within a range of two values.
13. What is the difference between DROP TABLE and TRUNCATE TABLE?
--DROP command deletes the full table, whereas TRUNCATE command deletes all the data from the table.
20. Mention the use of INTERSECT operator/ clause in SELECT statement and write a syntax to use it.
--The INTERSECT operator returns common records from two or more SELECT statements and arranges them in
ascending order by default.
--The syntax for this operator is
SELECT columns FROM table1
INTERSECT
SELECT columns FROM table2
Wheather its digital marketing, web-development, or data analytics, SQL is a highly demanded language for all job
profiles.
It is thus advised, to go through this guide thoroughly and practise SQL queries before starting a project on the topic
or applying for its interview.
Though simple and easy to learn, there's a huge demand of SQL Developers in the market.
With this note, we conclude this book and hope you had a great journey learning SQL throughout this book.
Annexure 1
Various String Functions with examples in SQL
SQL has offered us with several string functions to be used in our queries. Given below is a list of all the string
functions with example and output: -
To slice a part of string from right side till a particular index value
SELECT RIGHT("Sample String", 3);
Output - "ing"
To add spaces
SELECT SPACE(15);
Output - It will add 15 spaces
To reverse a string
SELECT REVERSE("abcdef");
Output - "fedcba"
There are various date functions in SQl, that can be used to find out date, month week, etc. and be used for running
different queries.
Below is a list of SQL Date Functions with example and query output: -
A Regular Exptression is a combination of letters, numbers, and meta-characters used to find specific patterns in
strings.
Along with SQL, he has an expertise in the feild of frontend and backend development, data analytics, android
development, etc. He has done several projects including a chrome extension, an NPM package, a Python library,
and an Android Application. He has delivered several seminars on topics like SQL, MERN Stack, Java, etc. and
has guided many beginners in the field of Software Engineering.