sql
sql
● What is SQL?
● SQL stands for Structured Query Language. It is used for accessing and
new record.
based on the specified primary key for a record within the WHERE
● What is RDBMS?
Tables are the database objects that are used in RDBMS. Table is a collection
of related data entries and it consists of numerous columns and rows.
Page 1 of 4
ID Ninja’s City
Name
101 Lokesh Ninja Kolkata
102 Kuldeep Ninja Bhopal
103 Ojasv Ninja Shimla
SQL MySQL
Page 2 of 4
● COMMENTS IN MySQL –
Page 3 of 4
Customer entity and with attributes(column):-
In this above customer entity we have used branch_id as the attribute that
we can use to set up a relationship with Branch entity. Similarly, in the
given ER Model below we can understand the different relationships that
exist between different entities.
Page 4 of 4
Introduction to SQL
We store data in SQL in the form of tables. Tables are the simplest objects
(structures) for data storage that exist in a database.
Below we have given an example of table - Defining a table using SQLCommands -
From a SQL command for each column attribute we have defined a specific data
type. In case of ID it is INT i.e Integer and similarly in case of Ninja_Name it is
VARCHAR i.e a variable length string.
Datatype Description
Datatype Description
DATE Format: YYYY-MM-DD. The supported range is from
'1000-01-01' to '9999-12-31'
format. But we can use the DATE_FORMAT() function to format the date time when
Eg:
FROM tablename
TINYINT: The Boolean data type is not specifically defined in MySQL, but it uses
this boolean value from the already existing Numeric data type explained above.
Syntax:
<column-name> BOOLEAN
);
There are two Advanced Data types in MySQL. They are:
1. Spatial types - Using this type, we can store single or multi-point data
(geometrical or geographical).
2. JSON types - JSON stands for JavaScript Object Notation. JSON has some
can be used to define the database schema. DDL commands are mentioned
below -
Page 1 of 3
● DELETE: Delete rows from a table.
TCL commands are used to manage transactions done in the database. Some
ROLLBACK.
using Tables)?
● Definition - Dual Tables are dummy tables that are already created by
● You can find the current time of the system, can perform mathematical
Syntax :
SELECT <STATEMENT_TO_EXECUTE>;
Page 2 of 3
Example:
Output: 1100
Page 3 of 3
Filtering and Sorting Data
● Filtering:
SQL filters are used to obtain a specific subset of the data items from the database. The filter
is an SQL WHERE clause that provides a set of comparisons that must be true in order for a
NOTE - MySQL is case sensitive regarding the data which is present in the table, but not for
the general syntax, use of keywords, table name and column name.
Ex-
For the above ER Diagram, To get data associated with a particular address we will use a filter.
SELECT *
FROM Branch
WHERE address = “Delhi”;
1
Here, address is the key and “Delhi” is the value which makes the key-value pair for the
Ex- For the same ER Model - We want to find a loan with an interest rate of either 25% or 35%.
SELECT *
FROM Loan_type
WHERE base_interest_rate = 25 OR base_interest_rate = 35;
In the above examples, we saw how we can use filters i.e., conditionals inside the
WHERE clause.
Ex - For the same ER Model - We want to find customer details whose date of birth is before
SELECT *
FROM Customer
WHERE date_of_birth < ’16-06-2000’;
General Form -
The general form of the WHERE clause in our query as a Conditional statement
SELECT column_name(s)
FROM T_name
WHERE conditions;
● BETWEEN Operator –
The BETWEEN operator in WHERE clause selects value within the specified range, so that we
Syntax:
SELECT <column-name>
FROM <table-name>
WHERE <column-name>
BETWEEN value-1 AND value-2;
2
To filtering the strings:
● Wildcards:
Symbol Description
Few examples:
3. '_r%'- Finds any values that have "r" in the second position.
4. 'a%o'- Finds any values that start with "a" and end with "o"
Ex- Write a SQL query to fetch branch id whose address starts with B,
SELECT id
FROM Branch
WHERE address = “B%”;
Query: -
SELECT column_name(s)
FROM T_name
WHERE column_name
LIKE '%o_r%';
Page 3 of 8
● Filtering Operators
1. IN operator: The IN operator allows specifying multiple values in a WHERE clause. Note: -
General Form:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, …);
Equivalent-
SELECT column_name(s)
FROM table_name
WHERE column_name = value1 OR column_name = value2 OR column_name = value3,
…….;
2. NOT IN operator: NOT IN operator is the same as IN operator in syntax and it just negates
the conditional i.e., NOT IN operator will return true for only conditionals which are false for
IN operator.
General Form:
SELECT column_name(s)
FROM table_name
The above query will return column_name which is not equal to value1,
value2, etc. which is nothing but a negation of what we get from IN operator.
3. IS NULL: The IS NULL operator is used to test for empty values (NULL values).
Ex- We want to find the branch ID for which address is NULL, the query is given below –
SELECT branch_id
FROM branch
WHERE address IS NULL;
Page 4 of 8
Similarly, we also have IS NOT NULL operator which we use to check for non-empty
values.
Ex: We want to find a branch ID for which address is not NULL, a query is given
below-
SELECT branch_id
FROM branch
WHERE address IS NOT NULL;
Apart from these operators, there are several comparison operators which can
be used to filter data. These operators are particularly used when filtering is
based on some numeric fields. The various comparison operators are shown in
Operato Meaning
r
= Equal to
General Form:
SELECT columnList(s)
FROM table_name
Page 5 of 8
There are some Logical operators which can also be used to filter data.
Following are some logical operators that can be used to filter data along with
Operato Meaning
r
SELECT columnList(s)
FROM table_name
SELECT columnList(s)
FROM table_name
● NOT operator
SELECT columnList(s)
FROM table_name
WHERE column_name NOT IN (value1, value2, …);
Order of precedence is the order in which the filtering conditions will be evaluated. This is
one of the important concepts when you are preparing for interviews. The order of
Page 6 of 8
Order Operator
Evaluated
1 Arithmetic operators
2 Concatenation operator
3 Comparison conditions
5 [NOT] BETWEEN
8 OR logical condition
● Sorting:
Sorting is simply done using the ORDER BY keyword which is used to sort the
General form:
SELECT id
FROM account
ORDER BY id ASC;
Page 7 of 8
Q. What is the difference between Sorting and Filtering?
Ans. Sorting is arranging the data in ascending or descending order according to the
user's needs
Whereas Filtering is used to fetch the data that a user might need for a use case.
Page 8 of 8
Grouping
● Grouping in SQL is done using GROUP BY. GROUP BY statement groups rows
that have the same values into summary rows, like “find the accounts in each
branch”
● After using the GROUP BY clause, all the rows with the same values of the
● Note that all the column names mentioned after SELECT statement shall be
values of a column and return the result into a single value. The aggregate
Function Description
● General form:-
Query:-
SELECT column_name(s)
FROM T_name
WHERE condition
GROUP BY column_name(s);
Page 1 of 5
Ex-
Table : Ninjas
ID Ninja’s City
Name
COUNT(ID) City
1 Shimla
2 Kolkata
3 Bhopal
Note: In the above query we have used the aggregate function COUNT().
Now if we want only CITY with COUNT = 2 (lets say), we have to use the HAVING
clause.
Page 2 of 5
SELECT COUNT(ID), City
FROM Ninjas
GROUP BY City
HAVING COUNT(ID) = 2;
Output:
COUNT(ID) City
2 Kolkata
● General form:-
Query:-
SELECT column_name(s)
FROM T_name
WHERE condition
GROUP BY column_name(s)
HAVING condition;
● COUNT(*) function -
This function counts (sums up) the total number of rows that satisfy the specified
records in a table.
Syntax:
SELECT COUNT(*)
FROM <table-name>;
ID Ninja’s City
Name
Page 3 of 5
QUERY -
SELECT COUNT(*)
FROM Ninjas;
Output:
6
● HAVING clause :
The HAVING clause is used to filter group of data as per specified conditions. It is
The HAVING and WHERE clause serve similar purpose, but there is slight
difference regarding the usage in the query and output in the result.
Syntax :
SELECT <column-name>
FROM <table-name>
GROUP BY <column-name>
HAVING <condition>
Example: Find the total number of ninjas who belongs to Bhopal, also display the
City column.
Table: Ninjas
ID Ninja’s City
Name
101 Lokesh Ninja Kolkata
Page 4 of 5
QUERY –
SELECT City, COUNT(*)
FROM Ninjas
GROUP BY City
HAVING City = “Bhopal”;
Output:
City COUNT(*)
Bhopal 3
WHERE HAVING
WHERE clause is used to filter data HAVING clause is used to filter group
It can be used with SELECT, UPDATE It can only be used with SELECT
operations.
SELECT <column-name>
FROM <table-name>
WHERE <condition>
GROUP BY <column-name>
HAVING <condition>
ORDER BY <column-name>
Page 5 of 5
Queries with Tables & Constraints
a. Add column
Syntax:
ALTER TABLE <table-name>
ADD <column-name> <data-type>;
Page 1 of 10
b. Drop column
Syntax:
ALTER TABLE <table-name>
DROP COLUMN <column-name>;
c. Modify column
Syntax-1:
ALTER TABLE <table-name>
MODIFY COLUMN <column-name> <data-type>;
Syntax-2:
ALTER TABLE <table-name>
ALTER COLUMN <column-name> <data-type>;
This is the table we want to create with Primary Key as Id, below is the query for it -
o Each table has only one primary key. But a primary key can have one or more
the conditions that apply to a single field Primary Key applies to multiple field
o Let's say for the same customer table we want id and branch id as PRIMARY
table yet -
In case we want to make any attribute a Primary Key we need to use ALTER
Note:- Primary Key column should already have been declared as NOT NULL at
Page 3 of 10
Similarly, we can declare the composite primary key (assuming columns or
We have learned to declare the primary key and all the conditions
associated with column(s) to be the Primary key now let us discuss how to
mentioned -
Now we want to delete id primary key we will use ALTER and DROP keyword as
mentioned below -
have any number of foreign key(s). Let’s us say we have a customer and
Table : customer
Page 4 of 10
Table : account
id balance customer_id
Page 5 of 10
Below we have mentioned an example of a UNIQUE Constraint –
CREATE TABLE customer
(
id INT NOT NULL,
name VARCHAR(255) NOT NULL,
UNIQUE(id)
);
If we want only customers with a minimum balance of let us say 3000 or more
Page 6 of 10
● What is the DEFAULT constraint?
DEFAULT constraint sets a default value for a column. This default value is added to
Let us say for all the accounts we want to have a balance of 100 when an
account is added we can make sure of this by using the DEFAULT constraint
done below-
Page 7 of 10
Below mentioned table summarises the constraint -
Constraint Description
TRUNCATE removes all the records from the table. Below is the given
general form -
After running this query all the data from the account table will be cleared but the
Whereas in the case of DROP the whole table will be dropped from the database i.e
Page 8 of 10
● Difference between Delete, Drop and Truncate:
● ON DELETE CASCADE:
ON DELETE CASCADE is an option that can be added to the table while creating
constraints. It is used to delete rows from the child table automatically when
● ON UPDATE CASCADE:
ON UPDATE CASCADE is an option that can be added to the table while creating
constraints. Suppose there is a situation where we have two tables such that
primary key of one table is the foreign key for another table. if we update the
primary key of the first table then using the ON UPDATE CASCADE foreign key of the
Page 9 of 10
Information Schema
General form:
Page 10 of 10
Modifying Data
● Modifying Data mainly comes under Data Manipulation Language in SQL. There
1. INSERT
2. UPDATE
3. DELETE
4. RENAME
For explaining all of these operations we will use the below-mentioned table-
● INSERT
To perform the INSERT operation, we have to use the INSERT INTO statement. There
Mention both the column names and the values you want to insert -
Output:-
Mention only the values of for the columns. Make sure the order of
Page 1 of 6
occurrence of values is the same as the order of columns -
Output:-
For storing date and time fields in SQL we have the following date fields
General form:
VALUES (value1,value2…);
Example:
statement.
General Form -
UPDATE TABLE
SET column1 = value1, column2 = value2, …
WHERE condition;
Note: Always remember to use WHERE with the UPDATE statement otherwise
& SQL.
Query:
UPDATE Student
SET Student_name = ‘Kuldeep Ravaliya’ AND Course = ‘MongoDB & SQL’
WHERE Student_id = 2;
Output:
● Additional Information:
The functions below can be used in the INSERT and UPDATE clauses to add the
1. CURDATE(): The CURDATE() function returns the current date value in the
General Form:
SELECT CURDATE();
Page 3 of 6
2. CURTIME(): The CURTIME() returns the current time value in HHMMSS.uuuuuu
General Form:
SELECT CURTIME();
● DELETE
To perform the delete operation on the existing table/database we use the DELETE
statement
General form-
Ex-
Output:
Note- We can also delete all the records from the table using - DELETE FROM
TABLE - this all table rows will be deleted but the table will still be there for use.
● RENAME
Ex- We can change the name of the student table ‘Student’ to ‘Student1’ using
Page 4 of 6
Output:
Student1 -
● REPLACE INTO
Ex-
Output:
This is used to modify existing data This works exactly like INSERT, but if
in the table. an old row in the table has the same
value as a new role for a PRIMARY
KEY or a UNIQUE index, the old row
is deleted before the new row is
inserted.
SET SQL_SAFE_UPDATES = 0;
Page 5 of 6
After this command, the DELETE clause can be used.
SET SQL_SAFE_UPDATES = 1;
Safe mode exists to disallow update and delete operations without the use of
PRIMARY KEY in a WHERE clause. Hence, we can prevent the loss of data with the
● DELETE CASCADE :
This clause is used to delete multiple records from more than one table, linked
● UPDATE CASCADE :
This clause is used to update multiple records from more than one table, linked
● REPLACE :
● It is used to update the already present tuple data in a relation.
● When we use REPLACE query with the help of WHERE clause in PRIMARY KEY
● If there is no reference of the primary key, then a new tuple entry will be
Page 6 of 6
Managing Database
● Creation of Database -
o Syntax:
CREATE DATABASE IF NOT EXISTS <database-name>;
● Using Database -
o Syntax:
USE <database-name>;
● Deleting Database-
o Syntax:
DROP DATABASE <database-name>;
● Displaying Database-
o Syntax:
SHOW DATABASES;
Page 1 of 1
Joining Tables
● What are JOINS in SQL?
JOIN is an operation that exists in SQL that helps us to combine rows from two or
● Types of JOIN:-
1. INNER JOIN - This returns a resulting table that has matching values
● LEFT OUTER JOIN - This returns a resulting table that all the data from left
● RIGHT OUTER JOIN - This returns a resulting table that all the data from
right table and the matched data from the left table
● FULL OUTER JOIN - This returns a resulting table that contains all data when
3. CROSS JOIN – This returns all the cartesian products of the data present in
both tables. Hence, all possible variations are reflected in the output.
4. SELF JOIN – It is used to get the output from a particular table when the same
Page 1 of 10
NOTE-1 : It is not compulsory to use the “OUTER” keyword in the joins. We can specify
the join as LEFT JOIN or LEFT OUTER JOIN, there is no difference or error in the output.
Output – All the data from a particular table. This kind of query is used in the case
of multiple tables.
NOTE-3: The JOINS can be used interchangeably (LEFT OUTER & RIGHT OUTER etc),
and a query can be amended to change the particular join into another alternate join, but
the output will be the same. There will be no error in doing so.
● INNER JOIN -
General form -
SELECT *
FROM TableA
INNER JOIN TableB
ON TableA.column1 = TableB.column1;
Example:
Table 1:- NINJA table is shown below -
Page 2 of 10
Table 2:- ORDERS
1 SQL 1
2 WEBDEV 2
3 CP 3
4 ALGO 4
Output:-
General form -
SELECT *
FROM TableA
LEFT JOIN TableB
ON TableA.column1 = TableB.column1;
Page 3 of 10
Example:
Table 1: NINJA table is shown below -
Table 2: ORDERS
1 SQL 1
2 WEBDEV 2
3 CP 3
4 ALGO 4
ORDERS.Order_ID;
Output:-
Page 4 of 10
● RIGHT JOIN -
General form -
SELECT *
FROM TableA
RIGHT JOIN
TableB
ON TableA.column1 = TableB.column1;
Example:
Table 1: NINJA table is shown below -
1 SQL 1
2 WEBDEV 2
3 CP 3
4 ALGO 4
Page 5 of 10
Query:
SELECT Ninja_ID, Name, City, Product_name
FROM NINJA
RIGHT JOIN ORDERS
ON NINJA.Ninja_ID = ORDERS.Order_ID;
Output:
● FULL JOIN -
General form -
SELECT * FROM TableA
LEFT JOIN TableB ON TableA.column1 = TableB.column2 UNION
SELECT * FROM TableA
RIGHT JOIN TableB ON TableA.column1 = TableB.column2
Example:
Table 1: NINJA
Page 6 of 10
Table 2: ORDERS
1 SQL 1
2 WEBDEV 2
3 CP 3
4 ALGO 4
Query:
SELECT Ninja_ID, Name, City, Product_name
FROM NINJA
LEFT JOIN ORDERS ON NINJA.Ninja_ID = ORDERS.Order_ID
UNION
SELECT Ninja_ID, Name, City, Product_name
FROM NINJA
RIGHT JOIN ORDERS ON NINJA.Ninja_ID = ORDERS.Order_ID;
Output:
Page 7 of 10
● CROSS JOIN & FULL JOIN -
The CROSS join produces the cartesian product of all the data present in both
JOIN and gives the value output as per the WHERE clause condition.
● CROSS JOIN –
General form -
SELECT *
FROM TableA CROSS JOIN TableA;
Example:
Table 1: NINJA
1 SQL 1
2 WEBDEV 2
3 CP 3
4 ALGO 4
Page 8 of 10
Query:
Output:
Page 9 of 10
● SELF JOIN -
General form -
SELECT A.Col_1, B.Col_2 FROM TableA A, TABLEA B
WHERE A.COL_NAME = B.COL_NAME
AND <condition>;
Example:
Table 1: NINJA table is shown below -
SELECT a.Ninja_ID,
b.Name FROM NINJA a,
NINJA b
WHERE a.Ninja_ID = b.Ninja_ID
AND a.City = “Jaipur”
Output:-
Ninja_ID Name
1 Ojasv Ninja
Page 10 of 10