0% found this document useful (0 votes)
9 views

sql

The document provides an introduction to SQL, explaining its purpose as a Structured Query Language for accessing and manipulating data using CRUD operations. It covers the basics of RDBMS, specifically MySQL, and details various SQL commands, data types, and filtering techniques. Additionally, it discusses the differences between SQL and MySQL, and outlines the structure of SQL statements including DDL, DML, DQL, DCL, and TCL.

Uploaded by

Dilbagh Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

sql

The document provides an introduction to SQL, explaining its purpose as a Structured Query Language for accessing and manipulating data using CRUD operations. It covers the basics of RDBMS, specifically MySQL, and details various SQL commands, data types, and filtering techniques. Additionally, it discusses the differences between SQL and MySQL, and outlines the structure of SQL statements including DDL, DML, DQL, DCL, and TCL.

Uploaded by

Dilbagh Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Introduction to SQL

● What is SQL?

● SQL stands for Structured Query Language. It is used for accessing and

manipulating the data.

● SQL uses CRUD operations to communicate with the databases. CRUD

stands for Create, Read, Update and Delete procedures.

● Here is a breakdown of CRUD operations -

▪ CREATE procedures: Performs the INSERT statement to create a

new record.

▪ READ procedures: Reads the records of the table

▪ UPDATE procedures: Executes an UPDATE statement on the table

based on the specified primary key for a record within the WHERE

clause of the statement.

▪ DELETE procedures: Deletes a specified row in the WHERE clause.

● What is RDBMS?

RDBMS stands for Relational Database Management System. It is the basis


for SQL, and for all modern database systems Ex- MS SQL, MySQL, etc.

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.

Table is the simplest form of data storage in a Relational Database. Below is an


example of table named Ninjas which contains attributes ID, Ninja’s Name and
City-

Page 1 of 4
ID Ninja’s City
Name
101 Lokesh Ninja Kolkata
102 Kuldeep Ninja Bhopal
103 Ojasv Ninja Shimla

In this course we will be using an open-source RDBMS i.e MySQL. This


database uses Structured Query Language for all CRUD operations and other
procedures.

MySQL uses the Client-Server model. In this model a "client" is a front-end


application that uses the services provided by a MySQL server. And this whole
use of the services takes place through SQL Queries.

Difference between MySQL and SQL :

SQL MySQL

SQL is a Structured Query Language. MySQL is an RDBMS to store,


It is useful to manage relational retrieve, modify and administrate a
databases. database using SQL.

SQL is a query language. MYSQL is used as an RDBMS


database.

To query and operate database Allows data handling, storing,


systems. modifying, deleting in a tabular
format.

Page 2 of 4
● COMMENTS IN MySQL –

There are 3 ways to add comments in MySQL.

● From # character, till the end of the line.


Syntax -
# this is a single-line comment.
● From - - (double-dash without space) till the end of line.
Syntax -
—This is a comment.
● Can add up multiple lines of comments using this starting and ending
syntax.
Syntax -
/* This is multiple line of comment. */

● Example: Banking System -

Understanding basic MySQL database using Banking System with help of ER


Model.
Note:- ER Model :

1. Entity - Real world object (Can be understand as a tables)


2. Attributes - These are the properties of the entity.

In our Banking system we will be considering below mentioned entities:


1. Customer
2. Account
3. Branches
4. Loan
5. Loan type(Loan_type)
6. Transactions
7. Cards

Page 3 of 4
Customer entity and with attributes(column):-

customer_id branch_id first_name last_name Gender D.O.B

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

● SQL Data Types-

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 -

CREATE TABLE CUSTOMERS’


(
ID INT NOT NULL,
Ninaja_Name VARCHAR (20) NOT NULL,
Ninja_Age INT NOT NULL,
Ninja_Address CHAR (25) ,
Ninja_Goal CHAR(25),
PRIMARY KEY (ID)
);

This command will result into creation of a table -

