0% found this document useful (0 votes)
9 views61 pages

SQL

The document provides an overview of databases, specifically focusing on relational databases and SQL (Structured Query Language). It covers fundamental concepts such as database structure, types of SQL commands, keys, constraints, and various SQL operations including creating, updating, and querying data. Additionally, it discusses joins, subqueries, and views, highlighting their importance in managing and retrieving data effectively.

Uploaded by

Abhishek Shigvan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
9 views61 pages

SQL

The document provides an overview of databases, specifically focusing on relational databases and SQL (Structured Query Language). It covers fundamental concepts such as database structure, types of SQL commands, keys, constraints, and various SQL operations including creating, updating, and querying data. Additionally, it discusses joins, subqueries, and views, highlighting their importance in managing and retrieving data effectively.

Uploaded by

Abhishek Shigvan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 61

`D̀ atabase

Database is collection of data in a format that can be easily accessed (Digital) A software

application used to manage our DB is called DBMS (Database Management System)


Types of
Databases Non-relational

Relational Data stored in tables (NoSQL) data not

stored in tables

** We use SQL to work with relational


DBMS
What is SQL?
Structured Query

SQL is a programming language used to interact with relational


Language
It is used to perform CRUD
databases.
operations : Create Read Update
Delete
Database
Structure
Databas
e
Table Table
1 2
Dat Dat
a a
What is a
table?
Student
table
Creating our First
Database
Our first SQL Query

CREATE DATABASE
db_name;

DROP DATABASE
db_name;
Creating our First
Table

USE db_name;
CREATE TABLE table_name
column_name1 datatype constraint,

(column_name2 datatype constraint,


column_name2 datatype constraint

);
SQL Datatypes
They define the type of values that can be stored in a
column
SQL
Datatypes
Signed & Unsigned

TINYINT UNSIGNED (0 to
255)
TINYINT (-128 to 127)
Types of SQL
Commands
DDL (Data Definition Language) : create, alter, rename, truncate &
drop
DQL (Data Query Language) :
select
DML (Data Manipulation Language) : select, insert, update &
delete
DCL (Data Control Language) : grant & revoke permission to
users
TCL (Transaction Control Language) : start transaction, commit, rollback
etc.
Database related
Queries
CREATE DATABASE db_name; CREATE

DATABASE IF NOT EXISTS db_name;

DROP DATABASE db_name; DROP

DATABASE IF EXISTS db_name;

SHOW

DATABASES;
Table related Queries
Create
CREATE TABLE table_name
(column_name1 datatype constraint,
column_name2 datatype constraint, );
Table related
Queries
Select & View ALL columns

SELECT * FROM
table_name;
Table related
Queries
Insert
INSERT INTO table_name
(colname1, colname2)
VALUES (col1_v1, col2_v1),
(col1_v2, col2_v2);
Keys
Primary Key It is a column (or set of columns) in a table that uniquely identifies each

row. (a unique id) There is only 1 PK & it should be NOT null.

Foreign Key A foreign key is a column (or set of columns) in a table that refers to the primary key in

another table.

There can be multiple FKs.

FKs can have duplicate & null values.


Keys
table1 -
table2 - City
Student
Understanding Foreign Keys and NULL Values
•Foreign Key: A foreign key is a field (or a set of fields) in one table that uniquely identifies a row
in another table. The table containing the foreign key is known as the child table, and the table
containing the candidate key is the parent table.
•NULL Values in Foreign Keys:
• In a database, a foreign key can reference a row in another table or it can be left empty, i.e.,
contain a NULL value.
• When a foreign key has a NULL value, it essentially means that the relationship is not
applicable or that the relationship between the child and parent tables is unknown.

CREATE TABLE Departments ( CREATE TABLE Employees (


DepartmentID INT PRIMARY KEY, EmployeeID INT PRIMARY KEY,
DepartmentName VARCHAR(100) EmployeeName VARCHAR(100),
DepartmentID INT,
); FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);
In the Employees table:
•The DepartmentID column is a foreign key that references the DepartmentID column in the
Departments table.
•If an employee doesn’t belong to any department, the DepartmentID in the Employees
table could be set to NULL.

Why Allow NULL Values in Foreign Keys?


1.Optional Relationships: A NULL value in a foreign key indicates that the relationship
between the child and parent table is optional. For example, an employee might not be
assigned to any department initially.
2.Data Flexibility: It allows flexibility in the data model, particularly during data entry when
the related data might not be available or applicable at the time.
3.Design Considerations: In some scenarios, not every record in a child table needs to have
a corresponding record in the parent table. Allowing NULL values helps in such cases.
Constraints

SQL constraints are used to specify rules for data in a


NOT NULL columns cannot have a null
table.

UNIQU value
all values in column are different
E

PRIMARY makes a column unique & not null but used only for
KEY one
Constraint
s
FOREIGN prevent actions that would destroy links between
KEY tables

DEFAUL sets the default value of a


T column
Constraint
s
CHEC it can limit the values allowed in a
K column
Create this sample table Insert this data
Select in Detail

used to select any data from the

Basic Syntax
database
SELECT col1, col2 FROM table_name;

To Select ALL
SELECT * FROM table_name;
Where Clause
To define some
conditions

SELECT col1, col2 FROM table_name


WHERE conditions;
Where Using Operators in
WHERE
Clause
Arithmetic Operators : +(addition) , -(subtraction), *(multiplication), /(division), %
(modulus)
Comparison Operators : = (equal to), != (not equal to), > , >=, <,
<=
Logical Operators : AND, OR , NOT, IN, BETWEEN, ALL, LIKE,
ANY
Bitwise Operators : & (Bitwise AND), | (Bitwise
OR)
Operators
AND (to check for both conditions to be
true)

OR (to check for one of the conditions to be


true)
Operator
s
Between (selects for a given
range)

In (matches any value in the


list)

NOT (to negate the given


condition)
Limit Clause
Sets an upper limit on number of (tuples)rows to be
returned

SELECT col1, col2 FROM table_name


LIMIT number;
Order By Clause
To sort in ascending (ASC) or descending order
(DESC)

SELECT col1, col2 FROM table_name


ORDER BY col_name(s) ASC;
Aggregate Functions
Aggregare functions perform a calculation on a set of values, and return a single

COUNT(
value.

) Get Maximum
MAX( )
Marks
MIN( )
SUM( )

AVG(
Get )
Average
marks
Group By Clause
Groups rows that have the same values into summary rows. It collects data
from multiple records and groups the result by one or more column.

*Generally we use group by with some aggregation


function.

Count number of students in each


city
Having Clause
Similar to Where i.e. applies some condition on rows.
Used when we want to apply any condition after
grouping.

Count number of students in each city where max marks cross


90.
General
Order
SELECT column(s) FROM
table_name WHERE
condition GROUP BY
column(s) HAVING condit
ion ORDER BY column(s)
ASC;
Having Clause
Similar to Where i.e. applies some condition on rows.
Used when we want to apply any condition after
grouping.

Count number of students in each city where max marks cross


90.
Table related
Queries
Update (to update existing
rows)
UPDATE table_name SET
col1 = val1, col2 = val2
WHERE condition;
Table related
Queries
Delete (to delete existing
DELETE
rows) FROM table_name
WHERE condition;
Cascading for FK
On Delete Cascade When we create a foreign key using this option, it deletes the referencing
rows in the child table when the referenced row is deleted in the parent table which has a
primary key.

On Update Cascade
When we create a foreign key using UPDATE CASCADE the referencing rows are updated in the
child

table when the referenced row is updated in the parent table which has a primary key.
Table related
Queries
Alter (to change the schema)
ADD Column
ALTER TABLE table_name ADD COLUMN
column_name datatype constraint;

DROP Column
ALTER TABLE table_name
DROP COLUMN column_name;

RENAME Table
ALTER TABLE table_name
RENAME TO new_table_name;
Table related
Queries
CHANGE Column
(rename)TABLE table_name CHANGE COLUMN old_name new_name
ALTER
new_datatype new_constraint;

MODIFY Column (modify datatype/


constraint)
ALTER TABLE table_name MODIFY col_name
new_datatype new_constraint;
ADD DROP
Column Column

MODIFY Column RENAME


Table

CHANGE Column
(rename)
Table related
Queries
Truncate (to delete table's
data)
TRUNCATE TABLE table_name
;
Joins in SQL
Join is used to combine rows from two or more tables, based on a related column between
them.
Types of
Joins

Inner Left Right Full


Join Join Join Join

Outer
Joins
Inner Join
Returns records that have matching values in both
tables

Syntax
SELECT column(s) FROM tableA INNER
JOIN tableB ONtableA.col_name =
tableB.col_name;
SELECT * FROM student INNER JOIN
Inner course ONstudent.student_id =
course.student_id;
Join
course
Example student

Result
Left Join
Returns all records from the left table, and the matched records
from the right table

Syntax
SELECT column(s) FROM tableA LEFT
JOIN tableB ONtableA.col_name =
tableB.col_name;
SELECT * FROM student as s
Left LEFT JOIN course as c

Join ONs.student_id = c.student_id;

course
Example student

Result
Right Join
Returns all records from the right table, and the matched
records from the left table

Syntax
SELECT column(s) FROM tableA RIGHT
JOIN tableB ONtableA.col_name =
tableB.col_name;
SELECT * FROM student as s
Right RIGHT JOIN course as c

Join ONs.student_id = c.student_id;

course
Example student

Result
Full Join
Returns all records when there is a match in either left or right
table

Syntax in
MySQL LEFT JOIN
UNION
RIGHT
JOIN
Full
Exampl
Join cours
e e
student

Resul
t
Think &
Ans
Qs:Write SQL commands to display the right exclusive join :

Left Exclusive Right Exclusive


Join Join
Self Join
It is a regular join but the table is joined with
itself.

Syntax
SELECT column(s) FROM
table as a JOIN table as b
ONa.col_name = b.col_name;
Self
Example
Join
Employee

Result
Union
It is used to combine the result-set of two or more SELECT
statements. Gives UNIQUE records.

To use it :
every SELECT should have same no. of
columns columns must have similar data types
columns in every SELECT should be in same
order

Syntax
SELECT column(s) FROM
tableA UNION SELECT
column(s) FROM tableB
SQL Sub Queries
A Subquery or Inner query or a Nested query is a query within another SQL
Quer
query. It involves 2 select statements. y

Syntax Sub

SELECT column(s) FROM Query

table_name WHERE
col_name operator
( subquery );
SQL Sub Queries
Example Get names of all students who scored more than

class average.

Step 1. Find the avg of class Step 2. Find the


names of students with marks > avg
SQL Sub Queries
Example Find the names of all students with even

roll numbers.

Step 1. Find the even roll numbers Step 2. Find


the names of students with even roll no
SQL Sub Queries
Example with FROM Find the max marks

from the students of Delhi

Step 1. Find the students of Mumbai Step 2. Find


their max marks using the sublist in step 1
MySQL Views
A view is a virtual table based on the result-set of an SQL
statement.

*A view always shows up-to-date data. The


database engine recreates the view, every
time a user queries it.

You might also like