SQL on Linux and its uses and application.pdf

bhaveshsethi456 26 views 79 slides Sep 05, 2024
Slide 1
Slide 1 of 284
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204
Slide 205
205
Slide 206
206
Slide 207
207
Slide 208
208
Slide 209
209
Slide 210
210
Slide 211
211
Slide 212
212
Slide 213
213
Slide 214
214
Slide 215
215
Slide 216
216
Slide 217
217
Slide 218
218
Slide 219
219
Slide 220
220
Slide 221
221
Slide 222
222
Slide 223
223
Slide 224
224
Slide 225
225
Slide 226
226
Slide 227
227
Slide 228
228
Slide 229
229
Slide 230
230
Slide 231
231
Slide 232
232
Slide 233
233
Slide 234
234
Slide 235
235
Slide 236
236
Slide 237
237
Slide 238
238
Slide 239
239
Slide 240
240
Slide 241
241
Slide 242
242
Slide 243
243
Slide 244
244
Slide 245
245
Slide 246
246
Slide 247
247
Slide 248
248
Slide 249
249
Slide 250
250
Slide 251
251
Slide 252
252
Slide 253
253
Slide 254
254
Slide 255
255
Slide 256
256
Slide 257
257
Slide 258
258
Slide 259
259
Slide 260
260
Slide 261
261
Slide 262
262
Slide 263
263
Slide 264
264
Slide 265
265
Slide 266
266
Slide 267
267
Slide 268
268
Slide 269
269
Slide 270
270
Slide 271
271
Slide 272
272
Slide 273
273
Slide 274
274
Slide 275
275
Slide 276
276
Slide 277
277
Slide 278
278
Slide 279
279
Slide 280
280
Slide 281
281
Slide 282
282
Slide 283
283
Slide 284
284

About This Presentation

SQL (Structured Query Language) in Linux is a powerful tool for managing and manipulating relational databases. SQL allows users to query, update, insert, and delete data from databases, as well as manage database structures, such as tables, views, indexes, and more. SQL is supported on various data...


Slide Content

ALRIGHT!

SETUP AND START WORING ON LINUX
MYSQL TUTORIAL

MySql Installation
Securing MySQL
Testing connectivity with MySQL
Basic necessary queries
Creating Database
Creating Table
Inserting data into the table
Reading data from Table
Update data into a table
Topics

Step 1: Installation
#yum install mysql-server.x86_64

Start/Enable MySQL
#sudo systemctl status mysqld.service
#sudo systemctl start mysqld.service
#sudo systemctl enable/disable mysqld.service

Secure the authentication process by
setting password for root
Step 2: Changing default options
#sudo mysql_secure_installation

Step 3: Testing Connection
You can verify your installation with the
mysqladmin tool
#mysqladmin -u root -p version
To connect and start using SQL Queries
#mysql -u root -p

Some Important Queries in starting
SHOW DATABASES;
SHOW TABLES;
USE <database_name>

Creating a new Database
CREATE DATABASE <db_name>;

CREATE
READ
UPDATE
DELETE
CRUD

Creating a new Table
CREATE TABLE students (
id INT,
name VARCHAR(100)
)
CREATE TABLE students (name VARCHAR(100), age INT)

Checking yout table
DESC TABLE

Adding data into a Table
INSERT INTO students(id, name)
VALUES (101, "Rahul")
INSERT INTO students VALUES (101, "Rahul")

Reading data from a Table
SELECT * FROM <table_name>
SELECT <column_name> from students

Modify/Update data from a Table
UPDATE students
SET contact=12345
WHERE name='Raju';

DELETE data from a Table
DELETE FROM students
WHERE name='Raju';

Deleting a Database or Table
DROP DATABASE <db_name>;
DROP TABLE <table_name>;

THANKS FOR WATCHING

Databases

List All Existing Database
SHOW DATABASES;

Creating a new Database
CREATE DATABASE <db_name>;

Working with a Database
USE <db_name>;

Deleting a Database
DROP DATABASE <db_name>;

Tables

Table
A table is a collection of related data
held in a table format within a database.

Creating a new Table
CREATE TABLE students (
id INT,
name VARCHAR(100)
)
CREATE TABLE students (name VARCHAR(100), age INT)

Checking your table
DESC TABLE

Adding data into a Table
INSERT INTO students(id, name)
VALUES (101, "Rahul")
INSERT INTO students VALUES (101, "Rahul")

Reading data from a Table
SELECT * FROM <table_name>
SELECT <column_name> from students