ID Ninja_Name Ninja_Age Ninja_Address Ninja_Goal

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.

While choosing a data type for a column attribute we have to think of


1. Value we want to represent - like if it is a name(Character data type
will be most suitable, VARCHAR) or Age(Numerical data type will be
more relevant, INT)
2. Space or Memory that value will occupy - like if we are taking customer
feedback we need to store value in a variable character data type,
VARCHAR.
Below we have given three main types of data types -

● String Data Types -

Datatype Description

CHAR(size) A FIXED length string (can contain letters, numbers, and


special characters). The size parameter specifies the
column length in characters - can be from 0 to 255. Default
is 1
VARCHAR(size) A VARIABLE length string (can contain letters, numbers,
and special characters). The size parameter specifies the
maximum column length in characters - can be from 0 to
65535
BINARY(size) Equal to CHAR(), but stores binary byte strings. The size
parameter specifies the column length in bytes. Default is
1
VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size
parameter specifies the maximum column length in bytes.

● Numeric Data Types:


Datatype Description
BIT(size) A bit-value type. The number of bits per value is
specified in size. The size parameter can hold a value
from 1 to 64. The default value for size is 1.
TINYINT(size) A very small integer. Signed range is from -128 to 127.
Unsigned range is from 0 to 255. The size parameter
specifies the maximum display width (which is 255)
INT(size)/ Signed range is from -2147483648 to 2147483647.
INTEGER(size) Unsigned range is from 0 to 4294967295. The size
parameter specifies the maximum display width (which is
255)
FLOAT(p) A floating point number. MySQL uses the p value to
determine whether to use FLOAT or DOUBLE for the
resulting data type. If p is from 0 to 24, the data type
becomes FLOAT(). If p is from 25 to 53, the data type
becomes DOUBLE()
DECIMAL(size, d) The number of digits after the decimal point is specified in
the d parameter. The maximum number for size is 65. The
maximum number for d is 30. The default value for size is
10. The default value for d is 0.
● Date and Time Data Types:

Datatype Description
DATE Format: YYYY-MM-DD. The supported range is from
'1000-01-01' to '9999-12-31'

DATETIME This is a date and time combination in the format:


YYYY-MM-DD hh:mm:ss. The supported range starts from
'1000-01-01 00:00:00' and end at '9999-12-31 23:59:59'.
TIME This is a time Format: hh:mm:ss. The supported range
is starts from '-838:59:59' and ends at '838:59:59'

TIMESTAMP TIMESTAMP values are stored as the number of seconds.


Format: YYYY-MM-DD hh:mm:ss. The supported range is
from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07'
UTC.

MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS'

format. But we can use the DATE_FORMAT() function to format the date time when

we want to display it.

Eg:

SELECT DATE_FORMAT (column_name, '%m/%d/%Y %H:%i')

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.

The values to be stored in this case will be 0 and 1.

Syntax:

CREATE TABLE <table-name>

<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

standard format that we need to follow in order to easily store information.

This structure is in the form of a KEY-VALUE pair.


SQL Commands
● Types of SQL statements/commands -

1. DDL(Data Definition language)

2. DQL/DRL(Data Query Language or Data Retrieve Language)

3. DML(Data Manipulation Language)

4. DCL(Data Control Language)

5. TCL(Transaction Control Language)

● DDL( Data Definition Language) -


DDL or Data Definition Language actually consists of the SQL commands that

can be used to define the database schema. DDL commands are mentioned

below -

● CREATE: Create TABLE, DATABASE, INDEX or VIEW

● DROP: Delete TABLE, DATABASE, or INDEX

● ALTER TABLE: Add/Remove columns from table

● TRUNCATE: Removes all records from a table.

● RENAME: Rename an existing object in the table.

● DQL(Data Query Language) -


DQL consists of commands that can feasibly retrieve the data from the

database using a single command. DQL commands are mentioned below -

