0% found this document useful (0 votes)
6 views

MYSQL

The document provides an overview of databases, including types of data, database management systems (DBMS), and SQL commands for data manipulation. It covers various SQL operations such as creating tables, inserting records, and using functions like MIN, MAX, and COUNT, as well as different types of joins. Additionally, it discusses constraints, aliases, and the HAVING clause for filtering grouped results.

Uploaded by

Girish MA
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

MYSQL

The document provides an overview of databases, including types of data, database management systems (DBMS), and SQL commands for data manipulation. It covers various SQL operations such as creating tables, inserting records, and using functions like MIN, MAX, and COUNT, as well as different types of joins. Additionally, it discusses constraints, aliases, and the HAVING clause for filtering grouped results.

Uploaded by

Girish MA
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

MODULE 1

Database:
A database is a structured collection of data, commonly stored and accessed
electronically from a computer system. In other words, databases support storage
and manipulation of data.

1. Types of Data
a. Quantitative
i. Numerical form

ii. Weight, volume, cost of an item.

b. Qualitative
i. Descriptive, but not numerical.

ii. Name, gender, hair color of a person.

Database management system


 In order to manage the database we use DBMS (Database Management
System)
 We give instructions to DBMS for pulling and modifying our data. The DBMS
executes the same and returns the result.

Types of database management systems


There are two types of Database Management Systems. They are:
1. Relational - Data are stored in tabular forms linked with some relationships.
2. Non-Relational - Doesn't have any table or relationships. e.g., NOSQL
Commonly used RDBMS
1. MySQL
2. SQL Server
3. Oracle

DATATYPE Description

CHAR string(0-255), string with size = (0, 255], e.g.,


CHAR(251)
VARCHAR(10) string(0-255)
INT integer(-2147483648 to 2147483647)
FLOAT Decimal with precision to 23 digits
DOUBLE Decimal with 24 to 53 digits

DATATYPE Description

DATE YYYY-MM-DD
DATETIME YYYY-MM-DD HH:MM:SS
TIMESTAMP YYYYMMDDHHMMSS
TIME HH:MM:SS
BOOLEAN 0/1
1. Types of SQL commands:
1. DDL (data definition language): defining relation schema.

1. CREATE: create table, DB, view.


2. ALTER TABLE: modification in table structure. e.g, change column datatype or add/remove
columns.
3. DROP: delete table, DB, view.
4. TRUNCATE: remove all the tuples from the table.
5. RENAME: rename DB name, table name, column name etc.
2. DRL/DQL (data retrieval language / data query language): retrieve data from the tables.

1. SELECT
3. DML (data modification language): use to perform modifications in the DB

1. INSERT: insert data into a relation


2. UPDATE: update relation data.
3. DELETE: delete row(s) from the relation.
4. DCL (Data Control language): grant or revoke authorities from user.
1. GRANT: access privileges to the DB

2. REVOKE: revoke user access privileges.

Database checking and changing the Database


Create database databasename;

SHOW DATABASES;
USE <Database Name>;

Use databasename;

Create Table and description of the Table


