0% found this document useful (0 votes)
32 views52 pages

A Quick Guide For SQL by Prince Verma and Heer Mehta

Uploaded by

Derrick's TV
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views52 pages

A Quick Guide For SQL by Prince Verma and Heer Mehta

Uploaded by

Derrick's TV
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Quick Guide for SQL

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: -

CREATE TABLE table_name(column1 datatype,


column2 datatype,
column3 datatype);
For example, following command can be used for creating a table named employees

CREATE TABLE employees(


emp_id INT,
emp_name VARCHAR(100),
emp_dept VARCHAR(55));

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;

Below is the output of this command: -

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: -

CREATE TABLE marketing_dept(


mktng_id INT NOT NULL,
mktng_name VARCHAR(100) NOT NULL,
mktng_des VARCHAR(35) NOT NULL,
mktng_city VARCHAR(25) NOT NULL DEFAULT "Magmoor");

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: -

CREATE TABLE marketing_dept(


mktng_id INT,
mktng_name VARCHAR(100) NOT NULL,
mktng_des VARCHAR(35) NOT NULL,
mktng_city VARCHAR(25) NOT NULL DEFAULT "Magmoor",
PRIMARY KEY(mktng_id));

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.

We can do this by typing the following command: -

CREATE TABLE marketing_dept(


mktng_id INT AUTO_INCREMENT,
mktng_name VARCHAR(100) NOT NULL,
mktng_des VARCHAR(35) NOT NULL,
mktng_city VARCHAR(25) NOT NULL DEFAULT "Magmoor",
PRIMARY KEY(mktng_id));

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.

To insert a single record into the table: -


INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);

To insert multiple records into the table: -


INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3), (value1, value2, value3), (value1, value2, value3), …;

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: -

INSERT INTO marketing_dept(mktng_name, mktng_des, mktng_city) VALUES('Person1', 'Manager', 'Olivera'),


('Person2', 'Sales Executive', 'Magmoor'),
('Person3',' Content Writer', 'Magmoor');

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.

INSERT INTO marketing_dept(mktng_name, mktng_des) VALUES('Person4', 'SEO Specialist');

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: -

SELECT * FROM table_name;

So, in case of marketing_dept it would be,

SELECT * FROM marketing_dept;

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: -

SELECT column1, column2 FROM table_name;


Editing a table
After making our table, we now want to change the name of our table. So a table can be renamed using following
command: -

RENAME TABLE old_name TO new_name;

So, to change the name of marketing_dept to mktng_dept, we can write: -

RENAME TABLE marketing_dept TO mktng_dept;

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.

UPDATE table_name SET column_name = new_value


WHERE column1 = value1;

So, in our case, we would write,

UPDATE mktng_dept SET mktng_des = 'Senior Manager'


WHERE mktng_name = 'Person1';

We can also delete a record (record of Person3, for example) using the Delete command. The syntax of the
command is as given below: -

DELETE FROM table_name


WHERE column_name = value_name;

So, in our case it would be: -

DELETE FROM mktng_dept


WHERE mktng_name = 'Person3';

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: -

TRUNCATE TABLE table_name;

In case of dropping a table we can write: -


DROP TABLE table_name;
Editing Columns of a Table
Now that we have looked upon updating records of a table, we would now look at editing a column. A column can
be changed using Alter Table 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: -

ALTER TABLE tablename


DROP COLUMN columnname;

So, in case of a previously made table, employees, if we want to drop emp_dept column, our command would look
like this: -

ALTER TABLE employees


DROP COLUMN emp_dept;

In case if we want to add a column in an existing table, we can write: -

ALTER TABLE table_name


ADD COLUMN column_name column_defination
FIRST/AFTER existing_column;
Here we write FIRST/ AFTER if we want our column at first place/ after any other column respectively.

So, if we want to add mktng_id after emp_id into out table, we can write: -

ALTER TABLE employees


ADD COLUMN mktng_id INT
AFTER emp_id;

Thus description of our table would now look like: -

Now, to Rename or Change a columns we can use the following syntaxes respectively: -

ALTER TABLE table_name


RENAME COLUMN old_name TO new_name;

ALTER TABLE table_name


CHANGE COLUMN old_name new_name datatype;

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: -

ALTER TABLE employees


RENAME COLUMN emp_name TO emp_fullname;

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: -

ALTER TABLE employees