● SELECT: Select data from database.

● DML(Data Manipulation Language) -


DML commands are used to make modifications to the database. DQL

commands are given below -

● INSERT: Insert data into a table.

● UPDATE: Update table data.

Page 1 of 3
● DELETE: Delete rows from a table.

● DCL(Data Control Language)-


DCL commands are used to grant and take back authority from users.

DCL commands are given below -

● GRANT: Access privileges to the database.

● REVOKE: Withdraws the user’s access privileges.

● TCL(Transaction Control Language)-

TCL commands are used to manage transactions done in the database. Some

of the TCL commands are given below -

● BEGIN TRANSACTION: It is used to begin a transaction.

● COMMIT: It used to apply changes and end transactions.

● ROLLBACK: It used to discard changes and end transactions.

● SAVEPOINT: It points within the groups of transactions in which to

ROLLBACK.

● Concept of Dual tables:


Can we use the SELECT command without using FROM keyword (or without

using Tables)?

● This could be achieved using the Dual Tables concept.

● Definition - Dual Tables are dummy tables that are already created by

MySQL itself. The significance of dual tables is that we can make

temporary changes without disturbing the user-defined tables.

● You can find the current time of the system, can perform mathematical

calculations using dual tables, convert the string from lower-case to

upper-case and vice-versa, etc.

Syntax :

SELECT <STATEMENT_TO_EXECUTE>;

Page 2 of 3
Example:

1. SELECT 1000 + 100;

Output: 1100

2. SELECT ucase(“coding ninjas”);

Output CODING NINJAS

Other keywords - NOW(), current_timestamp(); will display time.

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

data item to be returned.

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.

Given below, gives us a branch that has Delhi as an address.

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

WHERE clause condition.

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

16th June 2000.

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

to filter the data is given below:

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

do not need to specify all entries exhaustively.

Syntax:

SELECT <column-name>
FROM <table-name>
WHERE <column-name>
BETWEEN value-1 AND value-2;

2
To filtering the strings:

● Wildcards:

Symbol Description

% Represents zero or more characters

_ Represents a single character

Few examples:

1. 'a%' - Find any value that starts with "a".

2. '%or%' - Finds any values that have "or" in any position.

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%”;

We use wildcards with LIKE operators.

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

We can use multiple OR operators in place of IN operators as well.

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

WHERE column_name NOT IN (value1, value2, …);

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

the table below:

Operato Meaning
r
= Equal to

> Greater than

>= Greater than or equal


to
< Less than

<= Less than or equal to

<> Not equal to

General Form:

SELECT columnList(s)

FROM table_name

WHERE column_name operator value(s);

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

the syntax of writing the query with the specific operator.

Operato Meaning
r

AND Returns true if both component conditions are


true

OR Returns true if either component condition is


true

NOT Returns true if the following condition is false

● AND requires both conditions to be true:

SELECT columnList(s)

FROM table_name

WHERE condition1 AND column_name LIKE ‘%a_;

● OR requires either condition to be true.

SELECT columnList(s)

FROM table_name

WHERE condition1 OR column_name LIKE ‘%a_;

● 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

precedence of the filtering component of SQL is given below:

Page 6 of 8
Order Operator
Evaluated
1 Arithmetic operators

2 Concatenation operator

3 Comparison conditions

4 IS [NOT] NULL, LIKE, [NOT] IN

5 [NOT] BETWEEN

6 NOT logical condition

7 AND logical condition

8 OR logical condition

● Sorting:

Sorting is simply done using the ORDER BY keyword which is used to sort the

result set in ascending or descending order.

General form:

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Ex- Enlist account ID in ascending order.

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

specified column name will get summarized into a single row.

● Note that all the column names mentioned after SELECT statement shall be

repeated in GROUP BY, in order to successfully execute the query.

● Aggregate functions - These are used to perform calculations on multiple

values of a column and return the result into a single value. The aggregate

