SQL Notes
Q. What is a Database?
- A Database is an Organised Collection of Data in a Format that Can Be Easily
Accessed or stored in a Computer System.
- A Software Application used to manage our Database is Called Database
Management System
- Users Use Database Management System(DBMS) to access Database.
- Databases are of 2 Types:
1. Relational Databases(SQL) - Data Stored in Tabular Format
2. Non-Relational Databases(NoSQL) - Data Stored in Non-Tabular Format
Q. What is SQL?
- Stands for Structured Query Language.
- SQL is a Programming Language used to interact with relational databases.
- SQL is a Case Insensitive Language.
- SQL is Used to perform CRUD operations: Create, Read, Update, and Delete.
Database Structure
- Here a Table is a Collection of Rows and Columns.
- Columns represent Schema/Attribute.
- Rows Represent Records.
Creating and Deleting Database
Syntax: CREATE DATABASE db_name;
Example: CREATE DATABASE university;
Syntax: DROP DATABASE db_name;
Example: DROP DATABASE university;
Creating Table
Syntax: USE db_name;
Example: USE university;
Syntax: CREATE TABLE table_name(
column_name1 datatype constraint,
column_name2 datatype constraint,
column_name3 datatype constraint,
);
Example: CREATE TABLE student(
Id INT PRIMARY KEY,
Name VARCHAR(50),
Age INT NOT NULL,
);
Insert Data Into Tables
Syntax: INSERT INTO table_name VALUES(x,”y”,z)
Example: INSERT INTO student VALUES (1,”Piush Das”,20)
INSERT INTO student VALUES (2,”Sibayan Banik”,22)
INSERT INTO student VALUES (3,”Raman Paul”,23)
SQL Datatypes
- In SQL, data types define the kind of data that can be stored in a column or
Variable.
Types of SQL Commands
- DDL(Data Definition Language): create, alter, rename, truncate and drop
- DQL(Data Query Language): select
- DML(Data Manipulation Language): insert, update, and delete
- DCL(Data Control Language): grant and revoke permissions to users
- TCL(Transaction Control Language): start transaction, commit, rollback
View Tables and Databases
Syntax: SHOW DATABASES;
Syntax: SHOW TABLES;
Table Related Queries
Syntax: SELECT * FROM table_name;
Example: SELECT * FROM students;
-It Will output all the rows of the student table in tabular format
Keys in Databases
Primary Key:
- It is a Column(or set of columns) in a table that uniquely identifies each row.
- Primary Key is Unique and Not Null.
- There is Only 1 Primary Key in a Table.
Foreign Key:
- It is a Column(or set of columns) in a table that refers to the primary key of
another table.
- Foreign Keys can have Duplicate and Null Values.
- There can be Multiple Foreign Key in a Table.
Constraints
SQL constraints are used to specify rules for data in a table.
- NOT NULL: Columns Cannot Have Null Values.
Constraints
Syntax: column_name datatype NOT NULL
Example: name varchar(50) NOT NULL;
- UNIQUE: All Values in Columns Should be Different.
Syntax: column_name datatype UNIQUE;
Example: name varchar(50) UNIQUE;
- PRIMARY KEY: Makes a Column Not Null and Unique but used only for one
column which would uniquely identify a row
Syntax: column_name datatype PRIMARY KEY;
Example: ID int Primary Key;
- FOREIGN KEY: Used to create links between two tables.
- Example: CREATE TABLE emp(
emp_id int,
FOREIGN KEY(emp_id) references manager(id)
):
- DEFAULT: Sets the default Value of a Column.
Syntax: column_name datatype DEFAULT value;
Example: salary int DEFAULT 25000;
- CHECK: It can limit all the values allowed in a column.
Example: CREATE TABLE temp(
age INT CHECK (age >= 18
);
Where Clause
To Define Some Condition
Syntax:
SELECT column FROM table_name
WHERE conditions;
Example:
SELECT * FROM students
WHERE marks > 80 ;
Using Operators in WHERE
- 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)
Limit Clause
Sets an upper limit on the number of (tuples)rows to be returned
Syntax:
SELECT col1, col2 FROM table_name
LIMIT number;
Example:
SELECT * FROM student
LIMIT 3;
Order By Clause
To sort in ascending (ASC) or descending order (DESC)
Syntax:
SELECT col1, col2 FROM table_name
ORDER BY col_name(s) ASC;
Example:
SELECT * FROM student
ORDER BY city ASC;
Aggregate Functions
Aggregate functions perform a calculation on a set of values and return a single value.
COUNT( ) , MAX( ) , MIN( ) , SUM( ) , AVG( )
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
columns.
- Generally, we use group by with some aggregation function.
Example: Count the number of students in each city
SELECT count(name), city;
FROM student
GROUP BY city;
Having Clause
Similar to Where i.e. applies some condition on rows.
Used when we want to apply any condition after grouping.
Example: Count the number of students in each city where max marks cross 90.
SELECT count(name), city;
FROM student
GROUP BY city
HAVING max(marks)>90;
General Order
SELECT column(s)
FROM table_name
WHERE condition
GROUP BY column(s)
HAVING condition
ORDER BY column(s) ASC;
Table related Queries
UPDATE: to update existing rows
Syntax:
UPDATE table_name
SET col1 = val1, col2 = val2
WHERE condition;
Example:
UPDATE student
SET grade = ‘S’
WHERE grade = ‘A’ ;
DELETE: to delete existing rows
Syntax:
DELETE FROM table_name
WHERE condition;
Example:
DELETE FROM student
WHERE marks < 33 ;
ALTER TABLE table_name;
ADD Column
Syntax:
ALTER TABLE table_name
ADD COLUMN column_name datatype constraint;
DROP Column
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
RENAME Table
Syntax:
ALTER TABLE table_name
RENAME TO new_table_name;
CHANGE Column (rename)
Syntax:
ALTER TABLE table_name
CHANGE COLUMN old_name new_name new_datatype new_constraint;
MODIFY Column (Modify Datatype, Constraint)
Syntax:
ALTER TABLE table_name
MODIFY col_name new_datatype new_constraint ;
TRUNCATE - Delete Table‘s Data
Syntax:
TRUNCATE TABLE table_name ;
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.
Example:
CREATE TABLE student(
Id INT PRIMARY KEY,
courseID INT,
FOREIGN KEY(courseID) REFERENCES course(id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Joins in SQL
Join is used to combine rows from two or more tables, based on a related column
between them.
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;
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;
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;
FULL JOIN
Returns all records when there is a match in either the left or right table
Syntax:
SELECT column(s)
FROM tableA FULL JOIN tableB
On tableA.col_name = tableB.col_name;
SQL Sub Queries
A Subquery or Inner query or a Nested query is a query within another SQL query.
It Involves Two Select Statements.
Syntax for Subquery in Where Clause:
SELECT column(s)
FROM table_name
WHERE col_name operator
(subquery);
Syntax for Subquery in From Clause:
SELECT column(s)
FROM (subquery) ;
Views in SQL
A view is a virtual table based on the result-set of an SQL statement.
Syntax:
CREATE VIEW viewname AS
SELECT column(s) FROM table_name ;
● A View always shoes up-to-date data. The database engine recreates the view,
everytime a user queries it.