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...
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 database systems, including MySQL, PostgreSQL, MariaDB, and SQLite, which can be easily installed and run on Linux systems.
### SQL and Linux Integration
On Linux, SQL databases are often used in server environments to manage data for web applications, enterprise systems, and data analysis tasks. Many popular database management systems (DBMS) such as MySQL, MariaDB, and PostgreSQL come pre-packaged in Linux distributions or can be installed via package managers like `apt` (for Debian-based distributions) or `yum` (for Red Hat-based distributions).
#### Installation
To install MySQL or PostgreSQL on Linux, users can run:
- For MySQL: `sudo apt-get install mysql-server` (Debian-based) or `sudo yum install mysql-server` (Red Hat-based)
- For PostgreSQL: `sudo apt-get install postgresql postgresql-contrib`
After installation, database services can be started using system commands like `sudo systemctl start mysql` or `sudo systemctl start postgresql`.
### Working with SQL on Linux
Once installed, users can interact with the databases via terminal using SQL commands. For example:
- To log in to MySQL: `mysql -u root -p`
- To log in to PostgreSQL: `psql -U postgres`
SQL commands can be used to:
- **Create a database:** `CREATE DATABASE dbname;`
- **Create a table:** `CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50), age INT);`
- **Insert data:** `INSERT INTO users (id, name, age) VALUES (1, 'John', 25);`
- **Query data:** `SELECT * FROM users;`
### Administration and Security
Linux provides strong security features for SQL databases. Permissions can be granted to specific users with commands like `GRANT` and `REVOKE`. Databases can be protected by controlling access to users and encrypting sensitive data. Linux-based tools like `cron` can be used for scheduled backups, while firewall settings help secure databases from unauthorized access.
### Conclusion
SQL on Linux is integral to managing data efficiently in modern computing environments. With its stability, security, and powerful command-line tools, Linux provides an excellent platform for running SQL databases for a wide range of applications.
In addition to managing databases directly via the command line, Linux users can also take advantage of graphical user interfaces (GUIs) like **phpMyAdmin**, **pgAdmin**, or **DBeaver**, which make interacting with SQL databases more intuitive by providing visual tools for creating tables, running queries, and managing data. These tools can be easily installed on Linux systems and are often used in tandem with command-line operations.
Linux also supports integration with various programming languages, such as Python, PHP, and Java, allowing developers t
Size: 17.37 MB
Language: en
Added: Sep 05, 2024
Slides: 79 pages
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
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
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
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
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.