functions are explained below:

Function Description

COUNT() The number of rows returned based on condition.

AVG() The average of the value is returned in the selected column.

MAX() The maximum value of a column is returned.

MIN() The minimum value of a column is returned.

SUM() The sum of the values in a specified column is returned.

● 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

101 Lokesh Ninja Kolkata

102 Kuldeep Ninja Bhopal

103 Raju Ninja Kolkata

104 Ojasv Ninja Shimla

105 Abhi Ninja Bhopal

106 Tarun Ninja Bhopal

Find the number of Ninjas in each city ?

SELECT COUNT(ID), City


FROM Ninjas
GROUP BY City
ORDER BY COUNT(ID) DESC;
Output:

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

condition, and if there is no condition, then it simply returns the number of

records in a table.

Syntax:

SELECT COUNT(*)
FROM <table-name>;

Example: Find the total number of records in the table Ninjas.


Table: Ninjas

ID Ninja’s City
Name

101 Lokesh Ninja Kolkata

102 Kuldeep Ninja Bhopal

103 Raju Ninja Kolkata

104 Ojasv Ninja Shimla

105 Abhi Ninja Bhopal

106 Tarun Ninja Bhopal

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

used with GROUP BY clause to get the results of column operations.

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

102 Kuldeep Ninja Bhopal

103 Raju Ninja Kolkata

104 Ojasv Ninja Shimla

105 Abhi Ninja Bhopal

106 Tarun Ninja Bhopal

Page 4 of 5
QUERY –
SELECT City, COUNT(*)
FROM Ninjas
GROUP BY City
HAVING City = “Bhopal”;

Output:

City COUNT(*)

Bhopal 3

● Usage of HAVING and WHERE clause.

WHERE HAVING

WHERE clause is used to filter data HAVING clause is used to filter group

based on certain specific condition. of data based on certain conditions.

It can be used without use of GROUP It cannot be used without using

BY clause. GROUP BY clause.

It is used before GROUP BY clause. It is used after GROUP BY clause.

It can be used with SELECT, UPDATE It can only be used with SELECT

and DELETE statements. statement.

It is implemented in row operations. It is implemented in column

operations.

Syntax with position of various clauses -

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

● Create table clause:


Syntax - 1: Both Constraint and Key are declared with column definition.

CREATE TABLE <table-name> (


<column-name-1> <data-type>,
<column-name-2> <data-type> CONSTRAINT,
<column-name-3> <data-type> KEY,
<column-name-4> <data-type> CONSTRAINT KEY
);

Syntax - 2: Key declared at the end.

CREATE TABLE <table-name> (


<column-name-1> <data-type>,
<column-name-2> <data-type>,
<column-name-3> <data-type> CONSTRAINT,
KEY_NAME1(<column-name1>),
KEY_NAME2(<column-name2>)
);

Syntax - 3: Both Constraint and Key declared at the end.

CREATE TABLE <table-name> (


<column-name-> <data-type>,
<column-name-> <data-type>,
KEY_NAME1(<column-name>),
KEY_NAME2(<column-name>),
CONSTRAINT1(<column-name>)
);

● ALTER table clause:


The various variations in ALTER table clause are explained in the following.

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

Below is a customer table with details related to the customer:

id branch_id first_name last_name DOB gender

This is the table we want to create with Primary Key as Id, below is the query for it -

CREATE TABLE customer


(
id INT NOT NULL,
branch_id INT NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(20),
DOB INT,
gender CHAR(6),
PRIMARY KEY(id)
);

In the above query, we have declared id as PRIMARY KEY.

● What is the Primary key?


o Primary Key helps us to uniquely identify tuples of a relation. It cannot be NULL

and have UNIQUE values.

o Each table has only one primary key. But a primary key can have one or more

columns(fields) as part of the Primary Key.


Page 2 of 10
o In case we have multiple fields as Primary key it is called Composite Key and all