CHANGE COLUMN emp_id id VARCHAR(10);

So, after making changes our table would look like: -


Various Clauses in SQL commands
From this chapter onwards we would take example of orders table from order_record database, with data as given
below: -

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: -

SELECT cost_name FROM orders;


Here, we have many costumers that who have purchased from the store multiple times. So, to get a non-repeating
list of costumer names, we use DISTINCT clause, as given below in the example: -

SELECT DISTINCT cost_name FROM orders;

We will get the result as given below: -


Here, we can notice that now names of costumers aren't repeated and we get distinct names.

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: -

SELECT cost_name, order_tprice FROM orders ORDER BY order_tprice DESC;


Here, we get all 13 records as the output, but what if we want to get top five records. For t we need to use our next
clause, LIMIT. So, the syntax of LIMIT clause is: -

SELECT valuename FROM tablename ORDER BY valuename LIMIT number;

In our case if we want top five orders, then we can write: -

SELECT cost_name, order_tprice FROM orders ORDER BY order_tprice DESC LIMIT 5;


So here we get the top five orders from the table. But in case if we want five orders, starting from index 6, we need
to set the offset value. So the cursor will now start counting records from a record number just after the offset
number. So if our offset number is 5, the cursor will start counting from 6. The syntax for giving offset num: ber is:
-

SELECT value_name FROM table_name ORDER BY value_name LIMIT offsetno. , limitno.;

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: -

SELECT cost_name, COUNT(*) FROM orders GROUP BY cost_name;

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: -

SELECT cost_name, COUNT(*) FROM orders GROUP BY cost_name HAVING COUNT(*)>1;

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: -

SELECT column_name FROM table_name WHERE condition;

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: -

SELECT * FROM orders WHERE order_tprice>500;

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: -

SELECT column_name FROM table_name WHERE condition1 AND/ OR condition2;

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: -

SELECT * FROM orders WHERE order_tprice>600 AND cost_name='PersonC';

Output:-

SELECT * FROM orders WHERE order_tprice>600 AND cost_name='PersonC';

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: -

SELECT column_name FROM table_name WHERE column_name IN list_of_values;

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): -

SELECT * FROM orders WHERE order_tprice IN (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 : -

SELECT column_name FROM table_name WHERE column_name IS NULL/ IS NOT NULL;


Aggregate Functions for values in a table
Aggregate functions operate over all the values in a single column, and return us a single value. So, the aggregate
functions used in SQL are SUM, COUNT, AVG, MIN, and MAX to find total sum, total number, average,
minimum, and maximum of all values respectively.

All of them have same syntax as given below: -

SELECT FUNC(column_name) FROM table_name;


(where FUNC = SUM, COUNT, AVG, MIN, MAX)

Using these functions over order_tprice column in orders table, we get: -


Indexing
An Index is a quick lookup table for faster retrieval of frequently searched records. In simple words if we index a
particular column, searching for a record using that column becomes much faster.

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,

CREATE TABLE table_name(


column1 datatype NOT NULL,
column2 datatype NOT NULL,…
PRIMARY KEY(column1),
INDEX(column2));

CREATE INDEX index_name


ON table_name(column_name);

Provided that the name of the index in the database is unique.

Thus if we want to set the index of cost_name column, we can write,

CREATE INDEX cost_names ON orders(cost_name);

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: -

CREATE TABLE table_name(


column1 datatype NOT NULL,
column2 datatype NOT NULL,…
CONSTRAINT constraint_name
FOREIGN KEY(column1)
REFERENCES table_name(column_name));

and

ALTER TABLE table_name


ADD CONSTRAINT constraint_name
FOREIGN KEY(column_name) REFERENCES tablename(column_name);

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.

Here, we now have MUL in the key column corresponding to cost_id.


Joins in SQL
Sometimes we need to represent the data of two inter-related tables at once. This can be done by Joins.

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).

Following are the images of bottommost records of both the tables: -

Costumers: -

Orders:-

We would now talk about joins.

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: -

SELECT columns FROM table1


INNER JOIN table2
ON table1.columnname = table2.columnname;

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;

Which will give us the following output: -


Here as cost_id and cost_name are common column names of both the tables, we need to specify the name of the
table we are referencing to for displaying that column. So we need to type either costumers.cost_id or orders.cost_id
instead of just cost_id to avoid any errors. The same goes with the cost_name.

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;

Which will give the following output: -

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.

