0% found this document useful (0 votes)
111 views64 pages

SQL Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views64 pages

SQL Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Myntra Database

Sunday, August 18, 2024 9:15 AM

CREATE TABLE User (


user_id INT PRIMARY KEY,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone_number char(15),
password VARCHAR(100) NOT NULL
);
CREATE TABLE Product (
product_id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
category VARCHAR(50),
brand VARCHAR(50)
);
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
user_id INT,
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
total_amount FLOAT NOT NULL,
status VARCHAR(20),
FOREIGN KEY (user_id) REFERENCES User(user_id)
);
CREATE TABLE OrderItem (
order_item_id INT PRIMARY KEY,
order_id INT,
product_id INT,
quantity INT,
price FLOAT NOT NULL,
FOREIGN KEY (order_id) REFERENCES Orders(order_id),
FOREIGN KEY (product_id) REFERENCES Product(product_id)

Create table (7-8) Page 1


);
INSERT INTO User VALUES
(1, 'Vihaan','Rathod','vihaan@gmail.com', 9876543210,'password123'),
(2, 'Arjun','Singh','arjun@gmail.com',876543210,'password456'),
(3, 'Rohan','Singh','rohan@yahoo.com','+91-9876664531', 'password789'),
(4, 'Saanvi','Reddy','saanvi@gamil.com','7666453111', 'password101112'),
(5, 'Pranav','Sai','pranav@yahoo.com', '+91-7876664533','password131415'),
(6, 'Diya','Antony','diya@gmail.com', '7876664531','password161718'),
(7, 'Aadhya','Reddy','aadhya@gmail.com','+91-7776664531','password192021'),
(8, 'Siddharth','Shetty','siddharth@gmail.com', '776664531','password222324'),
(9, 'Nikhil','Sharma','nikhil@gmail.com','886664532','password252627'),
(10, 'Krishna','Reddy','krishna@gmail.com','+91-8886664535','password282930'),
(11, 'Viraj','Nair','viraj@gmail.com', '91-8766745345','password313233'),
(12, 'Neha','Nair','neha@gmail.com','91-976684539','password343536'),
(13, 'Sahana','Singh','sahana@gmail.com','91-976684566','password373839'),
(14, 'Kavya','Reddy','kavya@gmail.com', '26686539','password404142'),
(15, 'Ishanvi','Gowda','ishanvi.j@gmail.com', '9146684539','password434445'),
(16, 'Ravi','Gowda','ravi@gmail.com', null,'password1212');
INSERT INTO Product (product_id, name, description, price, category, brand) VALUES
(1, 'Slim Fit Jeans', 'Blue slim fit jeans for men', 1500, 'Clothing', 'Levis'),
(2, 'Printed T-shirt', 'Cotton t-shirt with graphic print', 2000, 'Clothing', 'Nike'),
(3, 'Running Shoes', 'Lightweight running shoes for women', 1000, 'Footwear', 'Adidas'),
(4, 'Backpack', 'Waterproof backpack with multiple compartments', 3000, 'Accessories', 'Puma'),
(5, 'Sunglasses', 'Stylish sunglasses with UV protection', 2500, 'Accessories', 'Zara'),
(6, 'Floral Print Dress', 'Flowy dress with floral print', 400, 'Clothing', 'Zara '),
(7, 'Casual Sneakers', 'Canvas sneakers for casual wear', 300, 'Footwear', 'Levis'),
(8, 'Leather Wallet', 'Genuine leather wallet with card slots', 1500, 'Accessories', 'Puma'),
(9, 'T-shirt', 'T-shirt with graphic print', 5000, 'Clothing', 'Hrx'),
(10, 'Smartwatch', 'Fitness tracker with heart rate monitor', 10000, 'Electronics', 'Apple'),
(11, 'Denim Jacket', 'Classic denim jacket for men', 450, 'Clothing', 'Arrow'),
(12, 'Ankle Boots', 'Leather ankle boots with buckle detail', 1400, 'Footwear', 'Arrow'),
(13, 'Crossbody Bag', 'Chic crossbody bag with chain strap', 1000, 'Accessories', 'Arrow'),
(14, 'Wireless Headphones', 'Bluetooth headphones with noise cancellation', 700, 'Electronics',
'Sony'),
(15, 'Printed Joggers', 'Stretchy Joggers with colorful print', 1200, 'Clothing', 'Hrx'),
(16, 'T-shirt', 'Cotton t-shirt', 2000, 'Clothing', 'Roadster');

Create table (7-8) Page 2


(16, 'T-shirt', 'Cotton t-shirt', 2000, 'Clothing', 'Roadster');

INSERT INTO Orders VALUES


(101, 1, "2021-01-10 10:47:20", 2000, 'Pending'),
(201, 2, "2021-02-12 14:57:33", 1500, 'Shipped'),
(301, 2, "2023-05-14 14:22:33", 7000, 'Delivered'),
(401, 4, "2023-05-14 14:57:33", 1000, 'Pending'),
(501, 3, "2024-01-22 09:40:15", 1000, 'Shipped'),
(601, 6, "2024-02-26 01:34:26", 2000, 'Pending'),
(701, 7, "2024-02-14 19:26:01", 1500, 'Shipped'),
(801, 5, "2024-04-17 17:09:51", 8000, 'Delivered'),
(901, 8, "2024-03-14 14:55:32", 9000, 'Pending'),
(902, 1, "2024-03-14 12:44:30", 5000, 'Shipped'),
(903, 3, "2024-04-16 17:08:51", 1000, 'Pending'),
(904, 9, "2024-04-17 17:08:51", 3000, 'Shipped'),
(905, 9, "2024-04-17 17:09:51", 4000, null),
(906, 9, "2024-04-17 17:08:51", 3000, null);

INSERT INTO OrderItem (order_item_id, order_id, product_id, quantity, price) VALUES


(111, 101, 2, 2, 4000),
(222, 201, 2, 1, 2000),
(333, 101, 3, 1, 1000),
(444, 401, 1, 2, 3000),
(555, 501, 5, 1, 2500),
(666, 301, 2, 2, 4000),
(777, 201, 4, 1, 3000),
(888, 601, 8, 1, 1500),
(999, 801, 7, 2, 300),
(9990, 701, 6, 1, 400),
(9991, 901, 9, 2, 10000),
(9992, 101, 10, 1, 10000),
(9993, 601, 11, 1, 450),
(9994, 801, 12, 2, 2800),
(9995, 701, 16, 1, 2000);

Create table (7-8) Page 3


Department
Sunday, September 15, 2024 12:35 PM

create table Department


(
department_id int primary key,
name varchar(25)
);

insert into Department(department_id, name) values


(1, "HR"),
(2, "Marketing"),
(3, "Finance"),
(4, "IT"),
(5, "Operations"),
(6, "Logistics");