Modify/Update data from a Table
UPDATE students
SET contact=12345
WHERE name='Raju';

DELETE data from a Table
DELETE FROM students
WHERE name='Raju';

DataTypes

DataTypes
An attribute that specifies the type of data in a
column of our database - table.

Most widely used are
Numeric - INT DOUBLE FLOAT DECIMAL
String - VARCHAR
Date

NOT NULL

DEFAULT Value

CREATE TABLE employee(
name VARCHAR(100),
acc_type VARCHAR(50) DEFAULT 'savings'
);

Primary Key

Primary Key
The PRIMARY KEY constraint uniquely identifies each
record in a table.
Primary keys must contain UNIQUE values, and cannot
contain NULL values.
A table can have only ONE primary key.

AUTO_INCREMENT

ALIAS

WHERE

Exercise - 1

Task
Create a database - bank_db
Create a table - employees
emp_id
name
desig
dept
emp_id column should not allow duplicate and null values
name column should not contain null value
desig column should have default value as 'Probation'
Value of emp_id column should auto increment

Task
Insert the following data

Task
Display the data

Exercise - 2

Task
Display the data

Task
Update the following data

Task
DELETE the following data

String Functions

CONCAT
CONCAT(first_col, sec_col)
CONCAT(first_word, sec_word, ...)

CONCAT_WS
CONCAT_WS('-', fname, lname)

SUBSTRING
SELECT SUBSTRING('Hey Buddy', 1, 4);

SUBSTRING
SELECT SUBSTRING('Hey Buddy', 1, 4);
1 4
Result: Hey

REPLACE

REPLACE
Hey Buddy
Hey Hello
Hello Buddy

REPLACE(str, from_str, to_str)
REPLACE('Hey Buddy', 'Hey', 'Hello')

REVERSE
SELECT REVERSE('Hello World');

CHAR_LENGTH
Select CHAR_LENGTH('Hello World');

UPPER & LOWER
SELECT UPPER('Hello World');
SELECT LOWER('Hello World');

Other Functions

SELECT INSERT('Hello Wassup', 6, 0, 'Raju');
SELECT LEFT('Abcdefghij', 3);
SELECT RIGHT('Abcdefghij', 4);
SELECT REPEAT('o', 5);
SELECT TRIM(' Alright! ');

Exercise - 3

Task 1:
101:Raju:Manager:Loan
Task2:
101:Raju Rastogi:Manager:Loan

Task3
101:Raju:MANAGER:Loan
Task4
L101 Raju
C102 Sham

DISTINCT
SELECT DISTINCT fname FROM employees;

ORDER BY
SELECT * FROM employees ORDER BY fname;

LIKE
Select * FROM employees
WHERE dept LIKE "%Acc%";

LIMIT
SELECT * FROM employees LIMIT 3;

ALTER TABLE employees
ADD COLUMN
salary INT NOT NULL
DEFAULT 25000;

GROUP BY

Loan Cash Account
IT
Deposit

SELECT dept FROM employees GROUP BY dept;
SELECT dept, COUNT(fname) FROM employees GROUP
BY dept;

COUNT
SELECT COUNT(*) FROM employees;

MAX & MIN
SELECT MAX(age) FROM employees;
SELECT MIN(age) FROM employees;

SELECT emp_id, fname, salary FROM employees
WHERE
salary = (SELECT MAX(salary) FROM employees);

SUM & AVG
SELECT SUM(salary) FROM employees;
SELECT AVG(salary) FROM employees;

Exercise - 4
DISTINCT, ORDER BY, LIKE and LIMIT

1: Find Different type of departments in database?
2: Display records with High-low salary
3: How to see only top 3 records from a table?
4: Show records where first name start with letter 'A'
5: Show records where length of the lname is 4 characters

1
2
3

4
5

Exercise - 5
COUNT, GROUP BY, MIN, MAX and SUM and AVG

1: Find Total no. of employees in database?
2: Find no. of employees in each department.
3: Find lowest salary paying
4: Find highest salary paying
5: Find total salary paying in Loan department?
6: Average salary paying in each department

DATAYPES
CHAR vs VARCHAR

DATAYPES
The CHAR and VARCHAR types are similar,
but differ in the way they are stored
and retrieved.

DATAYPES
VARCHAR(50)
The length can be specified as a value
from 0 to 65,535.

DATAYPES
CHAR is fixed length
CHAR(5) --> Only 5 character allowed
The length can be any value from 0 to
255.