One will be class9 and other will be class10, as given below: -

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: -

SELECT column1, column2, column3… FROM table1


UNION/ UNION ALL
SELECT column1, column2, column3… FROM table2;

Thus, if we want to stack sname, and spercent from both the tables, then we would execute the following command:
-

SELECT sname, spercent FROM class9


UNION/ UNION ALL
SELECT sname, spercent FROM class10;

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.

Thus, the Output will be: -

In case of UNION

In case of UNION ALL


String Functions in SQL
There are several string functions that operate over strings and give desired outputs. In this chapter, we will look at
some of them. These functions can be used with the SELECT statement to get the desired output, as given in the
following examples.

To convert string into upper case: -


SELECT UPPER(cost_name) FROM ORDERS/
SELECT UPPER('String Value');

To convert string into lower case: -


SELECT LOWER(cost_name) FROM ORDERS; /
SELECT LOWER('String Value');

To concat two strings: -


SELECT CONCAT("String1", "String2");

To find character length of a String: -


SELECT CHARACTER_LENGTH("A sample string");

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.

Let us now look at some of the Date Functions: -

To display current date: -


SELECT CURRENT_DATE(); /
SELECT CURDATE(); /
SELECT SYSFATE();

To print a particular date: -


SELECT DATE('2022-02-12');

To print name of the month: -


SELECT MONTHNAME('2022-02-12');

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: -

To display current date and time (Time stamp): -


SELECT CURRENT_TIMESTAMP(); /
SELECT NOW(); /
SELECT LOCALTIME();

To print time in 12-hour format: -


SELECT TIME_FORMAT("16:34:00", '%r');

To convert seconds into time values: -


SELECT SEC_TO_TIME("45240");

To print difference between two time values: -


SELECT TIMEDIFF("12:34:00", "12:37:34");

To print minute of time value


SELECT MINUTE("12:34:00");

So these were the important time functions in SQL.


Regular Expressions
Regular Expressions are sequences of characters, used to search for different patterns in the strings.

Below are some examples of how can regular expressions be used to search for strings with specific patterns: -

To print records for strings ending with H: -


SELECT * FROM orders WHERE cost_name REGEXP'H$';

To print all records for strings starting with a or n: -


SELECT * FROM orders WHERE cost_name REEXP'^[an]';

To print all the records containing 'son' or 'onX'


SELECT * FROM orders WHERE cost_name REGEXP'son|onX';

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.

2. Does SQL support any programming language features?


-- SQL is exclusively made for data organization, manipulation, and analysis. So it does not support any
programming language feature. So, it cannot be used for anything other tha data manipulation, organization, and
analytics like other programming languages.

3. What is a Foreign Key ?


-- A foriegn key in a table is a key that references to primary key of another table. So foriegn key column of one
table, known as child table refers to the primary key feild of the other table, known as parent table.

4. What is a Unique Key and how can it be declared?


-- A unique key in a table is a column or group of more than one column, that stores unique value for each record. It
ensures that no duplicate values are stored inside a column.
--The following syntax can be used to declare a unique key: -

CREATE TABLE table_name(


column1 datatype NOT NULL,
column2 datatype UNIQUE.....);

5. What is the difference between Primary Key and Unique Key?


-- Unique Key can store NULL values but Primary Key cannot.
-- Another difference is we cannot delete or edit the values of Primary Key, but we can do so in case of Unique
Key.

6. List out the types of operators in SQL.


--The operators in SQL are: -
--Arithmatic Operators - (+,-,*,/,%)
--Logical Operators - (AND, OR, IS NULL, BETWEEN, ..) ,
--Comparison Operators - (>, <, =...),
--Bitwise Operators - (&, | , ~)
--Compound Operators - (+=, *=,...)
--String Operators - (+=, +, %...)

7. What is a View in SQL ? Write a syntax to create a View.


-- A View in SQL is a virtual table/ output which is based on result-set of an SQL query. For eg: -The output of
SELECT statement can be virtually stored in a View.
--Following is the syntax for creating a View.

CREATE VIEW view_name AS


SELECT column_name FROM table_name WHERE condition;
Here we can also store output of join, unions etc. in separate Views provided that all of them have a unique name.

8. What are Joins SQL ? List some of them.


--Joins in SQL are used to retrieve data from more than one tables in a meaningful manner. They are used to
display data of two tables simultaneously into a single table.
The types of joins are Inner Join, Left Join, Right Join, Full Join.

