SQL (notes) (1)
SQL (notes) (1)
by
APNA
COLLEGE
Database
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)
APNA
COLLEGE
Types of Databases
Relational Non-relational (NoSQL)
APNA
COLLEGE
Database Structure
Database
Table 1 Table 2
Data Data
APNA
COLLEGE
What is a table?
Student table
APNA
COLLEGE
Creating our First Database
Our first SQL Query
APNA
COLLEGE
Creating our First Table
USE db_name;
APNA
COLLEGE
SQL Datatypes
They define the type of values that can be stored in a column
APNA
COLLEGE
SQL Datatypes
Signed & Unsigned
APNA
COLLEGE
Types of SQL Commands
DDL (Data Definition Language) : create, alter, rename, truncate & drop
APNA
TCL (Transaction Control Language) : start transaction, commit, rollback etc.
COLLEGE
Database related Queries
SHOW DATABASES;
See database and table in microsoft and oracel Use
APNA
COLLEGE
Table related Queries DISTINCT
Select & View ALL columns * DISTINCT removes duplicate rows and records from the result set based on the selected columns.
* It is useful when you want to fetch only unique values or combinations of values from a table.
APNA
COLLEGE
Table related Queries
Insert
APNA
COLLEGE
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.
APNA
COLLEGE
Keys
table1 - Student table2 - City
APNA
COLLEGE
Constraints
SQL constraints are used to specify rules for data in a table.
PRIMARY KEY makes a column unique & not null but used only for one
APNA
COLLEGE
Constraints
FOREIGN KEY prevent actions that would destroy links between tables
APNA
COLLEGE
Constraints
CHECK it can limit the values allowed in a column
APNA
COLLEGE
Create this sample table Insert this data
APNA
COLLEGE
Select in Detail
used to select any data from the database
Basic Syntax
To Select ALL
APNA
COLLEGE
Where Clause
To define some conditions
APNA
COLLEGE
Where Clause
Using Operators in WHERE
Comparison Operators : = (equal to), != (not equal to), > , >=, <, <=
APNA
COLLEGE
Operators
APNA
COLLEGE
Operators
APNA
NOT (to negate the given condition)
COLLEGE
Limit Clause
Sets an upper limit on number of (tuples)rows to be returned In microsoft and oracle sql server
use type like this :-
SELECT TOP 3 *
FROM student;
SELECT col1, col2 FROM table_name
LIMIT number;
APNA
FROM student
WHERE marks > 90
ORDER BY marks DESC
COLLEGE
OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY;
Order By Clause
APNA
COLLEGE
Aggregate Functions
Aggregare functions perform a calculation on a set of values, and return a single value.
COUNT( )
MAX( )
Get Maximum Marks
MIN( )
SUM( )
AVG( )
APNA
COLLEGE
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.
APNA
COLLEGE
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.
APNA
COLLEGE
General Order
SELECT column(s)
FROM table_name
WHERE condition Put a condition on row's.
GROUP BY column(s)
HAVING condition Put a condition on group's.
ORDER BY column(s) ASC;
APNA
COLLEGE
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.
APNA
COLLEGE
Table related Queries
Update (to update existing rows)
UPDATE table_name
SET col1 = val1, col2 = val2
WHERE condition;
APNA
COLLEGE
Table related Queries
Delete (to delete existing rows)
APNA
COLLEGE
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.
APNA
COLLEGE
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
APNA
RENAME TO new_table_name; COLLEGE
Table related Queries
APNA
COLLEGE
ADD Column DROP Column
APNA
COLLEGE
Table related Queries
Truncate (to delete table's data)
APNA
COLLEGE
Joins in SQL
Join is used to combine rows from two or more tables, based on a related column between them.
Alias Name:-
* Column Alias is used to temporarily rename a column in the result set.
Ex:-
SELECT FirstName AS Name
FROM Students;
APNA
* Aliases don’t change the actual schema; they only affect the way
the query is written and the results are displayed.
COLLEGE
Types of Joins
Outer Joins
APNA
COLLEGE
Inner Join
Returns records that have matching values in both tables
Syntax
SELECT column(s)
FROM tableA
INNER JOIN tableB
ON tableA.col_name = tableB.col_name;
APNA
COLLEGE
SELECT *
Inner Join FROM student
Example INNER JOIN course
ON student.student_id = course.student_id;
student course
APNA
Result
COLLEGE
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
ON tableA.col_name = tableB.col_name;
APNA
COLLEGE
SELECT *
Left Join FROM student as s
Example LEFT JOIN course as c
ON s.student_id = c.student_id;
student course
Result
APNA
COLLEGE
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
ON tableA.col_name = tableB.col_name;
APNA
COLLEGE
SELECT *
Right Join FROM student as s
Example RIGHT JOIN course as c
ON s.student_id = c.student_id;
student course
Result
APNA
COLLEGE
Full Join
Returns all records when there is a match in either left or right table
Syntax in MySQL
LEFT JOIN
UNION
RIGHT JOIN
APNA
COLLEGE
Full Join
Example
course
student
Result
APNA
COLLEGE
Think & Ans
Qs: Write SQL commands to display the right exclusive join :
APNA
COLLEGE
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
ON a.col_name = b.col_name;
APNA
COLLEGE
Self Join
Example
Employee
Result
APNA
COLLEGE
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 APNA
SELECT column(s) FROM tableB
COLLEGE
SQL Sub Queries
A Subquery or Inner query or a Nested query is a query within another SQL query.
SELECT column(s)
FROM table_name
WHERE col_name operator
( subquery );
APNA
COLLEGE
SQL Sub Queries
Example
Get names of all students who scored more than class average.
Cartesian product :-
The Cartesian product (also known as the cross join) in SQL is a result of multiplying every row from
one table with every row from another table. It happens when there is no explicit relationship or
condition (like JOIN with ON clause) between the two tables, resulting in every possible combination
APNA
of rows from the two tables.
* Cartesian product returns all possible combinations of rows between two tables.
COLLEGE
* It can lead to large result sets if not used carefully, especially with large tables.
SQL Sub Queries
Example
Find the names of all students with even roll numbers.
APNA
COLLEGE
SQL Sub Queries
Example with FROM
Find the max marks from the students of Delhi
APNA
COLLEGE
MySQL Views
A view is a virtual table based on the result-set of an SQL statement.