the conditions that apply to a single field Primary Key applies to multiple field

Composite Key as well.

o Let's say for the same customer table we want id and branch id as PRIMARY

KEY we can use the below-mentioned declaration if we haven't declared the

table yet -

CREATE TABLE customer


(
id INT NOT NULL,
branch_id INT NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(20),
DOB INT,
gender CHAR(6),
PRIMARY KEY(id, branch_id)
);

Let's say we have declared table, as mentioned below:

CREATE TABLE customer


(
id INT NOT NULL,
branch_id INT NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(20),
DOB INT,
gender CHAR(6)
);

In case we want to make any attribute a Primary Key we need to use ALTER

keyword for that as mentioned below -

ALTER TABLE CUSTOMER


ADD PRIMARY KEY (ID);

Note:- Primary Key column should already have been declared as NOT NULL at

the time of creating the table.

Page 3 of 10
Similarly, we can declare the composite primary key (assuming columns or

attributes we want to use are declared as NOT NULL) as done below -

ALTER TABLE CUSTOMERS


ADD CONSTRAINT Pkey_Custid PRIMARY KEY (ID, NAME);

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

delete a primary key - Let us say have declared a table as below

mentioned -

CREATE TABLE customer


(
id INT NOT NULL,
branch_id INT NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(20),
DOB INT,
gender CHAR(6),
PRIMARY KEY(id)
);

Now we want to delete id primary key we will use ALTER and DROP keyword as

mentioned below -

ALTER TABLE CUSTOMERS


DROP PRIMARY KEY;

● What is Foreign Key?


Foreign Key refers to the Primary Key of another table. Each table can

have any number of foreign key(s). Let’s us say we have a customer and

account table with details mentioned below -

Table : customer

id branch_id first_name last_name DOB gender

Page 4 of 10
Table : account

id balance customer_id

Declaring customer table -

CREATE TABLE customer


(
id INT NOT NULL,
branch_id INT NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(20),
DOB INT,
gender CHAR(6),
PRIMARY KEY(id)
);

Declaring account table with Primary Key and Foreign Key -

CREATE TABLE account


(
id INT NOT NULL,
balance INT,
customer_id INT NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(customer_id) REFERENCES customer(id) );

● What is a UNIQUE constraint?


UNIQUE constraints make sure that all the values in a column which is declared

UNIQUE are different.

Then, what is the difference between UNIQUE and PRIMARY KEY?

UNIQUE PRIMARY KEY

UNIQUE constraint column need not PRIMARY KEY constraint


be a PRIMARY KEY. automatically has a UNIQUE
constraint.
Multiple columns in a table There is only one PRIMARY KEY in a
can have a UNIQUE table
constraint

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

Using UNIQUE constraint in multiple columns

CREATE TABLE customer


(
id INT NOT NULL,
name VARCHAR(255) NOT NULL,
CONSTRAINT UNIQUE(id, name)
);

● What is the CHECK constraint?


The CHECK is used to put limitations on the value range that we can put
in a column.
For example let's say we have the account table as given below,

account_id balance customer_id

If we want only customers with a minimum balance of let us say 3000 or more

we can use the CHECK constraint to ensure that.

CREATE TABLE account


(
account_id INT NOT NULL,
balance INT NOT NULL,
customer_id INT NOT NULL,
CHECK(balance >= 3000)
);

Page 6 of 10
● What is the DEFAULT constraint?

DEFAULT constraint sets a default value for a column. This default value is added to

all the new records unless other value is specified.

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

CREATE TABLE account


(
account_id INT NOT NULL,
balance INT DEFAULT 100,
customer_id INT NOT NULL,
);
We can drop the default constraint by using DROP keyword –

ALTER TABLE account


ALTER balance DROP DEFAULT;

Also, if suppose we haven’t initialised the balance we can later modify as

done below-

ALTER TABLE account


MODIFY balance DEFAULT 100;

