SQL Notes
SQL Notes
❖ What is Database?
• A database is used to store the collection of records in an organized form. It allows us to hold the
data into tables, rows, columns, and indexes to find the relevant information frequently.
• We can access and manage the records through the database very easily.
OR
• A database is a well-organized collection of data that is stored in an electronic format
• It is an electronic system which allows user to easily access, manipulate and update the data.
❖ ADVANTAGES:
1. Easy to use
2. It is secure
3. Client/ Server Architecture
4. Free to download
5. It is scalable/ expandable.
6. Speed
7. High Performance
I-RISE SOFTWARE TRAINING INSTITUTE
❖ SQL Commands:
Divided into four categories:
• Data Query Language (DQL Commands in SQL)
• Data Definition Language (DDL Commands in SQL)
• Data Manipulation Language (DML Commands in SQL)
• Data Control Language (DCL Commands in SQL)
➢ Select: -
• It is an SQL command which is used to fetch or retrieved the data from database.
SYNTAX: -
Select * from Table_Name;
• SELECT Column_Name_1, Column_Name_2, Column_ Name_ 3 FROM Table _Name;
Example: - Select * from signup;
▪ Example: -
Create table student (
Id int,
First_Name varchar (50).
Last_Name(50)
);
2) Alter:-
The ALTER statement is always used with "ADD", "DROP" and "MODIFY" commands according
to the situation.
1 ADD: To add a column in the table
Syntax: : alter table Table_name ADD Column name datatype;
Example :- alter table Students Details add Class varchar(50);
I-RISE SOFTWARE TRAINING INSTITUTE
2)Update:-
It is an SQL statement which is used to update the existing record into the table.
Syntax:- Update table_name SET column name= “Updated value” Where column name= existing
column value;
Example : UPDATE demo SET surname = “lmn” where id=1; (NOTE):
TO REMOVE THE ERROR for UPDATE QUERY USE FOLLOWING SYNTAX EXECUTE
FIRST-> SET SQL_SAFE_UPDATES = 0; (TO disABLE SAFE MODE)
Execute SECOND-> update MAD_STUDENTS9 set salary = 10000 where ID=3;
SET SQL_SAFE_UPDATES = 1; (NO NEED TO WRITE THESE QUERY)
3)Delete:-
It is an SQL statement which is used to delete the existing record from the table.
Syntax:- Delete from table name Where column name = column value (which defined as primary
key);
Example: delete from demo Where id= 1;
❖ CONSTRAINT
Constraint:- The constraint in SQL is used to specify the rule that allows or restricts what
value/data will be stored in table.
It also helps to limit the type of data that will be inserted inside the table.
1)NOTNULL
2)UNIQUE
3)Check
4)Default
5) Primary key
6) Foreign key
I-RISE SOFTWARE TRAINING INSTITUTE
1) NOT NULL :-
The NOT NULL constraint ensures that a column cannot have a NULL value.
It is used when a column must always contain a value, i.e., it's a mandatory field.
Empty string is allowed in NOT NULL column.
Example:-
2) UNIQUE :-
The UNIQUE constraint ensures that all values in a column are distinct.
This means no duplicate values can be stored in the specified column.
You can apply the UNIQUE constraint to one or more columns in a table.
Example :-
4) Default:-
This constraint is used to set a default value for the particular column where we have not
specified any value.
Example:-
CREATE TABLE student5 (
st_id int NOT NULL,
name varchar(255) NOT NULL,
sirname varchar(255),
address varchar(255) DEFAULT ‘Pune’
);
INSERT INTO student5 (st_id, name, surname, address) VALUES
(1, 'Ravi', 'Patil', DEFAULT), -- uses default: 'pune'
(2, 'Sita', 'Joshi', 'Mumbai'), -- explicit value
(3, 'Amit', 'Kumar', DEFAULT), -- uses default: 'pune'
(4, 'Reena', 'Shah', 'Delhi');
❖ With single query
insert into student5(st_id,name,surname) values (11,"kishor","Rathod");
I-RISE SOFTWARE TRAINING INSTITUTE
5) Primary key:-
The primary key constraint is used to identify each record in a table. The column contains the
primary key constraint it cannot be null OR empty. In a table there is only one primary key.
Based on the primary key you can join the two tables or more tables. The primary key
constraints column must have unique value.
• MySQL treats ' ' as a valid string value — it's not NULL.
• MySQL allows one empty string ('') as a valid PRIMARY KEY only if the column is
of type VARCHAR or CHAR.
• Primary key allows only one unique empty string, just like it would allow one unique
name like 'Ravi'.
• But if the column is of type INT or BIGINT, then trying to insert ' ' is often
automatically cast to 0, which might raise a different kind of error.
Example :-
CREATE TABLE student (
id INT primary key,
name VARCHAR(45) ,
surname VARCHAR(45) ,
Gmail VARCHAR(45)
);
6) Foreign key :-
This constraint is used to link two tables together. It is also known as the referencing key. A
foreign key column matches the primary key field of another table. It means that the foreign
key field in one table refer to the primary key field of another table.
I-RISE SOFTWARE TRAINING INSTITUTE
Example :-
Creating table:-
• Creating Table -> Cities
CREATE TABLE Cities (
ID INT PRIMARY KEY,
City varchar(50) NOT NULL
);
• Creating Table -> Student_Details
CREATE TABLE Student_Details(
Name varchar(50) NOT NULL,
Email varchar(50) NOT NULL,
S_Id INT,
FOREIGN KEY (S_Id) REFERENCES Cities(ID)
);
****Clauses****
• It is use to apply filters on the queries and get the filtered queries in result set.
1) Where
2) Order By
3) Distinct
4) Group By
5) Having
❖ Where clause:-
• It is an sql command which is used to extract only those record which full fill the
specified condition. The WHERE clause is used to filter records
• If you only want to see data for a certain department, salary range, or city, WHERE
helps filter out the rest.
Syntax: select * from table name where Column name = value;
Example : select * from employee where st_id=11;
❖ Order By clause:-
• It is an sql command which is used to sort the result set in ascending and descending
order.
• Used when you want results in a specific order like salary high to low, names
alphabetically, etc.
❖ Descending order:
Syntax: select * from Table name order by Column name desc;
Example : select * from employee order by Surname desc ;
❖ Ascending order:
Syntax: select * from Table name order by Column name asc;
Example : select * from employee order by Surname asc ;
I-RISE SOFTWARE TRAINING INSTITUTE
❖ Distinct:-
• Used to remove duplicate values from the result set. It ensures each returned row is
unique.
• If a column has repeating values (like department names), but you want to list each
unique one only.
Syntax :- SELECT DISTINCT column1 FROM table_name;
Example :- SELECT DISTINCT department FROM employees;
3) AVG (): -
4) MIN (): -
Returns the smallest (minimum) value in a column.
Finding the employee with lowest salary in the company.
Sysntax: - SELECT MIN(column_name) FROM table_name;
Example:- SELECT MIN(salary) AS min_salary FROM employees;
5) MAX(): -
Returns the largest (maximum) value in a column.
Finding the highest salary from employees.
3) Group By Clause:-
GROUP BY helps us group similar rows together and then apply calculations like total, average, or
count on each group.
Syntax: select Column name , Aggregate function from Table name group by column name
Example:
BY USING ONLY GROUP BY CLAUSE and USING AGGREGATE FUNCTION COUNT
1. select CITY, count(CITY) from employees group by CITY;
BY USING WHERE CLAUSE WITH GROUP BY CLAUSE
2. select CITY, count(CITY) from employees where Age>=27 group by CITY;
BY USING ONLY GROUP BY CLAUSE and USING AGGREGATE FUNCTION SUM
3.select AGE, sum(AGE) as "SUM OF AGE" from employees group by AGE;
BY USING ONLY GROUP BY CLAUSE and USING AGGREGATE FUNCTION MIN
4.select CITY, min(AGE) as "minimum age" from employees group by CITY;
BY USING ONLY GROUP BY CLAUSE and USING AGGREGATE FUNCTION MAX
5.select CITY, max(AGE) as "maximum age" from employees group by CITY;
BY USING ONLY GROUP BY CLAUSE and USING AGGREGATE FUNCTION AVG
6.select CITY, avg(AGE) as "average age" from employees group by CITY;
I-RISE SOFTWARE TRAINING INSTITUTE
❖ Having clause:-
• It is used to filter the record. As we know that we cannot use the where clause with
aggregate function that’s the reason we are using having clause
• HAVING Clause is used with the GROUP BY clause. It always returns the rows where the
condition is TRUE.
Syntax: Select Column name, aggregate function(column name)as “New column name” from
table name group by column name having aggregate function (column name) condition
Example:1: select CITY, avg(AGE) as "average age" from employees group by CITY having
avg(AGE)<32;
Example :2: select CITY, sum(salary) as "sum of salary" from employees group by CITY
having sum(salary)>55000;
Two aggregate functions on two column
Example:3: SELECT city, SUM(salary) AS total_salary, AVG(age) AS average_age
FROM employees GROUP BY city HAVING SUM(salary) > 5000 AND
AVG(age) < 30;
Syntax:-
For Column Alias:
SELECT column_name AS alias_name FROM table_name;
I-RISE SOFTWARE TRAINING INSTITUTE
Example:-
SELECT AGE AS selfage FROM employees;
Note: -
Aliases are temporary—they only exist during the execution of the SQL query.
The AS keyword is optional but recommended for clarity.
Avoid using reserved SQL keywords as alias names.
❖ OR Condition in SQL: -
The OR condition in SQL returns rows when any one of the conditions is true. It is more flexible
than AND.
Syntax: SELECT * FROM table_name WHERE condition1 OR condition2;
Example: - SELECT * FROM employees WHERE Age <= 29 OR City = “Pune”;
I-RISE SOFTWARE TRAINING INSTITUTE
❖ UNION: -
• The UNION operator combines the result sets of two or more SELECT statements into a
single result set.
• Eliminates Duplicate Rows: When you use UNION, the result will only contain unique
rows. Any duplicate rows are automatically removed.
Rules for Using UNION:
• Each SELECT statement involved in the UNION must have the same number of columns.
• The data type of the columns must be the same in each SELECT statement.
• The columns in each SELECT statement must appear in the same order.
❖ UNION ALL :-
The UNION ALL operator combines the result sets of two or more SELECT queries, just like
UNION, but does not remove duplicates.
Retains Duplicate Rows: If a row appears in multiple SELECT statements, it will appear multiple
times in the result set.
Use UNION ALL when you want to keep all rows from the combined result set, including
duplicates.
It's generally faster than UNION because it does not require the additional processing of removing
duplicates.
I-RISE SOFTWARE TRAINING INSTITUTE
❖ LIKE:-
1. In MySQL, LIKE condition is used to perform pattern matching to find the correct result.
2. It is used in SELECT, INSERT, UPDATE and DELETE statement with the combination of
WHERE clause.
3. There are two wildcards often used in conjunction with the LIKE operator:
• The percent sign (%) represents zero, one, or multiple characters
Example 1: select * from emp where Surname like 'p%' ; (characters start from pa)
Example 2: select * from emp where Surname like '%ri ' ; (characters ends from ri)
Example 3: select * from emp where Surname like '%au%' ; (characters between au)
Example 4: select * from emp where Surname like '%a%' ; (middle character a)
Example 4: select * from emp where surname like 's%a';
(Surnames starting with "S" and ending with "a")
Example 5: select * from emp where surname like '%an%'; (Surnames that contain "an")
I-RISE SOFTWARE TRAINING INSTITUTE
***JOINS***
It is used to combine rows from one or more tables based on related column in between them.
1. Inner Join
2. Left Join / Left Outer Join
3. Right Join/ Right Outer join
4. Full Join
INNER JOIN:-
It is returning only those records which is having matching values in both table and hides
other rows and columns.
RIGHT JOIN:-
The right join returns all the record from right table and matching record from left table.
The result shows null from the left side where there is no match.
I-RISE SOFTWARE TRAINING INSTITUTE
FULL JOIN:-
A FULL JOIN returns all rows when there is a match in either the left or right table. It will
include records with matching values from both tables and those with no match in either table.
Note: If you're using MySQL (which doesn’t support FULL JOIN)