9. What is Full Join?


--Full Join, unlike Inner join displays all the records from both the table whether they are common or not.

10. What is Cross Join?


--Cross Join in SQL is used to match every record of one table to every other record of another table. It is often used
when two tables don't share a common column. Suppose that in table1 we have records A,B and C, and in table2,
we have 1,2,3. So in case of Cross Join A will be matched with 1, 2, as well as 3. Same goes with B and C.

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.

12. Write an SQL quey to find names starting with 'A'


--SELECT * FROM table_name WHERE name LIKE 'A%'

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.

14. What is ACID property for a database?


--ACID is an acronym used for Atomicity, Consistency, Isolation, and Durability. All of these properties ensure
that data transactions are processed reliably in a database system.
The individual acid properties are as follows: -
--Atomicity - It ensures all the transactions or operations within a transaction unit be executed properly. So, in case
of failure of one transaction, the entire transaction woud fail and database state would be left unchanged.
--Consistency - It ensures validation of data in a transaction and prevents data crashes in future.
--Isolation - Isolation defines how and when changes made by one operation are visible to others. This property
controls concurrency in the database.
--Durability - It ensures that once a transaction has been committed, it persists permanently even if the system
crashes, power loss, or failed.

15. Is a blank space or zero equal to NULL value?


--No, NULL value is different from blank space or zero. We can compare a blank space or zero to another value of
the same data type. But the NULL value cannot be compared.
--NULL simply means an unavailable/ unassigned/ unknown/ not applicable value. It is an unknown value
indicating no data is provided or data is missing. Thus it cannot be compared with any of the variables.

16. What is the use of the DISTINCT keyword/ clause?


-- DISTINCT keyword fetches unique records and prevents repetition of values in records. It is used with SELECT
statement to retrieve different data from table

17. What is the difference between WHERE and HAVING Clause?


--The main difference between WHERE and HAVING clause is that WHERE clause is implemented in row
operations whereas HAVING clause is implemented in column operations.
--WHERE clause is used with ALTER, SELECT, and UPDATE statements for filtering data.
--HAVING Clause is used with SELECT statement and generally with aggregate functions in SELECT statement.

18. How to insert comments in SQL?


--Comments are the explanations and annotations ignored at the time of parsing SQL code. The two types of
comments are: -
--Single LIne comments - They start with two consecutive hyphens ‘--’.
--Multi LIne Comments - They are wrapped between ‘/*’ and ‘*/’ .

19. What is the use of FIRST() and LAST() column in SQL?


--The FIRST() function returns the first value of the selected column and LAST() returns the last value of the
selected column.

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

(Here common records from table1 and table2 will be printed)


Conclusion and Ending Note
So , this was a short guide for SQL. We can conclude that SQL is a simple and easy to learn language. However, we
can master it only after rigourous practise of SQL queries.

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.

SQL skill, thus has a great scope in future.

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 convert a string into upper case letters


SELECT UPPER(cost_name) FROM costumers; (OR)
SELECT UCASE(cost_name) FROM costumers;

To convert a string into lower case


SELECT LOWER(cost_name) FROM costumers; (OR)
SELECT LCASE(cost_name) FROM costumers;

To see number of characters in a string


SELECT CHARACTER_LENGTH('Sample String');

To concat two strings


SELECT CONCAT("String1", "String2");
Output - String1String2

To concat multiple strings with a seperator in between


SELECT CONCAT_WS("str1","str2","str3","str4");
(Here the first string acts as a seperator between all these strings)
Output - str2str1str3str1str4

To trim the space on left side of the string


SELECT LTRIM(" Sample String ");
Output - "Sample String "

To trim the space on right side of the string


SELECT RTRIM(" Sample String ");
Output - " Sample String"

To trim the space on both the sides side of the string


SELECT TRIM(" Sample String ");
Output - "Sample String"

To print the position of first character of a word that is in the string


SELECT POSITION("String" IN "This is a String");
Output - 11

SELECT INSTR("This is a String", "String");


Output - 11

To start searching in a String from Specific position


SELECT LOCATE("Str1", "Str1 will not be considered but Str1 will be", 5);
Output - 33 (as it starts searching from 5th position)

To slice a part of String from a particular position