Page 7 of 10
Below mentioned table summarises the constraint -

Constraint Description

CHECK Determine whether the value is valid or not from a


logical expression

FOREIGN Link between two tables by one specific column of


KEY both tables. The specified column in one table must
be a PRIMARY KEY and referred by the column of
another table known as a FOREIGN KEY.

UNIQUE Maintains the uniqueness of a column in a table.


More than one UNIQUE column can be used in a
table.

NOT NULL column can not contain any NULL value

PRIMARY Enforces the table to accept unique data for a


KEY specific column and is a unique index for accessing
the table faster.

● What is TRUNCATE? How is it different from DROP and DELETE?

TRUNCATE removes all the records from the table. Below is the given
general form -

TRUNCATE TABLE account;

After running this query all the data from the account table will be cleared but the

table will still exist.

Whereas in the case of DROP the whole table will be dropped from the database i.e

table record and schema will be cleared from the database.

Also, DELETE is used to delete the record of a particular row or conditionals -

DELETE FROM account where account_id = XYZ;

Page 8 of 10
● Difference between Delete, Drop and Truncate:

Delete Drop Truncate

DML command DDL command DDL command

Removes one, Removes the entire Removes all the


some or all the table structure. records from the
records in the table.
table.

Is a slow operation Relatively faster Fastest of all.

● 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

similar rows in the parent table get deleted.

● 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

second table automatically get updated.

● How to rename the table and column?

Rename a table from cust to customers –

ALTER TABLE cust


RENAME TO customers;

Rename column name to the surname in customers table -

ALTER TABLE customers


RENAME name TO surname;

Page 9 of 10
Information Schema

We have an in-built view in MySQL called information_schema, which holds all

details about the constraints on a particular table. INFORMATION_SCHEMA

provides access to information about the MySQL server, such as database

metadata, database or table names, column data types, and permissions.

General form:

SELECT COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME,


REFERENCED_TABLE_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_NAME = 'table_name';

Page 10 of 10
Modifying Data

● Modifying Data mainly comes under Data Manipulation Language in SQL. There

are mainly four types of operations we can perform on a table/database.

1. INSERT

2. UPDATE

3. DELETE

4. RENAME

For explaining all of these operations we will use the below-mentioned table-

(Assume it to be empty at the beginning)

Table Name - Student

Student_id Student_name Batch Course

● INSERT

To perform the INSERT operation, we have to use the INSERT INTO statement. There

are two ways to use this statement as mentioned below.

Mention both the column names and the values you want to insert -

INSERT INTO Student (Student_id, Student_name, Batch, Course)


VALUES (1, Ojasv, 2018, SQL);

Output:-

Student_id Student_name Batch Course


1 Ojasv 2018 SQL

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 -

INSERT INTO Student


VALUES (2,Kuldeep, 2018, MongoDB);

Output:-

Student_id Student_name Batch Course

1 Ojasv 2018 SQL

2 Kuldeep 2018 MongoDB

For storing date and time fields in SQL we have the following date fields

1. DATE - format YYYY-MM-DD

2. YEAR - format YYYY or YY

3. DATETIME - format: YYYY-MM-DD HH:MI: SS

4. TIMESTAMP - format: YYYY-MM-DD HH:MI: SS

General form:

INSERT INTO table_name

VALUES (value1,value2…);

Example:

Consider a Table name : order with following attributes

o_id pname o_date

INSERT function will be shown below:

INSERT INTO order


VALUES (‘1’, ‘table’, ‘2022-01-13’);

o_id pname o_date


1 table 2022-01-13
Page 2 of 6
● UPDATE

To perform update operations on a table/database we have to use UPDATE

statement.

General Form -

UPDATE TABLE
SET column1 = value1, column2 = value2, …
WHERE condition;

Note: Always remember to use WHERE with the UPDATE statement otherwise

values will be updated for all the columns.