DATAYPES
When CHAR values are stored, they are right-
padded with spaces to the specified length.
When CHAR values are retrieved, trailing spaces
are removed unless the PAD_CHAR_TO_FULL_LENGTH
SQL mode is enabled.

CHAR(4)
If you try to insert value 'AB'
MySQL will store the value as 'AB '

CHAR can be used in case of fixed length values
like
Country code: US, IN, AU

DATAYPES
DECIMAL

DATAYPES
So far we have only used and seen
INT Datatype...

DATAYPES
What will happen when we store
values like 15.35?

DATAYPES
DECIMAL(6,3)

The maximum number of digits for DECIMAL is 65

DATAYPES
DECIMAL(5,2)
Total digit
Digits after decimal

DATAYPES
Example: 155.38
119.12
28.15
1150.15

DATAYPES
FLOAT, DOUBLE

DATAYPES
FLOAT, DOUBLE
MySQL uses four bytes for single-precision
values and eight bytes for double-precision

DATAYPES
FLOAT, DOUBLE
Float - upto ~7 digits, takes 4 bytes of memory
Double - upto ~15 digits, takes 8 bytes of memory

DATAYPES
DATE, TIME, DATETIME

DATAYPES
DATE, TIME, DATETIME
DATE
yyyy-mm-dd format

DATAYPES
DATE, TIME, DATETIME
TIME
HH:MM:SS format

DATAYPES
DATE, TIME, DATETIME
DATETIME
'yyyy-mm-dd HH:MM:SS' format

DATE TIME Functions
CURDATE, CURTIME, NOW

DATE TIME Functions
CURDATE() - yyyy-mm-dd
CURTIME() - hh:mm:ss
NOW() - yyyy-mm-dd hh:mm:ss

DAYNAME,
DAYOFMONTH,DAYOFWEEK
DATE TIME Functions

DATE Formatting

DATE Formatting
Tue Mar 28th
21st Tue at 21:20:28
2023/04/18
Suppose we need to get date in a given format like

DATE Formatting
DATE_FORMAT()
DATE_FORMAT(now(), '%D %a at %T')
Result: 21st Tue at 21:20:28
DATE_FORMAT(now(), '%m/%d/%y')
Result: 04/16/23

DATE Formatting
DATE_FORMAT()
DATE_FORMAT(now(), '%H:%i')
Result: 20:34
DATE_FORMAT(dob, '%r')
Result: 08:35:48 PM

DATE MAth

DATEDIFF(expr1, expr2)
DATE_ADD(date, INTERVAL expr unit)
DATE_SUB(date, INTERVAL expr unit)

DATE_ADD('2023-05-01',INTERVAL 1 DAY)
DATE_ADD('2023-05-01',INTERVAL 1 YEAR)
DATE_SUB('2023-05-01',INTERVAL 1 MONTH)

TIMEDIFF(expr1, expr2)
TIMEDIFF('20:00:00', '18:00:00')

DEFAULT &
ON UPDATE TIMESTAMP

CREATE TABLE blogs (
text VARCHAR(150),
created_at DATETIME default CURRENT_TIMESTAMP,
updated_at DATETIME ON UPDATE CURRENT_TIMESTAMP
);

Exercise - 6

Exercise - 6
Print the current time (HH:MM:SS)
Print the current date (yyyy-mm-dd)
Print current day of the week (Monday, Tuesday...)
What is the use case of CHAR datatype?
Which datatype can be used to store value 123.456?
Display date in format
dd:mm:yyyy
April 22nd at 22:00:00

Exercise - 6
Solution

Exercise - 6
Print the current time (HH:MM:SS)
Print the current date (yyyy-mm-dd)
Print current day of the week (Monday, Tuesday...)
What is the use case of CHAR datatype?
Which datatype can be used to store value 123.456?
Display date in format
dd:mm:yyyy
April 22nd at 22:00:00

Exercise - 6
SELECT CURTIME();
SELECT CURDATE();
SELECT DAYNAME(NOW());
What is the use case of CHAR datatype?
Which datatype can be used to store value 123.456?
Display date in format
dd:mm:yyyy - date_format(now(), '%d:%m:%Y')
April 22nd at 22:00:00 - date_format(now(), '%M %D at %T')

Operators

Relational Operators

Find employees whose salary is more than
65000

=
=
We have relational
operators

SELECT * FROM employees
WHERE salary > 65000;

Logical Operators

AND
OR

ANDCondition 1 Condition 2
When both the conditions are true

ANDsalary=25000 dept=Loan

ORCondition 1 Condition 2
When either of the condition is true

ORsalary=65000 desig='Lead'