SELECT SUBSTRING("Sample String", 3);
Output - "mple String"
SELECT SUBSTR("Sample String", 3);
Output - "mple String"
To slice a string from left side of an index
SELECT LEFT("Sample String", 4);
Output - "Samp"

To slice a part of string from right side till a particular index value
SELECT RIGHT("Sample String", 3);
Output - "ing"

To pad a string from right side with a particular character


SELECT RPAD("String", 15, "-");
Output - "String---------" (Total should be 15, so 9 dashes on right side)

To pad a string from left side with a particular character


SELECT RPAD("String", 15, "*");
Output - "*********String"

To add spaces
SELECT SPACE(15);
Output - It will add 15 spaces

To reverse a string
SELECT REVERSE("abcdef");
Output - "fedcba"

To replace a part of string with other string


SELECT REPLACE("Sample String", "String", "Another String");
Output - "Sample Another String"

To compare length of two strings


SELECT STRCMP("abcd", "abcdef");
Output - "-1"
(0 if both are equal, 1 if left is greater, -1 if right is greater)

To find index of a character in a list of characters


SELECT FIELD("c", "f","h","c","x","S","f");
Output - 3
(find c in (f,h,c,x,S,f))

To round off value till particular number of digits


SELECT FORMAT(3434.6675, 3);
Output - 3434.678
Annexure 2
Various Date Functions in SQL

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: -

To display current date


SELECT CURRENT_DATE(); (OR)
SELECT CURDATE(); (OR)
SELECT SYSDATE();

To print a particular date (Example - 16 June 2019)


SELECT DATE("2019-06-16");

To print month of a particular date


SELECT MONTH("2019-06-16");
Output - 6

To print name of month


SELECT MONTHNAME("2019-06-16");
Output - "June"

To print quarter of the year, to which the date belongs


SELECT QUARTER("2019-06-16");
Output - 2

To return day number at a particular date in a year


SELECT DAYOFYEAR("2019-06-16");
Output - 167

To return day of month at a particular date


SELECT DAY("2019-06-16"); (OR)
SELECT DAYOFMONTH("2019-06-16");
Output - 16

To print name of the day at a particular date


SELECT DAYNAME("2019-06-16");
Output - "Sunday"

To print Day of week (starting at Sunday=1)


SELECT DAYOFWEEK("2019-06-16");
Output - 1

To return weekday number for a date (starting at Monday=0)


SELECT WEEKDAY("2019-06-16");
Output - 6

To return week number at a particular date


SELECT WEEKOFYEAR("2019-06-16");
Output - 24

To print year as well as week of a particular date


SELECT YEARWEEK("2019-06-16");
Output - 201924

To print day of the year


SELECT DAYOFYEAR("2019-06-16");
Output - 167

To print last day of the month to which a particular date belongs


SELECT LAST_DAY("2019-06-16");
Output - "2019-06-30"

To print number of days between date and year 0


SELECT TO_DAYS("2019-06-16");
Output - 737591

To convert numeric representation into date


SELECT FROM_DAYS(737591);
Output - 2019-06-16

To print date in a particular format


SELECT DATE_FORMAT("2019-06-16", "%D %M %Y"); Output - 16th June 2019

To print difference between two dates


SELECT DATEDIFF("2019-06-30","2019-06-16");
Output - 14

To add 10 days to a date and again return the date


SELECT ADDDATE("2019-06-16", INTERVAL 14 DAY);

To subtract 10 days from the date and return the date


SELECT DATE_SUB("2019-06-16", INTERVAL 14 DAY);
Annexure 3
Various meta-characters for Regular Expression

A Regular Exptression is a combination of letters, numbers, and meta-characters used to find specific patterns in
strings.

So here is a list of meta-characters and their use in Regualr Expression: -

^ - To start matching at the beginning of the string

$ - To start matching at the end of the string

. - To match a single character, except for a nw line

[abc] - Match any of the characters mentioned in the bracket

[a-h] - To match a character between a particular range

[0-9] - To match a digit between 0 to 9

{n} - To match n instances of preceding element


About The Author
Prince Verma
About The Author Prince Verma Author of this book, 'Quick Guide For SQL', Prince
Verma, an alumnus of NIT Surat, is a currently a Software Engineer, who has worked on
several projects. Apart from this book, he has launched a similar certification course on
Udemy named 'Introduction to MySQL'.

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.

He can be contacted at: -


Contact No. : - +91 7096277820
Email: - [email protected]

You might also like