Ex- UPDATE Kuldeep to Kuldeep Ravaliya and MongoDB to MongoDB

& SQL.

Query:

UPDATE Student
SET Student_name = ‘Kuldeep Ravaliya’ AND Course = ‘MongoDB & SQL’
WHERE Student_id = 2;
Output:

Student_id Student_name Batch Course


1 Ojasv 2018 SQL
2 Kuldeep Ravaliya 2018 MongoDB & SQL

● Additional Information:
The functions below can be used in the INSERT and UPDATE clauses to add the

current timestamp in the column value.

1. CURDATE(): The CURDATE() function returns the current date value in the

'YYYYMMDD' format or ‘'YYYY-MM-DD' format. It depends on whether a

string or numeric value is used in the table function.

General Form:

SELECT CURDATE();
Page 3 of 6
2. CURTIME(): The CURTIME() returns the current time value in HHMMSS.uuuuuu

format or ‘HH:MM: SS’ format. It depends on whether a string or numeric value

is used in the table function.

General Form:

SELECT CURTIME();

● DELETE

To perform the delete operation on the existing table/database we use the DELETE

statement

General form-

DELETE FROM table


WHERE condition;

Ex-

DELETE FROM Students


WHERE Student_name = ‘Kuldeep Ravaliya’;

Output:

Student_id Student_name Batch Course


1 Ojasv 2018 SQL

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

To perform Rename operation on a table we can use RENAME statement -

Ex- We can change the name of the student table ‘Student’ to ‘Student1’ using

RENAME statement, syntax for that –

RENAME TABLE Student TO Student1;

Page 4 of 6
Output:
Student1 -

Student_id Student_name Batch Course


1 Ojasv 2018 SQL

● REPLACE INTO

To perform Replace operation on a table we can use REPLACE INTO statement.


General form-

REPLACE [INTO] T_name(column_name(s))


VALUES(value_list);

Ex-

REPLACE INTO Student1(student_name)


VALUES (‘1’,‘LOKESH’, 2019,’SQL’);

Output:

Student_id Student_name Batch Course


1 Lokesh 2018 SQL

● Difference between UPDATE & REPLACE INTO?

UPDATE REPLACE INTO

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.

● DELETE in Safe Mode -


By default safe update mode is enabled. We can disable it by this command:

SET SQL_SAFE_UPDATES = 0;

Page 5 of 6
After this command, the DELETE clause can be used.

To enable the safe mode, we can use the following command:

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

help of DELETE in Safe Mode.

● DELETE CASCADE :
This clause is used to delete multiple records from more than one table, linked

through foreign key.

● UPDATE CASCADE :
This clause is used to update multiple records from more than one table, linked

through foreign key.

● 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

column, then the row present will get update.

● If there is no reference of the primary key, then a new tuple entry will be

added in the relation, with updated values.

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

more tables based on a related column between them.

● Types of JOIN:-
1. INNER JOIN - This returns a resulting table that has matching values

from both the table or all the tables.

2. OUTER JOIN – We have 3 types of OUTER JOINS -

● LEFT OUTER JOIN - This returns a resulting table that all the data from left

table and the matched data from the right table

● 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

there is a match on left or right table data. It can be implemented using

the UNION operation.

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

table is joined to itself.

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.

NOTE-2 : Query - Table_Name.*

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 -

Ninja_ID Name CITY

1 Ojasv Ninja Jaipur

2 Tejas Ninja Trichy

3 Rejas Ninja Manipal

Page 2 of 10
Table 2:- ORDERS

Order_ID Product_name Ninja_ID

1 SQL 1

2 WEBDEV 2

3 CP 3

4 ALGO 4

SELECT Ninja_ID, Name, City, Product_name


FROM NINJA
INNER JOIN ORDERS
ON NINJA.Ninja_ID = ORDERS.Order_ID;

Output:-

Ninja_ID Name City Product_name


1 Ojasv Ninja Jaipur SQL