create table Employee


(
e_id int primary key,
first_name varchar(25),
last_name varchar(25),
department_id int,
foreign key(department_id) references Department(department_id)
);

insert into Employee(e_id, first_name, last_name, department_id) values


(1, "Amit", "Gupta", 1),
(2, "Priya", "Sharma", 2),
(3, "Rahul", "Singh", 3),
(4, "Meera", "Patel", 4),
(5, "Arjun", "Kumar", 1),
(6, "Anjali", "Deshpande", 2),
(7, "Vivek", "Malhotra", 3),
(8, "Riya", "Nair", null),
(9, "Suresh", "Menon", null);

Create table (7-8) Page 4


05.
Sunday, September 15, 2024 12:36 PM

Creating tables and :-


1. create database june_b2;
2. system cls;
3. use june_b2;
4. show tables;
5. Creating table :-
CREATE Table TableName
(
column_name datatype,
column_name datatype,
column_name datatype,
column_name datatype,
……………………………………,
);

Ex -

CREATE Table Student


(
id int,
firstname varchar(25),
lastname varchar(25),
age int,
email varchar(15),
branch varchar(15)
);
6. insert into Student values
(1, "Ravi", "Singh", 24, "ravi@gmail.com", "EC"),
(1, "Ram", "Tripathi", 23, "ram@gmail.com", "EC");
a. SELECT * from Student;

DATA Types :-

Data Type Length


int 4 bytes
float 4 bytes
char 0 to 255 characters
varchar 65535 characters
Date '000-00-00' (YYYY-MM-DD)

Difference between char and varchar :-


• Even though both of them can store a sequence of characters but still char can only store 6
characters while varchar can store a lot more than that.
• Char data type is fixed data type (It will have the memory of fixed size even though we don't use
it) while varchar is the variable type of data type. Ex :-

Create table (7-8) Page 5


○ Char(5) :-
R A M

○ varchar(5) :-
R A M

In the varchar case the empty space will be used in future for storing some other data while in
char it will be left empty and memory will be wasted.

Create table (7-8) Page 6


06. Constraints :-
Sunday, September 15, 2024 12:37 PM

Constraints :-
It is a rule or restriction which is applied to a column.
1. NOT NULL (Value cannot be null)
2. UNIQUE (value cannot be repeated)
3. CHECK (Check the entered value is in the range ex age >=15)
4. DEFAULT (To fill the default value)
5. PRIMARY KEY (Not null and Unique)
6. Foreign Key

EX :-
CREATE TABLE Student
(
id int primary key,
firstName varchar(25) not null,
lastName varchar(25),
age int check(age >= 15),
branch varchar(5) default "CS"
);

Insertion into a table :-


There are 3 types of insertion -
1. By providing all the values -
insert into Student (1, "Ram", "Tripathi", 23, "EC");

2. If we don’t know some value provide as null :-


insert into Student (1, "Ram", "Tripathi", 23, null);