CREATE TABLE <TABLE NAME> (<COLUMN NAMES

DATA TYPE (<LENGTH>);

DESC <TABLE NAME>;

CREATE TABLE EMPLOYEE (EMPLOYEEID VARCHAR(10), FIRSTNAME VARCHAR(58), LASTNAME


VARCHAR(50));

TO SEE THE TABLE DATATYPES

DESC <TABLE NAME>;


Click on Run option, When we are executing the query.

Inserting records into the Table


INSERT INTO <TABLE NAME> VALUES(...);
TO FETCH ALL THE RECORDS - SELECT SYNTAX
SELECT * FROM <TABLE NAME>;

The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

EXAMPLE; SELECT * FROM EMPLOYEE


TO FETCH COLUMN-WISE RECORDS - SELECT SYNTAX
SELECT <COLUMN NAME> FROM <TABLE NAME>;

MODULE 2

TO FETCH THE UNIQUE RECORDS – SELECT DISTINCT SYNTAX


SELECT DISTINCT <COLUMN NAME> FROM <TABLE NAME>;

The SELECT DISTINCT statement is used to return only distinct (different)


values.
SELECT FIRSTNAME FROM EMPLOYEE;
Example: SELECT DISTINCT LASTNAME FROM EMPLOYEE;
Fetching the entire result with some condition – WHERE SYNTAX
SELECT * FROM <TABLE NAME> WHERE <CONDITION>

The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition.

SELECT * FROM EMPLOYEE WHERE LASTNAME ='Kumar';

To add multiple values in WHERE clause - IN OPERATOR.


SELECT <COLUMN NAME> FROM <TABLE NAME> WHERE <COLUMN NAME> IN
(VALUE1, VALUE2,...);

To add multiple values in WHERE clause - IN OPERATOR.


SELECT <COLUMN NAME> FROM <TABLE NAME> WHERE <COLUMN NAME> IN
(VALUE1, VALUE2,...);
To select values within a given range of values- BETWEEN OPERATOR.
SELECT <COLUMN NAME> FROM <TABLE NAME> WHERE <COLUMN NAME>
BETWEEN VALUE 1 AND VALUE 2;

Some Basic Operators


Operators are key words to perform arithmetical, logical and comparison operations.
Firstly let's learn the basic Operators:
• AND
• OR
• NOT

AND
AND Operator is used to show the records if the conditions which are separated
by AND are true.
SELECT <COLUMN NAMES> FROM <TABLE NAME> WHERE <CONDITION 1> AND
<CONDITION 2>...;
OR Operator is used to show the records if any of the conditions which are separated
by OR are true.
SELECT <COLUMN NAMES> FROM <TABLE NAME> WHERE <CONDITION 1> OR
<CONDITION 2>...;
Ex: SELECT FIRSTNAME FROM EMPLOYEE WHERE EMPLOYEEID=110 OR
LASTNAME='Kumar';
NOT Operator is used to show the records if the conditions are not true.
SELECT <COLUMN NAMES> FROM <TABLE NAME> WHERE NOT<CONDITION>;
Ex: SELECT FIRSTNAME FROM EMPLOYEE WHERE NOT LASTNAME='Kumar';

MODULE 3
ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
Arrangement of records while displaying the result- ORDER BY SYNTAX
SELECT * FROM <TABLE NAME> ORDER BY <COLUMN NAME> ASC|DESC;
EX: SELECT * FROM EMPLOYEE ORDER BY FIRSTNAME;

Ex: SELECT * FROM EMPLOYEE ORDER BY FIRSTNAME DESC;

Arranging column wise result with some condition


SELECT <COLUMN NAME> FROM <TABLE NAME> WHERE <CONDITION> ORDER BY
<COLUMN NAME>;
To check Null Values –
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record
without adding a value to this field. Then, the field will be saved with a NULL value.
It is not possible to test for NULL values with comparison operators, such as =, <, or
<>.
We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL Syntax
SELECT * FROM <Table Name> WHERE <Column Name> IS NULL;

IS NOT NULL Syntax is used to show the records which are not null values.
SELECT * FROM <Table Name> WHERE <Column Name> IS NOT NULL;
SELECT FROM EMPLOYEE WHERE EMPLOYEEID IS NOT NULL;

To modify records in table - UPDATE Syntax


UPDATE<TABLE NAME> SET<COLUMN NAME> = <Value> WHERE <Condition>;
The UPDATE statement is used to modify the existing records in a table.

To delete some records –


The DELETE statement is used to delete existing records in a table.
DELETE Syntax-DELETE FROM <Table Name> WHERE <Condition>;

LIMIT Syntax - To display specific number of records


The SQL SELECT LIMIT statement is used to retrieve records from one or more tables
in a database and limit the number of records returned based on a limit value.

SELECT <COLUMN NAME> FROM <TABLE NAME> LIMIT <N>;


MODULE 5
MIN()
The MIN() function returns the smallest value of the selected column.

MIN Syntax
SELECT MIN(COLUMN NAME) FROM <TABLE NAME> WHERE <CONDITION>;
MAX()
To return the largest record in the column - MAX() Syntax
SELECT MAX(<COLUMN NAME>) FROM <TABLE NAME> WHERE <CONDITION>;

COUNT()
To check the number of records/rows which satisfies a specific criterion
COUNT() Syntax--
SELECT COUNT<Column Name> FROM<Table Name> WHERE <Condition>;
AVG()
To check the average value of the numeric column
AVG() Syntax--
SELECT AVG<Column Name> FROM<Table Name>;

SUM()
To get the sum of the numeric column
SUM() Syntax--
SELECT SUM<Column Name> FROM <Table Name>;
LIKE operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign (%) represents zero, one, or multiple characters
The underscore sign (_) represents one, single character
The percent sign and the underscore can also be used in combinations!

To fetch names starting with ‘A’– ‘A%' Syntax


SELECT * FROM <Table Name> WHERE <Column Name> LIKE '%';
To fetch names ending with ‘A’– ‘%A' Syntax
SELECT * FROM <Table Name> WHERE <Column Name> LIKE '%';

To fetch names containing with ‘ar’– “%ar%’ Syntax


SELECT * FROM <Table Name> WHERE <Column Name> LIKE '%ar%';

To fetch names with 'a' in Second position – a%' Syntax


SELECT * FROM <Table Name> WHERE <Column Name> LIKE ____a%';

To fetch names which starts with ‘D' and ends with 'I' - 'A%N' Syntax
SELECT * FROM <Table Name> WHERE <Column Name> LIKE ‘D%N';

To fetch names not starting with ‘D’– ‘D%' Syntax


SELECT * FROM <Table Name> WHERE <Column Name> NOT LIKE ‘D%';
To fetch names starting with ‘D’ and containing at least 3 characters-Syntax
SELECT * FROM <Table Name> WHERE <Column Name> LIKE 'D_%_%';

ALIAS
Aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
ALIAS is of two types:
• Alias Column
• Alias Table

SELECT <COLUMN NAME> AS <ALIAS NAME> FROM <TABLE NAME>;


Alias Table Syntax
SELECT <COLUMN NAME> FROM <TABLE NAME> AS <ALIAS NAME>;
CONSTRAINTS (DDL)
1. Primary Key

1. PK is not null, unique and only one per table.


2. Foreign Key
1. FK refers to PK of other table.
2. Each relation can having any number of FK.
3.

3. UNIQUE
1. Unique, can be null, table can have multiple unique attributes.
2. CREATE TABLE customer (

email VARCHAR(1024) UNIQUE,

);
4. CHECK
1. CREATE TABLE customer (

CONSTRAINT age_check CHECK (age > 12),

);
2. “age_check”, can also avoid this, MySQL generates name of constraint automatically.

5. DEFAULT
1. Set default value of the column.
CREATE TABLE account (


saving-rate DOUBLE NOT NULL DEFAULT 4.25,

);
6. ALTER OPERATIONS
1. Changes schema
2. ADD
1. Add new column.
2. ALTER TABLE table_name ADD new_col_name datatype ADD new_col_name_2 datatype;
3. e.g., ALTER TABLE customer ADD age INT NOT NULL;
3. MODIFY
1. Change datatype of an attribute.
2. ALTER TABLE table-name MODIFY col-name col-datatype;
3. E.g., VARCHAR TO CHAR
ALTER TABLE customer MODIFY name CHAR(1024);
4. CHANGE COLUMN
1. Rename column name.
2. ALTER TABLE table-name CHANGE COLUMN old-col-name new-col-name new-col-
datatype;
3. e.g., ALTER TABLE customer CHANGE COLUMN name customer-name
VARCHAR(1024);
5. DROP COLUMN
1. Drop a column completely.
2. ALTER TABLE table-name DROP COLUMN col-name;
3. e.g., ALTER TABLE customer DROP COLUMN middle-name;
6. RENAME
1. Rename table name itself.
2. ALTER TABLE table-name RENAME TO new-table-name;
e.g., ALTER TABLE customer RENAME TO customer-details
Having clause

The having clause is used to filter the results of a Group by query


based on aggregate functions.

• Where Clause is used to filter rows before grouping


• Having Clause is used to filter grouped results after applying
aggregate functions.

Syntax : -
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column
HAVING condition;

MODULE 7
JOIN
To combine rows from two or more tables - JOIN Syntax.
There are six types of joins:
 Inner Join - to fetch matching records of both the tables.
 Left Join - to fetch all the records from left table and matching records from
the right table.
 Right Join to fetch all the records from right table - and matching records from
the left table.
 Full Join - to fetch all the records when there is a match in records.
 Self-Join – A join where a table is joined with itself to compare rows within a
same table.
 Cross Join – combining every row from first table with every row from the
second.

Inner Join:
Retrieves records from both tables where there is a match between the
department_id column in the Departments table and the department_id column in
the Employees table.
Syntax
SELECT <COLUMN NAME> FROM TABLE1 INNER JOIN TABLE2 ON <TABLE1.COLUMN
NAME>= <TABLE2.COLUMN NAME>

LEFT JOIN:
Retrieves all records from the Employees table and the matching records from the
Departments table based on the department_id column. If there is no match, the
result will contain NULL values for the columns from the Departments table.
Left Join Syntax
SELECT <COLUMN NAME> FROM TABLE1 LEFT JOIN
TABLE2 ON <TABLE1.COLUMN NAME>=
<TABLE2.COLUMN NAME>
RIGHT JOIN:
Retrieves all records from the Departments table and the matching records from the
Employees table based on the department_id column. If there is no match, the result
will contain NULL values for the columns from the Employees table.
Right Join Syntax
SELECT <COLUMN NAME> FROM TABLE1 RIGHT JOIN TABLE2 ON <TABLE1.COLUMN
NAME>= <TABLE2.COLUMN NAME>
FULL OUTER JOIN:
Retrieves all records from both the Employees and Departments tables. If there is a
match, it includes the matched records. If there is no match, it includes NULL values
for the columns from the other table.
Full Outer Join Syntax
SELECT <COLUMN NAME> FROM TABLE1 FULL OUTER JOIN TABLE2 ON
<TABLE1.COLUMN NAME>=<TABLE2.COLUMN NAME>

Self-Join –
Table data ---
CREATE TABLE employees (

employee_id INT PRIMARY KEY,

employee_name VARCHAR(50),

manager_id INT

);

INSERT INTO employees (employee_id, employee_name, manager_id) VALUES

(1, 'John', 3),

(2, 'Alice', 3),

(3, 'Bob', NULL),

(4, 'Carol', 2);

SELECT e1.employee_name AS employee, e2.employee_name AS manager

FROM employees e1 LEFT JOIN employees e2 ON e1.manager_id = e2.employee_id;

Cross join –
Product and Colors.

Table Data –

CREATE TABLE products (

product_id INT PRIMARY KEY,

product_name VARCHAR(50)

);

CREATE TABLE colors (

color_id INT PRIMARY KEY,

color_name VARCHAR(50)

);
INSERT INTO products (product_id, product_name) VALUES

(1, 'T-shirt'),

(2, 'Jeans');

INSERT INTO colors (color_id, color_name) VALUES

(1, 'Red'),

(2, 'Blue');

SELECT p.product_name, c.color_name


FROM products p
CROSS JOIN colors c;

You might also like