2 Tejas Ninja Trichy WEBDEV

3 Rejas Ninja Manipal CP


● LEFT JOIN -

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 -

Ninja_ID Name CITY

1 Ojasv Ninja Jaipur

2 Tejas Ninja Trichy

3 Rejas Ninja Manipal

5 Kejas Ninja Lucknow

Table 2: ORDERS

Order_ID Product_name Ninja_ID

1 SQL 1

2 WEBDEV 2

3 CP 3

4 ALGO 4

SELECT Ninja_ID, Name, City, Product_name


FROM NINJA
INNER JOIN ORDERS
ON NINJA.Ninja_ID =

ORDERS.Order_ID;

Output:-

Ninja_ID Name City Product_name


1 Ojasv Ninja Jaipur SQL
2 Tejas Ninja Trichy WEBDEV
3 Rejas Ninja Manipal CP
5 Kejas Ninja Lucknow NULL

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 -

Ninja_ID Name CITY

1 Ojasv Ninja Jaipur

2 Tejas Ninja Trichy

3 Rejas Ninja Manipal

5 Kejas Ninja Lucknow


Table 2: ORDERS

Order_ID Product_name Ninja_ID

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:

Ninja_ID Name City Product_name


1 Ojasv Ninja Jaipur SQL
2 Tejas Ninja Trichy WEBDEV
3 Rejas Ninja Manipal CP
NULL NULL NULL ALGO

● 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

Ninja_ID Name CITY

1 Ojasv Ninja Jaipur

2 Tejas Ninja Trichy

3 Rejas Ninja Manipal

5 Kejas Ninja Lucknow

Page 6 of 10
Table 2: ORDERS

Order_ID Product_name Ninja_ID

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:

Ninja_ID Name City Product_name

1 Ojasv Ninja Jaipur SQL

2 Tejas Ninja Trichy WEBDEV


3 Rejas Ninja Manipal CP
3 Kejas Ninja Lucknow NULL
NULL NULL NULL ALGO

Page 7 of 10
● CROSS JOIN & FULL JOIN -

The CROSS join produces the cartesian product of all the data present in both

tables. Hence, all possible combinations or variations will be reflected, also it

doesn’t have ON clause, as we don’t require any condition as we are joining

everything to everything. A FULL JOIN is a combination of LEFT JOIN and RIGHT

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

Ninja_ID Name CITY

1 Ojasv Ninja Jaipur

2 Tejas Ninja Trichy

3 Rejas Ninja Manipal

5 Kejas Ninja Lucknow


Table 2: ORDERS

Order_ID Product_name Ninja_ID

1 SQL 1

2 WEBDEV 2

3 CP 3

4 ALGO 4

Page 8 of 10
Query:

SELECT NINJA.Ninja_ID, NINJA.Name, NINJA.City,


ORDERS.Product_name FROM NINJA
CROSS JOIN ORDERS;

Output:

Ninja_ID Name City Product_name

1 Ojasv Ninja Jaipur SQL


2 Tejas Ninja Trichy SQL
3 Rejas Ninja Manipal SQL
5 Kejas Ninja Lucknow SQL
1 Ojasv Ninja Jaipur WEBDEV
2 Tejas Ninja Trichy WEBDEV
3 Rejas Ninja Manipal WEBDEV
5 Kejas Ninja Lucknow WEBDEV
1 Ojasv Ninja Jaipur CP
2 Tejas Ninja Trichy CP
3 Rejas Ninja Manipal CP
5 Kejas Ninja Lucknow CP
1 Ojasv Ninja Jaipur ALGO
2 Tejas Ninja Trichy ALGO
3 Rejas Ninja Manipal ALGO
5 Kejas Ninja Lucknow ALGO

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 -

Ninja_ID Name CITY

1 Ojasv Ninja Jaipur

2 Tejas Ninja Trichy

3 Rejas Ninja Manipal

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

You might also like