IN, NOT IN

Account
Cash
Loan
Find employees From following department

SELECT * FROM employees
WHERE dept = 'Account'
OR dept = 'Cash'
OR dept = 'Loan';

SELECT * FROM employees
WHERE dept IN ('Account', 'Cash', 'Loan');

BETWEEN

Find employees whose salary is more than
40000 and Less than 65000
>40000
<65000

SELECT * FROM employees
WHERE
salary >=40000 AND salary <=65000;

SELECT * FROM employees
WHERE
salary BETWEEN 40000 AND 65000;

CASE

IS NULL

IS NULL
SELECT * FROM employees
WHERE fname IS NULL;

NOT LIKE

IS NULL
SELECT * FROM employees
WHERE fname NOT LIKE 'A%';

Exercise - 7

Find employees whose salary are between
30000 to 40000
Find employees whose first name start with
Find employee whose salary=25000 and
department should be 'Cash'
Find employees from following designation
Manager, Lead and Associate
'R' or 'S'

Exercise - 7
Solution

UNIQUE
CONSTRAINT

What if we need to store the
phone numbers in a column.

CHECK
CONSTRAINT

We want to make sure phone no. is
atleast 10 digits...

NAMED CONSTRAINT

ALTERING
Tables

How to add or remove a column?

How to rename a column or table name?

How to rename a column?

How to rename a table name?

How to modify a column?
Ex: Changing datatype
or adding Default values etc

How to add DEFAULT value to a column?

How to change column name and set NOT
NULL?

How to Add or Drop Constraints?

How to Check Existing Constraints?

Relationship

RElATIONSHIP

Simple data and table...

Real World

Data is not that simple...

Employees

Employees
Salary Attendance
requests task
offices

Types of Relationship
One to One
One to Many
Many to Many

1 : 1

Employees
Employee
Details

1 : MANY

Employees
Employee Task

Many : Many

Books Authors

Author A
Author B
Book A
Book B
Book C
Book D

Let's Understand a Use-Case of
1:Many

Suppose we need to store the following data
customer name
customer email
order date
order price

Customers Orders
cust_id
cust_name
cust_email
order_id
order_date
order_amount

Customers Orders
cust_id
cust_name
cust_email
order_id
order_date
order_amount
cust_id

Customers
Orders

Foreign Key

Customers
Orders

Customers
Orders
Primary Key
Foreign Key
Primary Key

Let's work practically with
Foreign Key..

JOINS

JOIN operation is used to combine rows
from two or more tables based on a related
column between them.

Customers
Orders
Primary Key
Foreign Key
Primary Key

Types of Join
Cross Join
Inner Join
Left Join
Right Join

Cross Join
Every row from one table is combined with
every row from another table.

Inner Join
Returns only the rows where there is a match
between the specified columns in both the
left (or first) and right (or second) tables.

Inner Join with Group By

Left Join
Returns all rows from the left (or first) table
and the matching rows from the right (or
second) table.

Right Join
Returns all rows from the right (or second)
table and the matching rows from the left (or
first) table.

CASCADE ON DELETE

Customers
Orders
Primary Key
Foreign Key
Primary Key

Exercise - 8

Authors
author_id
author_name
Books
book_id
title
ratings
au_id

Exercise - 8
Solution

Many : Many

Let's Understand a Use-Case of
Many : Many

Students
Courses

Student A
Course A
Course B
Course C

Student A
Course A
Student B
Student C

id
student_name
students
id
course_name
fees
courses

id
student_name
students
id
course_name
fees
courses
student_id
course_id
student_course

id
student_name
students
id
course_name
fees
courses
student_id
course_id
student_course

Exercise - 9
Solution

Print No. of students for each course.

Print No. of courses taken by each students

Total FEES Paid by Each Student

VIEWS

HAVING Clause

GROUP BY ROLLUP

STORED Routine

STORED Routine
An SQL statement or a set of SQL
Statement that can be stored on
database server which can be call no. of
times.

Types of STORED Routine
STORED Procedure
User defined Functions

STORED Procedure

STORED PROCEDURE
These are routines that contain a series of
SQL statements and procedural logic.
Often used for performing actions like data
modification, transaction control, and
executing sequences of statements.

USER DEFINED FUNCTIONS

WINDOW FUNCTIONS

Introduced in version 8.0.
Window functions, also known as analytic
functions allow you to perform calculations
across a set of rows related to the current row.
Defined by an OVER() clause.

ROW_NUMBER()
RANK()
DENSE_RANK()
LAG()
LEAD()
Tags