3. By providing some values, in this way the default value will be inserted for not mentioned
ones :-
insert into student(id, firstName, lastName, age) values(2, "Shyam, "SK", 24);

Here d_id is the foreign key for the faculty table.

Create table (7-8) Page 7


07. Composite primary key
Sunday, July 28, 2024 10:15 PM

Starting of 7th part is in the techM laptop :-

1. Creating Student table:-

create table student


(
s_id int primary key,
s_name varchar(25)
);

insert into student values(301, "Ravi"), (302, "Ramya"), (303, "Rahul");

2. Creating course table :-

create table course


(
c_id int primary key,
c_name varchar(25)
);

insert into course values(101, "CS"), (102,"Civil"), (103, "Mech");

Creating a Composite key Table:-

create table student_course


(
s_id int,
c_id int,
primary key(s_id, c_id),
foreign key(s_id) references student(s_id),
foreign key(c_id) references course(c_id)
);

insert into student_course values(301, 101);


insert into student_course values(301, 101);

Auto Increment mechanism :-

It is used in the unique column and also we can use it in primary key column because it must be
unique3.

create table person


(
id int primary key auto_increment,
name varchar(25)
);

Inserting values:-

Create table (7-8) Page 8


Inserting values:-

insert into person(name) values("Raju");

insert into person(Name) values("Kavya");

insert into person(name) values("itachi");

select * from person;

1 Raju
2 Kavya
3 Itachi

desc person; to check see the schema of the table(Description).

Create table (7-8) Page 9


07.
Sunday, September 15, 2024 12:38 PM

1. Creation of Department Table

create table department


(
d_id int primary key,
d_name varchar(15)
);

2. Insertion into Department :-

insert into department values(201, "CS"), (202, "EC"), (203, "Mech");

3. Creation of table faculty :-

create table faculty


(
f_id int primary key,
name varchar(15),
email varchar(25),
dept_id int,
foreign key(dept_id) references department(d_id)
);

4. Insertion into the faculty :-


• insert into faculty values(2, "Akash", "akash@gmail.com", 201);

• insert into faculty values(2, "Pooja", "pooja@gmail.com", 202);

There are two levels of constraints table level constraints and column level constraints.

Column level constraints :- We can declare them in the same line as declaring a variable. Ex default,
check, etc.

Table level constraints :- We can declare them in the end of the table creation. Ex - primary key, foreign
key. Here primary key is both table level and column level constraint but the foreign key is the table
level constraint.

Note :- We can't drop the parent class without dropping the child class

Create table (7-8) Page 10


07. b
Sunday, September 15, 2024 12:39 PM

1. Creating table course :-

create table course


(
c_id int primary key,
c_title varchar(15)
);

2. Creating table student :-

create table student


(
s_id int primary key,
s_name varchar(15)
);

Composition :-

create table student_course


(
student_id int,
course_id int,
primary key(student_id, course_id),
foreign key(course_id) references course(c_id),
foreign key(student_id) references student(s_id)
);

Create table (7-8) Page 11


08.
Sunday, September 15, 2024 12:38 PM

Create table (7-8) Page 12


08. Alter command
Sunday, August 4, 2024 12:32 PM

desc student; // to describe the table or to check the schema of the table.

(add) ALTER command :-


1. alter table student
add age int;

2. To add multiple columns in it :-


alter table student
add(gen char(1), dob date);

(rename) Rename Column :-

alter table student


rename column gen to gender;

(Drop)Drop Column :-

alter table student


drop dob;

(Modify) Changing the Data type of a column:-

We can change the datatype to any datatype only if no columns have the value. Ex - we can
change the gender column from char(1) to int only if no rows have the value of gender otherwise
we only can change it to varchar() from char.

alter table student


modify gender varchar(1);

(Modify) Changing the length of datatype :-

alter table student


modify gender varchar(6);

(ADD) Adding/ (DROP) Removing constraint :-

Create table student_details


(
id int,
name varchar(25),
age int
);

Alter table student_details


add constraint pk primary key(id);

alter table student


add constraint ck check(age>=18);
Dropping a constraint :-

Create table (7-8) Page 13


Dropping a constraint :-

alter table student_details


drop primary key; // it will drop the constraint not the column.

alter table student_details


drop constraint ck;

Note :- we cannot add not null and default in this form.

Create table (7-8) Page 14


09.
Sunday, September 15, 2024 12:40 PM

Creating a table
create table student_info
(
id int,
name varchar(16),
email varchar(25),
phone bigint,
age int,
gender varchar(25)
);

Adding values to the table -

insert into student_info values


(1, "Latha", "Latha@gmail.com", 8513457893, 23, "M"),
(2, "Suresh", "Suresh@gmail.com", 9534576562, 18, "F"),
(3, "Rakesh", "rakesh@gmail.com", 7458967293, 23, "M"),
(4, "Deepika", "deepika@gmail.com", 7584637593, 17, "F"),
(5, "Mahesh", "mahesh@gmail.com", 9954576789, 32, "M");

CRUD Operations :-

1. UPDATE :-

a. Updating a row with a single condition :-

• update student_info set age = null


where id = 5;
Here where is the clause (Putting conditions)

• update student_info set age = 44


where id = 1;

b. Updating a row with multiple conditions :-

• update student_info set age = 30


where id = 2 and name = "Suresh";

Note :- MySql is not case sensitive for commands, datatypes, constraints or for the data that we are
entering, but in case of oracle the data inside the table is case sensitive and all other things are case
insensitive.

Question :-
Write a query to increment age of every student by one year.

update student_info
set age = age + 1;

Note : Without the condition the query will be applied to every row in the table.

Create table (7-8) Page 15


2. Delete :-
Removing Single Record (Row) with one condition :-

delete from student_info


where id = 5;

Here Important details of SQL:-


• delete, update, select are the commands
• From, clause is clause,
• add, table, database is a keyword

Removing a single record with multiple commands :-

delete from student_info


where id = 3 and phone = 7458967293 and gender = "M";

3. Truncate :-
To remove all the records from the table. It is faster than using delete command to clear the
table.
It will only remove the data but not change or remove the structure of table.

truncate table student;

Create table (7-8) Page 16


10 Query
Sunday, August 11, 2024 4:34 PM

Ques :- WAQ to show all the products whose price is 144 to 3883.

Ans :-
select *
from product
where price > 144 and price < 3858;

Or
 Between

select *
from product
where price between 144 and 3883;

 Distinct :-

Ques :- WAQ to show all the unique brand names.

select distinct brand


from product;

 Difference in unique and distinct.


a. Unique is used when creating a table but distinct is used while writing a query.
b. Unique is a constraint, while distinct is not a constraint.
c. Unique is used to insure that unique values are inserted and distinct is used to ensure that
unique values are fetched.

NOTE :-
We have to use distinct in select statement only.

Create table (7-8) Page 17


10.
Sunday, September 15, 2024 12:40 PM

1. WAQ to display product_id, product_name, and price whose product price is greater than
500rs.

select product_id, name, price


from Product
where (price > 500);

1. WAQ to display product_id, product_name, and price with 25% discount whose product price is
greater than 500rs.

select product_id, name, price - (price * 0.25)


from Product
where price > 500;

Note:- All the changes in price or discount we'll be doing on the select statement.
Internal Execution of SQL statements :-
a. Firstly FROM is going to be executed
b. Then WHERE is executed
c. Then in last SELECT is executed.

3. Display all the products whose brand is Arrow.

select *
from product
where brand = "Arrow";

4. Display all the products whose category is not Clothing.

select *
from product
where category != "Clothing";

5.

Create table (7-8) Page 18


11. Query
Sunday, August 11, 2024 5:03 PM

SQL 11[15-07-2024][Queries]

1. Ques :-
Can I use distinct in more than one columns?

Ans :- Yes, we can use distinct in different columns. And we don't have to specify distinct for every
columns it will be applied to all columns if we write it once only. It will work as composite primary key
i.e. Together it will check for different columns whether it is unique or not.

• Between and/ not between and :-

2. Ques :- WAQ to show name and brand and id is not 5 to 10.

select name, brand


from Product
where product_id not between 5 and 10;

3. WAQ to show all the products whose brand is "Adidas", "Nike", either "Levis".
select name, brand, price
from product
where brand = "Adidas" or brand = "Levis" or brand = "Nike";

Or

• in( , , ,) / not in( , , ,):-


select name, brand, price
from product
where brand in( "Adidas", "Levis", "Nike");

4. WAQ to show name, brand and price of products whose price is less than 3000 and brand is not
"Adidas", "Nike", and "Levis".
select name, brand, price
from product
where price < 3000 and brand not in("Adidas", "Nike", "Levis");

5. Write a Q to show details of products whose status is not updated.


select *

Create table (7-8) Page 19


select *
from Orders
where status is not null;
6. WAQ to display id, name, and annual salary of employees.
select user_id, firstName, salary * 12
from Employee;
• Alias :-
It is optional you can use mention it or without mentioning it we can apply it.
select product_id, name, price, price - (price * .05) as Discounted_price
from product;

Or

select product_id, name, price, price - (price * .05) Discounted_price


from product;

In first we have used as and in second we haven't used as. Both are correct.

Or

select product_id, name, price, price - (price * .05) "Discounted price"


from product;

Create table (7-8) Page 20


12. Like Operator
Sunday, August 11, 2024 5:04 PM

SQL 12[16-07-2024][Like Operators]

https://www.google.com/url?q=https://www.youtube.com/watch?v%3DLibiOjJWAmg%26t%
3D1s&sa=D&source=editors&ust=1723446371244156&usg=AOvVaw0kG7l0oayH-7RdPoIAmMwe

Operators :-
• Arithmetic Operators :-
○ +,
○-
○*
○/
○%
• Comparison Operators / Symbolic Operators
○ = (Equals to)
○ > (Greater than)
○ <(Less than)
○ >=(Greater than or equals to )
○ <=
○ <> (Not equals to)

• Logical Operators
○ AND (Everything to be true)
○ OR (Any one is true)
○ Distinct (to fetch unique values)
○ Between and
○ Not Between And
○ IN
○ Not IN
○ Is Null
○ Is Not Null
○ Like

• Like :-
Like is an operator. Which come under the logical operators or keywords as an operators. We'll be

Create table (7-8) Page 21


Like is an operator. Which come under the logical operators or keywords as an operators. We'll be
using Like operator in incomplete information fxor pattern matching.

Special Characters Or Wildcard Characters:-


• % (modulus) -> It matches 0 or more number of characters.
• _ (underscore) -> It matches exactly one character.

Data What we need Pattern


arjun 1. Starts with a Like "a%"
Anil 2. Ends with a Like "%a"
ausha 3. Contains us Like "%us%"
arun 4 .second character is r Like "_r%"
Bhuvan 5. Exactly 4 characters Like "____"
6. Last 3rd character is v Like "%v__"

Note:- Pattern should be always in either single or double quotes.

1. Ques :- WAQ to show all the users whose name starts with a.
Ans :-
select *
from User
where firstName Like "a%";

2. Ques :- all users whose last name ends with a.


Ans :-
select *
from User
where lastName Like "%a";
3. Ques:- WAQ to display product name and description of product which contains "T-shirt" in
product name and it should be cotton type.
Ans :-
select *
from Product
where name Like "%T-shirt%" and description Like "%cotton%";
4. WAQ to show all the users whose name starts with either a, e, I, o, u.
Ans :-
select *
from User
where firstName Like "a%" or firstName Like "a%"or firstName Like "e%"or firstName Like "i%"or
firstName Like "u%";

Create table (7-8) Page 22


13. RegExp.
Thursday, August 15, 2024 11:04 AM

SQL 13[17-07-2024][Regular Expression]

SQL 13[17-07-2024][Regular Expression]

1. WAQ to show all the orders where total amounts second digit is 5 from left to right.
select *
from Orders
where total_amount Like "_5%";
Regular Expressions:-

1. [] Always use square brackets.


2. [abc] :- a, b or c Use no space
3. [a-z] :- a, b, c, ……… z Use - for a range of values.
4. [A-Z] :- A, B, C, …… Z Use Upper case also
5. [0-9] :- 0, 1, 2, … 9
6. [a-zA-Z] :- a, b, c, … z, A, B, ….. Z
7. [a-zA-Z0-9] :- a, b, c, ….. z, A, B, ….. Z, 0, 1, 2, .... 9
8. [a-z][a-z] :- aa, ab,….az, ba, bb, …. bz, ……..ca, …. Zz If we are not giving any numbers then it will
pick only one character.
9. [A-Z][a-z] :- Aa, Ab, ….. Ba, Bb, ….. Zz
10. [a-z][a-z][a-z] Or [a-z]{3} Here 3 indicates minimum numbers of times it will occur. :- aaa,
bbb, ccc, abc, acc …. zzz
11. [a-z]{3,5} Here 3 is for minimum number of times and 5 is for maximum number of times :-
aaa, aaaa, aaaab, aaa, acde, zzcx, ccc, bca, mca, ccac, ….
12. [a-z]{3, } Here no maximum so we'll leave it as empty:- aaa, aaaa, aaaab, aaaaaaafadf, ………

• [] -> [abc], [a-z]


• {} -> []{4} (Only one number then it is considered as minimum), []{4,8} (min, max), []{4, }
•^ -> Starts with
•$ -> ends with
•? -> Occurs 0 or 1 time (Might occur or not)
•+ -> Occurs 1 or more times
• * -> it occurs 0 or more times
•. -> Matches 1 character

Create table (7-8) Page 23


• . -> Matches 1 character

13. [A-Z]{2}[0-9]{3} -> CS001, EC003, BX105, CX902, ZY501


14. [0-9]{10} -> 9924671311, 6241321321, 8888888888, 9454194541
15. ^[6-9][0-9]{9} -> Indian phone number
16. [a-z]{1,6} -> aaa, bb, c, abcded, abcd, abxyzp, abxyq
17. [0-9a-zA-Z]{4} -> 05ab, ab05, 0154, 9645, aAb4, BB1C, B14a
18. [0-9a-f]{5} -> hexadecimal value of length 5

Create table (7-8) Page 24


14. Regular Expression continue
Thursday, August 15, 2024 11:05 AM

SQL 14[18-07-2024][Regular Expression continuation]

Note here :-
Symbol Definition
^ Starts with
$ Ends With
+ Matches 1 or more characters
? Matches 0 or 1 character
* Matches 0 or more characters
. Matches 1 character

• [a-zA-Z1-5*#]{2, }
• [a-zA-Z0-9+$]{3, }
• [xy+z] :- xyz, xyyz, xyyyz. Xyyyyyz
• [xy*z] :- xyz, xyyz, xyyyz, xyyyyyyyz, xz
• [docx?] :- doc, docs
• ^[aeiouAEIOU].{1}[aeiouAEIOU]$ :- A*u, A*A, Exu, U$E, USA, UE
• ^[AEIOU][a-zA-Z0-9]?[aeiuoAEIOU]$ :- A3U, AA, Exu, UE, USA, UE

SQL 14[18-07-2024][Regular Expression continuation]

Ques :- WAQ to show the details of all the customers whose name starts with A
Ans :-
select *
from user
where firstName REGEXP "^A";

Ques :- WAQ to show all the users whose name starts with a vowel.
Ans :-
select *
from user
where firstName REGEXP "^[aeiouAEIOU]";

Create table (7-8) Page 25


where firstName REGEXP "^[aeiouAEIOU]";

Ques :- WAQ to show all the users whose name does not starts with a vowel.
Ans :-
select *
from user
where firstName not REGEXP "^[aeiouAEIOU]";

Ques :- WAQ to show all the valid numbers in user table.


Ans :-
select phone_number
from User
where phone_number regexp "[6-9][0-9]{9}"

Ques :- Write a query to show all the valid emails.


Ans :-
select email
from User
where email regexp "[a-zA-Z._0-9]@[a-z]\.[a-z]";

Que :- WAQ to show all the products whose 3rd letter is A.


Ans :-
select name
from Product
where name regexp "^..A";

Que :- WAQ to show all the products in whose name 3 rd letter is A.


Ans :-
Select name
From product
Where name regexp "^..A";

Que :- Write a query to show all the users whose first name's 3 character is Vowel.
Ans :-
Select name
From product
Where name regexp "^..[aeiouAEIOU]";

Ques :- WAQ to show all the users whose first name had two vowels together.
Ans :-
select *
from products
where name regexp "[aeiouAEIOU]{2}"

Create table (7-8) Page 26


15. Functions (St in Office)
Thursday, August 15, 2024 11:05 AM

SQL 15[19-07-2024][functions]

• We have two types of functions :-


1. Single row function :-
It will return value for each input. For 1 input it will return 1 output and for 5 inputs it will return 5
outputs.
a. String functions
b. Math Functions
c. Window Function
d. Date Function
e. Control flow functions
f. Comparison functions
2. Multi row functions:-
For 1 input it will return 1 output and also for 5 inputs it will group them together and return one
value.
a. Aggregate Functions / Group functions

1. String Functions :-

• Upper()
• Lower()
• Concat()
• Length()
• Substr()
• Instr()

• Replace :-
It will take min and max 3 parameters and replace all the occurrence of the given word.
select replace("Original String", "old_String", "new_String");

Select replace("Myntra is a great site", "a", "abhi");


= Myntrabhi is abhi greabhit site
• Trim :-
It will only work in starting and end of a String. It can trim characters or white spaces.
Trim(Leading | trailing | both character from string)

Create table (7-8) Page 27


Ex :- select trim(leading "m" from "madam");

○ ltrim - to trim the white spaces from left. ltrim(" Tap Academy ");
○ rtrim - to trim the white spaces from left. rtrim(" Tap Academy ");

Create table (7-8) Page 28


15. Functions
Sunday, September 15, 2024 12:44 PM

SQL 15[19-07-2024][functions]

We have two types of functions :-


1. Single row functions-
It will return value for each and every input. For 1 input it will return 1 output and for 5 input it
will return 5 output.
a. String Functions
b. Math Functions
c. Window Functions
d. Date Functions
e. Control Flow Functions
f. Comparison Function
2. Multi Row Functions-
For 1 input it will return 1 output and also for 5 inputs it will group them together and return one
value.
a. Aggregate Functions / Group functions

1. String Function :-
• upper()
select upper("tap academy"); It will take one argument.
• lower()
select lower("THIS IS ABHISHEK"); it will also have only one argument.
• concat()
select concat("tap", " ", "academy"); Min it will take 2 and can take as many as we want.
• length()
select length("Abhishek "); It will also take only one parameter.
• substr()
Substr(String, position, number of characters).
Substr("Slim Fit Jeans", 6, 3);
• instr() :- it will return the position of a given character. Positions start from 1 not 0.
Instr("TapAcademy","p" ); it will take min and max only two inputs.

But in Oracle instr will take min 2 max 4 parameters.


Instr(main string, string to find, starting index, number of occurrence);
Ex :- instr("I am a abhishek", "a", 5, 3); // But remember it is case sensitive as it is Oracle.
• replace()
• trim()
35 min…
Note :- in both Oracle and MySQL there exist a default table known as dual. It has one row and one
column. If you execute the following query in MySQL it will be executed but in Oracle you have to
mention the table name as dual.
:-
select upper("this is the tap");

But in oracle it must be like :-


select upper("this is the tap")
from dual;
We can use this table without any database redirection.

Create table (7-8) Page 29


16. Math & Date Function
Saturday, August 17, 2024 4:42 PM

SQL 16[22-07-2024][Math functions & Date functions]

1. mod()
2. round()
3. truncate()
4. ceil()
5. floor()

1. Mod :-
mod(dividend, divisor)
mod(10, 3);

2. Round() :-

3. truncate() :-
No incrementation just cut the part.

Create table (7-8) Page 30


4. Ceil :-
5. floor:-

DATE FUNCTIONS :-
1. curdate() :- To include current date.
Select curdate();

2. now() :- It is similar to curdate.


Select now();

3. Day() :-
Day(date);
Select day("2024-06-17"); == 17

4. Month() :-
Select month("2024-06-17"); == 06

5. Year() :-
Select year("2024-06-17"); == 2024

6. datediff() :-
datediff(new_date, old_date);

Select datediff("2024-08-18", "2001-06-30");

7. date_add() :-
Date_add(date, interval 1 second);
Date_add("2024-06-17 23:59:59", interval 1 second);

Create table (7-8) Page 31


Date_add("2024-06-17 23:59:59", interval 1 second);

8. last_day():-
last_day(date);
It will return the last day of the month in date format yyyy-mm-dd.

9. timestampdiff()
timestampdiff(day/month/years, old_date, new_date);

10. Extract() :-
Extract(second from datetime);
Select extract(second from "2000-12-01 12:59:39"); == 39

11. Date_format() :-

12. Date():-
Date(date);
Date("2023-04-36 10:23:04");

14. Time():-
Time(date);
Time("2023-04-06 10:23:04"); == 10:23:04

Create table (7-8) Page 32


17.
Saturday, August 17, 2024 4:42 PM

SQL 17 [23-07-2024] [Date Functions]

Create table (7-8) Page 33


18. Comparison control flow functions
Saturday, August 17, 2024 4:43 PM

SQL 18 [24-07-2024] [Comparison, Control Flow Functions]

Comparison Functions :-

• Isnull()
• Coalesce()

1. Isnull():-

It will return 0 or 1. if the input is null then it will return 1 otherwise it will return 0.
Isnull(parameter);
Select isnull(null); // 1
Select isnull(10); //0

1. Coalesce():-

It can take any number of parameters.


Coalesce(param1, param2, ….. paramN);
Note :- any arithmetic operations done with null be result to a null. 100 + null = null.
So to avoid it we use coalesce it will check if the first input is null then it will return other as
output.

Select coalesce(null, 1); // 1


Select coalesce(10, 1); // 10
Select coalesce(null, null, 10); // 10

Control Flow Functions :-

1. Case()
2. If()
3. Ifnull()
4. Nullif()

1. Case() :-
If we want to achieve multiple conditions in a single statement then we have to use case :-

Create table (7-8) Page 34


If we want to achieve multiple conditions in a single statement then we have to use case :-

select name, brand, price


case
when brand = "Nike" then price - price*15 / 100
when brand = "Puma" then price price*25/100
Else price - price*10/100;
End as discounted_price
from Product;

Case
When condition1 then operation
When condition2 then operation
……..
End

2. If():-

If(expression, if_true_exp, if_false_exp)

Select if(5=5, 'True', 'False');

3. Ifnull()

Ifnull(expression1, expression2);

Ifnull(null, 0) // 0

4. Nullif()
Check for some data and if it matches then make it null. If both the expressions are matching then
it will return null otherwise it will return normal value which is there in first parameter.

Nullif(exp1, exp2);
Select nullif(5,5) // null

Ex :- make all the status null if it is completed.

Select nullif(status, 'Delivered'), status


from Orders;

Ques :-WAQ to display the name, band and price and discounted price. While printing provide 25%
discount for "Puma", 15% for Nike, and 10% for others.

select name, brand, price,


case
when brand = "Puma" then price - price*0.25
when brand = "Nike" then price - price * .15
else price - price * .10
end as "Discounted Price"
from Product;

Ques :- WAQ to display name, price and status of product. If price is above 500 then print "Price is above
500", and if the price is equal or below 500 then print "Price is equal or below 500".

Create table (7-8) Page 35


select name, price,
case
when price > 500 then "Price is above 500."
when price <= 500 then "Price is below or equal to 500."
end as "above/below 500"
from Product
order by price;

or

select name, price, if(price > 500, "Price is above 500", "Price is equal or below 500") as
price_status
from Product
order by price;

Ques :- WAQ to show user id, email and phone number if it is not present then print "Phone number is
not present"

select user_id, email, phone_number, ifnull(phone_number, "No phone number available") as


if_null
from user;

Create table (7-8) Page 36


19. Window Functions and Aggregate Functions
Sunday, September 15, 2024 12:46 PM

SQL 19[25-07-2024][Window Functions and Aggregate Functions]

Sorting of data :-
We can sort the SQL data based on our requirements.

Select *
From user
Order by firstName asc;

Select *
From user
Order by firstName desc;

Window Functions :-

1. Rank()
2. Dense_rank()
3. Row_number()

Window_function
Over([partition_definition][order_definition][frame_definition])

1. RANK():-
Id name Marks Rank()
1. Richa 80 1
4. Ravi 70 2
3. Suman 70 2
4. Roopa 65 4
5. Ramesh60 5

Here if the marks are same then rank will also be same and we'll miss the number between. Here we are
missing 3rd rank.
Note :- before giving the ranks we have to sort the data.

Ex :- select id, name, marks, rank()


Over(order by marks desc)
From student;

2. DENSE_RANK() :-
It will not skip the rank when we have two or more similar ranks.

Id name Marks Dense_Rank()


1. Richa 80 1

Create table (7-8) Page 37


1. Richa 80 1
4. Ravi 70 2
3. Suman 70 2
4. Roopa 65 3
5. Ramesh60 4

Ex :-
select id, name, marks, dense_rank()
Over(order by marks desc)
From student;

3. row_number():-
It will give the numbers to the rows. It doesn't care whether the rows are sorted or not.

Id name Marks Row_number()


1. Richa 80 1
4. Ravi 70 2
3. Suman 70 2
4. Roopa 65 3
5. Ramesh60 4

So, basically ran() will give the rank but skip the number for which the rank is same, dense_rank() will
also give the rank and not skip the ranks even for same ranks these both will work on sorted data. While
row_numer() will give the numbers to the rows, it can work on both sorted and non-sorted data.

select id, name, marks, row_number()


Over(order by desc)
From student;

Now single row functions are completed.

57 min.

Ques :- WAQ to show the product price and rank them. The topmost expensive product should be
ranked 1.

select price, dense_rank()


over(order by price desc)
from Product;

Ques :- WAQ to display the product id, name, category, price and rank of each product price within its
category.

select product_id, name, category, price, dense_rank()


over(partition by category order by price desc) as "Rank"
from Product;

Aggregate Functions :-
Multirow or aggregate functions. It will return one result for one or more inputs. There are
different types of aggregate functions :-
1. Count()
2. Sum()

Create table (7-8) Page 38


2. Sum()
3. Min()
4. Max()
5. Avg()

Ques :- WAQ to show the number of products whose brand is "Arrow".


select count(product_id)
from product
where brand = "Arrow";

Ques :- WAQ to display total price and number of products whose brand is Puma.
select count(product_id) as Total, sum(price) as "Total price"
from Product
where brand = "Puma";

Create table (7-8) Page 39


20. having clause and group by clause
Sunday, September 15, 2024 12:47 PM

SQL 20[26-07-2024][having clause and group by clause]

Group By :-
Used to group the products depending upon the category selected.

Que :- WAQ to show minimum price of products for different brands.

select brand, min(price)


from Products
group by (brand);

Que :- WAQ to show the user_id and total amount of money spend by user for orders which is shipped.
select user_id, sum(total_amount)
from Orders
where status = "Shipped"
group by user_id;

Note :- To Identify where to use group by we have to check the select statement. If we have a aggregate
function sum(), count(), avg(), min(), max() then we'll have only one output and with it if we have some
other table which can have multiple values such as user_id then we have to use group by. And based on
all the normal columns we have to group it. It can be one two or more than that but we have to use
each one of them.

There are two rules to use group by :-


1. If there is a normal column with an aggregate column then we have to use group by.
2. If we have multiple normal columns then we must include them all in group by.
3. Whatever normal column is in group by, it is not mandatory to include in select statement.
4. If we are using order by in a query having group by then we have to order by only the columns
that are used in group by. Not by any other columns.

Here in the last question first of all from will get executed then where condition will get executed
afterwards group by will be executed and in last select will be executed.

Ques :- WAQ to display name, highest and lowest price and total number of products whose product id
is greater than 5.

select name, min(price) as "Lowest Price", max(price) as "Highest Price", count(*) as "Total
products"
from products
where product_id > 5
group by name;

Ques :- WAQ to display brand name, lowest price and highest price and total number of products
Whose product id is greater than 5 and display the result in descending order based on brand names.

select brand, min(price), max(price), count(*)

Create table (7-8) Page 40


select brand, min(price), max(price), count(*)
from Products
where product_id > 5
group by brand
order by brand desc;

Note :- Here order of execution will be :-


1. From
2. Where
3. Group by
4. Select
5. Order by

Ques -WAQ to display brand and highest price of the product whose id is greater than or equal to 10 and
whose maximum price is less than 3000;

Select brand, max(price)


From products
Where product_id >= 10
Group by brand
Having max(price) < 3000;

Note :- we can't use condition which is dependent on aggregate functions before grouping. So we can’t
use max(price) < 3000 before group by clause. Also we can't use where before the group by clause.
Hence we have to use having clause for this type of requirements.
So, whenever we have an aggregate condition to be checked we have to check it after the group by
clause by using having.

Ques :- WAQ to show brand which has avg price less than 1000 and also have minimum of two products.
select brand
group by brand
having avg(price) < 1000 and count(*) > 2;

Ques :- WAQ to show the brand and max price of the products whose product id is greater or equal to
10 and whose average price is between 1000 and 10000.

select brand, max(price)


from Products
where product_id >= 10
group by brand
having avg(price) between 1000 and 10000;

Ques :- WAQ to show brand which has the avg price 1000 or 1500 or 10000.

select brand
from products
group by brand
having avg(price) in(1000, 1500, 10000);

Ques :- WAQ to show the date when different multiple users ordered something.

select date(order_date)
from Orders
group by date(order_date)

Create table (7-8) Page 41


group by date(order_date)
having count(distinct user_id) > 1;

Create table (7-8) Page 42


21. having clause limit offset subqueries
Sunday, September 15, 2024 12:47 PM

SQL 21[29-07-2024][having clause limit offset subqueries]

Ques : Display the order id where the total number of items is greater than 2.

select order_id
from OrderItems
group by order_id
having count(order_item_id) > 2;

Ques :- WAQ to display the months in the format YYYY-MM where the total number of orders placed
was greater than 2.

select date_format(order_date, "%Y-%m")


from Orders
group by date_format(order_date, "%Y-%m")
having count(order_id) > 2;

Ques :- WAQ to display the product id that have a total quantity greater than 3 and an average price is
less than 5000.

select product_id
from OrderItems
group by product_id
having avg(price) < 5000 and sum(quantity) > 3;

Ques :- WAQ to show the Nth highest salary of an employee.


select salary
from employee
order by desc
limit 1 offset 4;

Ques :- WAQ to display the least two salary of an employee.

Select salary
From employee
Order by salary asc
Limit 2;

Subqueries :-

A query inside another query is known as subquery. It is inner query or nested query.
We'll use it when information is not given in the question .
Also whenever we want to check the conditions in the multiple keywords.

Types of subqueries :-

Create table (7-8) Page 43


Types of subqueries :-
1. Single row subquery
2. Multirow subquery
3. Correlated subquery
4. Non-Correlated subquery

Ques :- Write a query to show the details of the most expensive product.

select *
from Products
where price =
(select max(price) from Products);

Imp Point :-
1. There will be one main query and also another subquery
2. Inside a main query we can have multiple subqueries.
3. Subqueries will be enclosed inside parentheses.
4. Final result always will be from the main query.
5. In the main query and in the subquery we can have multiple tables. But it should have a relation
6. In Non-corelated subqueries, subquery will get executed first and then the main query will be
executed.

Ques :- WAQ to display the names of products that have a higher price than the avg price of all products.

Select name
From products
Where price >
(select avg(price)
From products);
Ques :- write a query to show the name of the users who have never placed an order.

select firstName
from Users
where user_id not IN
(select distinct user_id
from Orders);

Create table (7-8) Page 44


22. Subquery
Saturday, August 24, 2024 11:20 AM

SQL 22[30-07-2024][Subqueries]

Note :- We have grater than all >all) and greater than any (>any)

Ques :- WAQ to display names, and emails of users who have places an order with a total amount
greater than 1000. Print the result in ascending order based on the first name.

select firstName, email


from user
where user_id in
(select user_id
from orders
group by user_id
having sum(total_amount) > 1000)
order by firstName asc;

Ques :- WAQ to display the employee who have a salary greater than any employee in department 21.

select fName, lName

Create table (7-8) Page 45


select fName, lName
from employee
where salary >any
(select salary
from department
where department = department21);

Ques :- WAQ to display the employee who have a salary greater than all employee in department 21.

select fName, lName


from employee
where salary >all
(select salary
from department
where department = department21);

Ques :- WAQ to select display the employee who earn more than the average salary of their
department.

Select fName, lName


From employee
Where salary >
(select avg(salary)
From department
Where employee_id = department.e_id
Group by department);

Ques :- WAQ to display the emails of users who have placed orders on the same date as another user.

Create table (7-8) Page 46


23. Joins
Sunday, September 15, 2024 12:49 PM

SQL 23[31-07-2024][Joins]

Ques :- WAQ to show display the employees who earn more than the avg salary in their department.

Select firstName, lastName


From employee as e1
Where e1.salary >
(
Select avg(salary)
From employee as e2
Where e1.d_id = e2.d_id
);

Note :- In co-related subqueries both internal and external query will execute parallelly.
And any query which is dependent upon the main query is known as co-related subqueries.

We can only take something from main query to the subquery. But doing it in reverse direction - taking
something from the sub query to the main query is not possible.

Ques :- WAQ to display the users who have ordered more than two different products.

select firstName, lastName, user_id


from Users as u1
where 2 < (
select count(order_id)
from Orders as o1
where o1.user_id= u1.user_id);

JOINS :-

Join is basically combining. To combine multiple tables we'll use joins. We use joins because :-
1. Joins can return the result from the multiple tables.
2. Joins are efficient and easy to write if we compare them with the sub queries.

Types of Joins:-
1. Inner Join
2. Natural Join
3. Outer Join:-
a. Left Outer Join
b. Right Outer Join
c. Full Outer Join
4. Cross Join

Create table (7-8) Page 47


4. Cross Join
5. Self-Join.

Note :- to perform inner join, tables must have some relationship.

1. Inner Join:-
Go to the tables and find out the relation. Then compare the values of those tables, wherever the
records matches take both the records and print the result.

Select *
From Employee inner join Department
Where Employee.department_id = Department.department_id;

2. Natural Join :-
It is almost same as Inner join. It will take all the matching values and print it, but it will remove
the 2 similar columns from the result also make the common column in the starting of the result.
We don't have to use the condition here it is not mandatory
here.

Select *
From Employee natural join Department ;

3. Outer Joint :- in Outer joins condition is mandatory.


a. Left Outer Join :-
Results all the records from left table and only the matching records from the right table.

b. Right Outer Join:-


It will give all the records from the right table and only common tables from the left table or
null in its place.
c. Full Outer Join :-
What are the set operators in MySQL ?
§ Union,
§ Union on
§ Intersect
§ Minus
We don’t have a full outer join but we can achieve it by taking left outer join union with the
right outer join.

4. Cross Join / Certation join :-


Whenever there is requirement and there is no relation between the tables we have to use cross
join. No condition is required as these two tables are not having any condition.

5. Self Join :-
There is no keyword as self join. Either we have to put comma between the name of table or
simply write keyword join to join two tables. Whenever we have a single table and we have to
check the conditions and perform the operations we have to go with the self join. We have to use
table alias to use self join.

Create table (7-8) Page 48


table alias to use self join.

24.
SQL 24[01-08-2024][Joins]

Ques :- WAQ to display the order_id, order_date total_amount along with the email of user who placed
them.

select order_id, order_date, total_amount, email


from Orders P inner join Users U
On P.user_id = U.user_id;

Note when we are using joins we have to use ON to check the condition.

Ques :- WAQ to display the names of products that have been ordered along with their quantities.

select P.name, O.quantity


from Products P inner join OrderItems O
On P.product_id = O.product_id;

Ques :- WAQ to display all the users along with products they have purchased.

select firstName, lastName, name


from users u inner join Orders o
on u.user_id = o.user_id inner join
OrderItems oi on o.order_id = oi.order_id
inner join Products p on p.product_id = oi.product_id;

Ques :- WAQ to display the list of users and the total amount they have spent.

select firstName, lastName, (total_amount)


from users u inner join Orders o
on u.user_id=o.user_id
group by firstName, lastName;

Ques :- WAQ to display the list of users along with their order details including user who have never
placed an order.

select firstName, lastName, o.*


from users u left join orders o
on u.user_id = o.user_id;

Note :- To print all the data of a table we have to use its alias and then * as we did in last query

Ques :- WAQ to display the names of products and corresponding orders IDs including products that
have never been ordered and product price is less than 1000.

select name, order_id

Create table (7-8) Page 49


select name, order_id
from Products p left join OrderItems oi
on p.product_id = oi.product_id;
where p.price < 1000;

Create table (7-8) Page 50


24.
Saturday, August 31, 2024 10:50 AM

SQL 24[01-08-2024][Joins]

-/
2.10? x

Ques :- WAQ to display all the users along with the products they have purchased including users who
have never purchased something.

select u.firstName, p.name


from user u left join orders o on u.user_id = o.user_id
left join orderItem oi on o.order_id = oi.order_id
left join Product p on p.product_id = oi.product_id;

Ques :- WAQ to display all user and their order details, including user who have never placed an order
and order and order placed by users that might no longer exists.

Create table (7-8) Page 51


25. Index, View, store processor
Saturday, August 31, 2024 10:35 AM

SQL 25[02-08-2024][index, view, stored procedure]

Create table (7-8) Page 52


Index :-
Indexes are the unique numbers generated by the system to efficiently fetch the data from the
tables. We cannot see the index or use it for any of our requirements.

Types of Index :-
1. Clustered Index -
Primary key, foreign key and composite primary key are the clustered indexes.
2. Non - clustered index -
Syntax :-
Create index index_name
On table name (column_name);

Note : index name must be unique. And use index only on the columns which are going to be used
frequently.

Ex :-
Create index name_indexing
On Product(name);

Dropping an index :-
Drop index index_name
On table_name;

So Here are the examples :-


create index ind on product(name);
explain(select * from product where name = "Slim Fit Jeans");

View :-
It is a virtual table. If we make any changes to this virtual table then the changes will reflect on the
main table. This virtual table is created to hide the sensitive information.
Ex :-
Create view Emp
As
Select id, name
From Employee;

Create table (7-8) Page 53


Syntax :-

Create view view_name


As
Select column1, column2, ….
From table_name;

Dropping a view :-

Drop view view_name;

Store Procedures :-

fd

Create table (7-8) Page 54


25. index, view, stored procedure
Sunday, September 15, 2024 12:49 PM

SQL 25[02-08-2024][index, view, stored procedure]

Store Procedures :-

delimitter//
Create procedure getEmployeesByDepartment(IN deptID INT)
Begin
Select EmployeeID, FirstName, LastName, Salary
From employee
Where departmentID = deptID;
End
//

Types of parameters :-
1. IN -> Input parameter
2. OUT -> Output parameter
3. INOUT -> Input output parameter.

Calling :-

getEmployeeByDepartment(1);

Ques :- Create a stored procedure to fetch employees details based on the department ID.

Delimitter//
Create procedure getEmployeesDetailsById(IN deptID INT)
Begin
Select employee_name, e_id
From Employee
Where department = deptID;
End
//

Create table (7-8) Page 55


26. Store Procedure, Trigger
Saturday, August 31, 2024 10:39 AM

SQL 26[03-08-2024][Stored Procedure]

Taking input in procedures :-

use myntra;
delimiter //
create procedure byBrand(in bran int)
Begin
select price, brand, name
from product
where product_Id = bran;
end
//

call byBrand(1);

Taking output in procedure:-

Ques :- Calculate the average salary of employees in a given department and return the result through
an out parameter.

Delimiter //
Create procedure returnResult(IN d_id int, out avgSalary float)
Begin
Select avg(salary) into avgSalary
From employees
Where department_id = d_id;
End
//

Calling Output procedure :-

Call returnResult(2, @avgSalary)


Select @avgSalary;

Ques :- WAQ to apply a discount to a product's price and return the discounted price through an INOUT
parameter.

Create table (7-8) Page 56


parameter.

Trigger :-

Triggers are event and actions.

Ques :- Create a trigger to update the price of the product, if the new price value is not same as old price
value then insert that record in product log table.
Ans :-
Create trigger updateValue
After update on product
For each row
Begin
If old.price <> new.price then
Insert into productlog(id, name, price)

Create table (7-8) Page 57


Insert into productlog(id, name, price)
Values(old.id, old.name, old.price)
End if;
End

Ques :- create a trigger if any record is deleted in product table that record should be inserted into the
productlog table.

Create trigger insertIntoProductLog


Before delete on product
For each row
Begin
Insert into productlog(id, name, value)
Values (old.id, old.name, old.value);
end

Create table (7-8) Page 58


27. Normalization
Saturday, August 31, 2024 10:39 AM

SQL 27 [05-08-2024][Normalization]

Normalization comes under the DBMS.

Normalization :-

It is the decomposition of the tables, and it will eliminate the anomalies Like - Insertion anomaly,
updation anomaly, deletion anomaly also removing data redundancy.

1. Insertion Anomaly :-

In the above table we can't insert any value to the students who haven't attended the exam. So the
value will be null for those fields. When most of the students are not attending the test then we'll have a
lot of rows like that without any values. So, it will be waste of the memory. In this situation we use
normalization to split the table into different sub tables.
Whenever there is any wastage of memory we call it insertion anomaly.

2. Updation anomaly :-

To update a data we have to write multiple queries, this problem is known as updation anomaly.

Create table (7-8) Page 59


ChatGpt -
Database Context: In the context of databases, an "updation anomaly" might refer to an issue where
updating data leads to inconsistencies or errors, often due to poor database design. This could involve
problems like:
• Redundancy: When the same data is stored in multiple places, updating one instance and not the
others can cause discrepancies.
• Data Integrity Issues: An update might violate constraints or business rules, leading to invalid or
corrupted data.

3. Deletion anomaly :-

Create table (7-8) Page 60


Here both x and y are the attributes. X is determinant which is determining/ identifying y. and Y is
dependent on x.

Functional dependency :-

all the determinants cannot become key, but every key will be determinant.

Here in the above dig. There are three determinants but we only have two keys.

Functional dependency :-
If one attribute is determining other attribute then the other attribute will be functionally dependent on
the determinant.

1. Partial dependency :-

2. Total dependency :-

Create table (7-8) Page 61


4. Transitive dependency :-

Types of Normalization :-
1. First Normal form (1nf)
2. Second Normal Form (2Nf)
3. Third Normal From (3Nf)
3.5 BCNF
4.
5. We have 4 and 5 form also.

1. First Normal Form :-


Rules :-
• Every column should be atomic column. (Separate column).
• Each shell contains a single value.

Raw table :-

Create table (7-8) Page 62


First Normalized table :-

Second Normalization :-
Rules :-
1. Table should be present in 1NF.
2. In a table partial dependency should not be present.

Third Normal Form (3NF) :-


Rules :-
• It should be present in second normal form.
• The table should not have transitive dependency.
Check the table with at least 3 columns or more than that.

Create table (7-8) Page 63


Create table (7-8) Page 64

You might also like