0% found this document useful (0 votes)
34 views38 pages

MYSQL Notes

The document provides a comprehensive overview of MySQL, covering key concepts such as data, databases, and database management systems (DBMS). It details various types of databases and DBMS, SQL commands, and the structure of tables, including data types and commands for data manipulation and definition. Additionally, it explains transaction control and query languages, along with practical examples of SQL commands.

Uploaded by

v.manohar792
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)
34 views38 pages

MYSQL Notes

The document provides a comprehensive overview of MySQL, covering key concepts such as data, databases, and database management systems (DBMS). It details various types of databases and DBMS, SQL commands, and the structure of tables, including data types and commands for data manipulation and definition. Additionally, it explains transaction control and query languages, along with practical examples of SQL commands.

Uploaded by

v.manohar792
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
You are on page 1/ 38

MYSQL

DATA:
Data is a statistically raw and unprocessed information. In computer language a piece of information
that can be translated into a form for efficient moment and processing is called data.
DATABASE:
Database is a collection of data that is organized which is also called structured data. It can be stored
in a computer system. It can be managed through database management system. In a database, data is
organized into tables consisting of rows and columns and it is indexed so data can be updated, expanded, and
deleted easily.
TYPES OF DATABASES:
 Relational Database
 Centralized Database
 NoSQL Database
 Distributed Database
 Cloud Database
 Network Database
 Object oriented Database
 Hierarchical Database
WHY WE USE DATABASE?
 Data Retrieval:
Database provide query that enable efficient and access of specific data.
 Data Organization:
Database allow for the structured organization of data into tables, rows, columns.
 Manage:
The structured data makes easier to understand and manage large sets of data.
 Relationship between data:
In relationship database data in different tables can be related to each other.
 Concurrency control:
Databases are designed to handle multiple users or process accessing and modifying data
simultaneously.
 Data Security:
This helps protect sensitive information and ensures that only authorized users can interact with
the database.
 Data Recovery:
Database often include features for data backup and recovery. Regular backups can be
performed to safeguard against data loss due to software errors, hardware failures or other
issues.

DBMS:
DBMS stands for Database Management System. It is a software system that facilitates the creation,
organization, and management of database.
The primary purpose of DBMS is to provide a structured way to store retrieve and manage data.
TYPES OF DBMS
 RDBMS (Relational Database Management System):
It organizes data into tables with rows and columns.
Tables can have relationship with each other.
Ex: MySQL, PostgreSQL, Oracle database, Microsoft SQL server
 NoSQL DBMS:
It is suitable for unstructured or semi-structured data.
Ex: Mango DB, Cassandra, Couchbase
 Object Oriented DBMS:
It stores the data in the form of objects, which are instance of classes.
Ex: db4o
 Graph DBMS:
It optimized for storing and querying graph data.
Ex: Neo4j, Arango DB
 In-memory DBMS:
It stores the data primarily in the computers main memory (RAM) for faster access.
Ex: Redis, SAP HANA
 Distributed DBMS:
It spreads data across multiple servers or locations.
Ex: Google cloud spanner, Amazon Aurora
 Columnar DBMS:
It stores the data in columns rather that rows optimizing for analytics.
Ex: Apache Cassandra, Amazon Redshift
 Time Series DBMS:
It optimized for handling time stamped data such as financial market data.
Ex: Influx DB, Open TSDB
 Document Oriented DBMS:
It stores data in semi-structured documents like Json or xml.
Ex: Mango DB, Couch DB
 XML DBMS:
It handles XML data.
Ex: BaseX

SQL – STRUCTURED QUERY LANGUAGE


It is designed for managing and manipulating Relational databases. It is a standard language for interacting
with RDBMS.
KEY CONCEPTS
1. Table: It represents the collection of related data.
2. Row: It is a single record in a table containing information about specific entity.
3. Column: It represents a specific attribute or field in a table.

SQL STATEMENTS
It consists of various statements used to perform different operations on a database.
1. SELECT: It retrieves data from one or more tables.
2. INSERT: Adds new record to a table.
3. UPDATE: Modifies existing records in a table.
4. DELETE: Removes records from a table.
5. CREATE: Creates new database objects such as tables and indexes.
6. ALTER: It modifies the structure of an existing database object.
7. DROP: Deletes a database object.
 SQL is not case sensitive but conventionally keywords are written in uppercase for better readability.
 Semicolons are used to terminate SQL statements.
MySQL COMMANDS
In MySQL the provided commands are used to perform various actions related to databases.
 SHOW DATABASES:
This command displays a list of existing databases in your MySQL server.
 CREATE DATABASE mydatabase:
This command creates a new database named mydatabase. After crating new database SHOW
DATABASES command is used to verify that the new database(mydatabase) has been
successfully created.
 USE mydatabase:
This command is used to switch to the specified database.
 DROP DATABASE mydatabase:
This command deletes the specified database permanently.
 EXIT:
This command is used to exist the MySQL command line interface.
 QUIT:
Similar to EXIT.

INTRODUCTION TO TABLES
A table is a fundamental structure used to organize and store data.
It is a 2D structure composed of rows and columns.
Each row in a table represents a record while each column represents a specific attribute.
CELL
The intersection of a row and column. It contains single data value.
PRIMARY KEY
It is a unique identifier for each record in the table.
TABLE NAME
Each table is given a unique name within the database.
DATATYPES
Datatypes define the kind of data that can be stored in a column.
The type of values are fixed or variable.

 NUMERIC:
These datatypes can include exact numeric datatypes
For ex: integer, float, bits

DATATYPE SIGNED UNSIGNED STORAGE


NAMES
TINYINT -128 to 127 0 to 255 1 Byte
(very small
integer)
SMALLINT -32768 to 32767 0 to 65535 2 Bytes
MEDIUMINT -8388608 to 8388607 0 to 16777215 3 Bytes
INT -2147483648 to 0 to 4294967295 4 Bytes
2147483647
BIGINT -9223372036854775808 0 to 8 Bytes
to 18446744073709551615
9223372036854775807

 FLOAT(m,d):
It is a floating-point number that cannot be unsigned. It defines the display length(m) and the
number of decimals(d).
For ex: float(10,2) which means 10 is the total number of digits including decimals where 2 is
the number of decimals.
It takes 24 places and requires 2 Bytes for storage.
 DOUBLE(m,d):
In this datatype decimal decision can go to 53 places and it requires 8 Bytes for storage.
It cannot be unsigned.
 DECIMAL(m,d):
In this datatype each decimal corresponds to byte.
 BIT(m):
It is used to store the bit values into the table column.
Here m defines number of bit per value that has a range of 1 to 64.
 BOOL:
It is used only for the true and false condition. It is considered numeric value 1 as True and 0
as False.
 BOOLEAN:
Similar to BOOL.
 STRING DATATYPES
The string datatypes is used to hold plain text and binary data.
NAME MAX SIZE FIXED/VARIABLE
CHAR(size) 255 characters Fixed length string
VARCHAR(size) 255 characters Variable length string
TINYTEXT(size) 255 characters Number of characters to store
TEXT(size) 65535 Number of characters to store
MEDIUM(size) 16777215
LONGTEXT(size) 4GB or 4294967295
BINARY(size) 255 characters Number of binary characters
stored or fixed length string
VARBINARY(size) 255 characters Variable length string
 BINARY LARGE OBJECT DATATYPE (BLOB)
TINYBLOB It can hold a max size of 255 bytes
BLOB It can hold a max size of 65535 bytes
MEDIUMBLOB It can hold a max size of 16777215 bytes
LONG It can hold a max size of 4GB/ 4294967295
bytes

 DATE AND TIME DATATYPES


This datatype is used for temporal values such as date, time, datetime, timestamp and year
DATATYPE RANGE/SIZE STORAGE FORMAT
Year[(2/4)] 2 digits or 4 digits 1 Byte YYYY
DATE 1000-01-01 to 3 Bytes YYYY-MM-DD
9999-12-31
TIME 00:00:00 to 3 Bytes HH:MM:SS
838:59:59
DATETIME 1000-01-01 5 Bytes YYYY-MM-DD
00:00:00 to HH:MM:SS
9999-12-31
23:59:59
TIMESTAMP(m) 1970-01-01 4 Bytes YYYY-MM-DD
00:00:01 to HH:MM:SS
2038-01-19
03:14:07

SQL COMMANDS

DDL DML DCL TCL DQL

CREATE INSERT GRANT COMMIT SELECT

DROP UPDATE REVOKE ROLLBACK

ALTER DELETE SAVEPOINT

TRUNCATE LOCK
DATA DEFINITION LANGUAGE (DDL)
 CREATE:
This command is used to create a new database, table, view or other database objects.
 DROP:
DROP is used to delete an existing database object, table.
It permanently removes the specified object.
 ALTER:
The ALTER command is used to modify the structure of an existing database object such as
table.
 TRUNCATE:
TRUNCATE is used to quickly delete all rows from a table.

DATA MANIPULATION LANGUAGE (DML)


 INSERT:
This command is used to add new records to a table.
 UPDATE:
UPDATE command is used to modify existing records in a table.
 DELETE:
DELETE command is used to remove records from a table based on a specific condition.
 LOCK:
LOCK can be used to control access to a resource, ensuring that only one transaction can access
it at a time, preventing conflicts.

DATA CONTROL LANGUAGE (DCL)


 GRANT:
The GRANT command is used to give specific permissions to a user in a database.
These permissions might include the ability to select, insert, update or delete data as well as
create or drop tables.
 REVOKE:
The REVOKE command is used to take away previously granted permissions from a user.

TRANSACTION CONTROL LANGUAGE (TCL)


 COMMIT:
The COMMIT command is used to permanently save the changes made during the current
transaction.
Once a transaction is committed, its changes become permanent and visible to other
transactions.
 ROLLBACK:
If an error occurs or if the transaction needs to be cancelled for any reason rollback is issued to
revert the database.
In simple it is used to undo the changes made during the current transaction.
 SAVEPOINT:
It is used to set a point within a transaction to which you can later ROLLBACK.
DATA QUERY LANGUAGE (DQL)
 SELECT:
SELECT command is used to retrieve data from one or more tables in a database.

COMMANDS
SHOW DATABASES;
CREATE DATABASE mydatabase;
SHOW DATABASES;
USE mydatabase;
DROP DATABASE mydatabase;
EXIT;

DDL
SHOW DATABASES;
CREATE DATABASE CODEGNAN;
USE CODEGNAN;
CREATE TABLE EMPLOYEES(EMP_ID CHAR(5),
-> FNAME VARCHAR(50),
-> LNAME VARCHAR(50),
-> AGE INT, DOJ DATE,
-> ADDRESS TINYTEXT,
-> DEPT VARCHAR(20));

SHOW TABLES;
DESC EMPLOYEES;
SHOW COLUMNS FROM EMPLOYEES;

ALTER TABLE EMPLOYEES


-> MODIFY FNAME VARCHAR(30);

DESC EMPLOYEES;

ALTER TABLE EMPLOYEES


-> ADD LOCATION TINYTEXT;
DESC EMPLOYEES;

ALTER TABLE EMPLOYEES


-> ADD PFID INT AFTER ADDRESS;

ALTER TABLE EMPLOYEES


-> RENAME COLUMN FNAME TO FIRSTNAME;

DESC EMPLOYEES;
ALTER TABLE EMPLOYEES
-> CHANGE COLUMN LNAME LASTNAME VARCHAR(60);

DESC EMPLOYEES;

ALTER TABLE EMPLOYEES


-> DROP COLUMN PFID;

ALTER TABLE EMPLOYEES


-> DROP COLUMN LOCATION;

ALTER TABLE EMPLOYEES RENAME CODEGNAN_EMP;

CREATE TABLE DEPARTMENTS (


-> DEPT_ID CHAR(3) PRIMARY KEY,
-> DEPT_NAME VARCHAR(50) NOT NULL,
-> MANAGER_ID CHAR(5),
-> LOCATION VARCHAR(100)
-> );

SHOW TABLES;
DESC departments;
DROP TABLE departments;
SHOW TABLES;
DESC codegnan_emp;
DML
INSERT INTO CODEGNAN_EMP (EMP_ID, FIRSTNAME, LASTNAME, AGE, DOJ, ADDRESS, DEPT)
-> VALUES ('E001', 'John', 'Doe', 30, '2023-01-01', '123 Main St', 'IT');

SELECT * FROM CODEGNAN_EMP;

INSERT INTO CODEGNAN_EMP (EMP_ID, FIRSTNAME, LASTNAME, AGE, DOJ, ADDRESS, DEPT)
-> VALUES
-> ('E001', 'John', 'Doe', 30, '2023-01-01', '123 Main St', 'IT'),
-> ('E002', 'Jane', 'Smith', 25, '2023-02-15', '456 Oak St', 'HR'),
-> ('E003', 'Bob', 'Johnson', 35, '2022-12-10', '789 Pine St', 'Finance');

SELECT * FROM CODEGNAN_EMP;

Delete a Specific Row:


DELETE FROM CODEGNAN_EMP
WHERE EMP_ID = 'E001';

Delete Rows Based on a Condition:


DELETE FROM CODEGNAN_EMP
WHERE AGE > 30;

Delete All Rows (Be Careful with This):


DELETE FROM CODEGNAN_EMP;

DELETE FROM CODEGNAN_EMP LIMIT 1;

UPDATE CODEGNAN_EMP
-> SET ADDRESS = '259 Spark St'
-> WHERE EMP_ID = 'E001';

SELECT * FROM CODEGNAN_EMP;


LOCK
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
START TRANSACTION;
-- Query and lock the row
SELECT * FROM CODEGNAN_EMP WHERE EMP_ID = 'E001' FOR UPDATE;
-- Update the AGE column
UPDATE CODEGNAN_EMP SET AGE = 31 WHERE EMP_ID = 'E001';

-- Commit the transaction


COMMIT;

SELECT * FROM CODEGNAN_EMP;

ROLLBACK
START TRANSACTION;

-- Perform some operations


UPDATE CODEGNAN_EMP SET AGE = 32 WHERE EMP_ID = 'E001';

INSERT INTO CODEGNAN_EMP (EMP_ID, FIRSTNAME, LASTNAME, AGE, ADDRESS, DEPT)


-> VALUES ('E004', 'Alice', 'Johnson', 28, '555 Elm St', 'Marketing');

SELECT * FROM CODEGNAN_EMP;

ROLLBACK;

SAVEPOINT
START TRANSACTION;

-- Perform some operations


UPDATE CODEGNAN_EMP SET AGE = 32 WHERE EMP_ID = 'E001';

INSERT INTO CODEGNAN_EMP (EMP_ID, FIRSTNAME, LASTNAME, AGE, ADDRESS, DEPT)


-> VALUES ('E004', 'Alice', 'Johnson', 28, '555 Elm St', 'Marketing');
SELECT * FROM CODEGNAN_EMP;

SAVEPOINT my_savepoint;

ROLLBACK TO SAVEPOINT my_savepoint;

SELECT * FROM CODEGNAN_EMP;


COMMIT;

SELECT
SELECT * FROM CODEGNAN_EMP;

-- Select specific columns from the CODEGNAN_EMP table


SELECT EMP_ID, FIRSTNAME, LASTNAME, AGE FROM CODEGNAN_EMP;

-- Select employees with an age greater than 30


SELECT * FROM CODEGNAN_EMP WHERE AGE > 30;

WHERE CLAUSE
The WHERE clause is used to filter records based on specific conditions in a query, allowing you to retrieve
data that meets specific criteria.
Ex: SELECT * FROM table WHERE column = ‘value’;
It means retrieves rows where the specific column has specific value.
SHOW DATABASES;
USE CODEGNAN;
SHOW TABLES;

SELECT * FROM CODEGNAN_EMP;


SELECT * FROM CODEGNAN_EMP WHERE AGE = 33;
SELECT * FROM CODEGNAN_EMP WHERE DEPT = ‘HR’;
SELECT * FROM CODEGNAN_EMP WHERE DOJ = ‘2023-02-04’;
SELECT * FROM CODEGNAN_EMP WHERE DOJ >= ‘2023-02-04’;
SELECT * FROM CODEGNAN_EMP WHERE DEPT = ‘MARKETING’ AND AGE = 26;
SELECT * FROM CODEGNAN_EMP WHERE AGE BETWEEN 25 AND 33;
MYSQL OPERATORS
MySQL operators are used to perform operation on the data in a database.
These operations can be categorized into several types

 ARITHMETIC OPERATORS

o +  used for addition

o -  used for subtraction

o *  used for multiplication

o /  used for division

o %  used for modulus which gives remainder

 COMPARISION OPERATORS

o =  checks if two values are equal

o != (or ) < >  checks is two values are not equal

o <  checks if left value is less than the right value

o >  checks if left value is greater than the right value

o <=  checks if left value is less than or equal to the right value

o >=  checks if left value is greater than or equal to the right value

o ‘BETWEEN’ & ‘AND’ : These are used to filter the results within a specific range

o ‘NOT BETWEEN’ & ‘AND’ : These are used to filter the results outside a specific range

o ‘IN’ : It is used to filter the results based on a list of specified values.

o ‘NOT IN’ : It is used to filter the results excluding a list of specified values.

o ‘IS NULL’ : It is used to filter results where a column is NULL.

o ‘IS NOT NULL’ : It is used to filter results where a column is NOT NULL.

 LOGICAL OPERATORS

o ‘AND’ : It is used to combine conditions. It returns TRUE only all conditions are TRUE

o ‘OR’ : It is used to combine conditions, it returns TRUE if atleast one of the condition is TRUE.

o ‘NOT’ : It is used to negate a condition. It returns TRUE if the condition is FALSE and vice

versa.
CREATE DATABASE librarydb;
USE librarydb;
CREATE TABLE BOOKS (
-> book_id INT PRIMARY KEY,
-> title VARCHAR(100),
-> author VARCHAR(50),
-> genre VARCHAR(50),
-> publication_year INT,
-> price DECIMAL(8, 2)
-> );

DESC books;

INSERT INTO books (book_id, title, author, genre, publication_year, price) VALUES
-> (1, 'The Great Gatsby', 'F. Scott Fitzgerald', 'Fiction', 1925, 15.99),
-> (2, 'To Kill a Mockingbird', 'Harper Lee', 'Fiction', 1960, 12.50),
-> (3, '1984', 'George Orwell', 'Dystopian', 1949, 10.99),
-> (4, 'The Catcher in the Rye', 'J.D. Salinger', 'Fiction', 1951, 14.75);

SELECT * FROM books;

-- Arithmetic Operators
UPDATE books SET price = price + 5.00;
SELECT * FROM books;

UPDATE books SET price = price - 3.00 WHERE publication_year < 1960;
SELECT * FROM books;

UPDATE books SET price = price * 2.0 WHERE genre = 'Fiction';


UPDATE books SET price = price / 2.0 WHERE publication_year > 1950;
UPDATE books SET price = 9.99 WHERE book_id % 2 <> 0;
-- Comparision Operators

SELECT * FROM books WHERE publication_year = 1960;


SELECT * FROM books WHERE genre != 'Fiction';
SELECT * FROM books WHERE price < 15.00;
SELECT * FROM books WHERE price > 15;
SELECT * FROM books WHERE publication_year <= 1950;
SELECT * FROM books WHERE publication_year >= 1950;
SELECT * FROM books WHERE publication_year BETWEEN 1950 AND 1960;
SELECT * FROM books WHERE price NOT BETWEEN 10.00 AND 20.00;
SELECT * FROM books WHERE genre IN ('Fiction', 'Science Fiction');
SELECT * FROM books WHERE genre NOT IN ('Fiction', 'Science Fiction');
SELECT * FROM books WHERE publication_year IS NULL;
SELECT * FROM books WHERE publication_year IS NOT NULL;

-- Logical Operators

SELECT * FROM books WHERE genre = 'Fiction' AND price > 15.00;
SELECT * FROM books WHERE genre = 'Dystopian' OR genre = 'Science Fiction';
SELECT * FROM books WHERE NOT genre = 'Fiction';

WARNINGS
In MySQL warnings are the issues that might effect the outcome of a query but don’t stop its execution.
ERRORS
These are the issues that prevent a query from completing successfully, when an error occur the server
typically stops processing the query returns an error message.

-- Warnings

SELECT 10/2;
SELECT 10 / 0;
SHOW WARNINGS;
Use codegnan;
CREATE TABLE mytable (
id INT PRIMARY KEY,
name VARCHAR(5)
);

INSERT INTO mytable (id, name) VALUES (1, 'ThisIsALongString');


SHOW WARNINGS;

SELECT '123abc' + 1;
SHOW WARNINGS;

SELECT CONCAT('123abc', 1);

#converting '2022-02-25' to Date type with cast function


SET sql_mode = 'STRICT_ALL_TABLES';
SELECT CAST('2022-02-25' AS DATE);
SELECT CAST('2022-02-30' AS DATE);
SHOW WARNINGS;

STRING FUNCTIONS
String functions are used to manipulate and operate on characters or text data.
There are different types of string functions:

 Alias: it is used to give a column or an expression a temporary name, making the output more
reliable.
Product_name AS ‘PRODUCT’
 CONCAT: it concatenates two or more strings.

CONCAT (product_name, category)

 CONCAT_WS: it concatenates with a specified separator.


 LOWER AND UPPER: it means converts the case of a string to lower case or upper case.
 Character length and Substring: it determines the length of a string and abstracts a substring.
LENGTH(product_name)
SUBSTRING(product_name,2,3)
Here 2 is the starting position in product_name.
3 is length of the substring to extract.
 Reverse and Replace: It means reverses the characters in a string and replaces occurrences of a
substring.
REVERSE(product_name)
REPLACE(category, ’Electronics’, ’Gadgets’)
 Left and right: Left extracts left most specified characters, right extracts right most specified
characters.

#String Functions

CREATE DATABASE PRODUCT_DETAILS;


USE PRODUCT_DETAILS;

CREATE TABLE PRODUCTS (


PRODUCT_ID INT PRIMARY KEY,
PRODUCT_NAME VARCHAR(100),
CATEGORY VARCHAR(50),
PRICE DECIMAL(8, 2)
);

-- INSERT SOME SAMPLE DATA


INSERT INTO PRODUCTS (PRODUCT_ID, PRODUCT_NAME, CATEGORY, PRICE) VALUES
(1, 'LAPTOP', 'ELECTRONICS', 1200.00),
(2, 'HEADPHONES', 'ELECTRONICS', 99.99),
(3, 'T-SHIRT', 'APPAREL', 19.99),
(4, 'COFFEE MAKER', 'APPLIANCES', 49.99);

DESC PRODUCTS;

SELECT * FROM PRODUCTS;

-- USING ALIASES FOR COLUMN NAMES


SELECT PRODUCT_NAME AS "PRODUCT", CATEGORY AS "PRODUCT CATEGORY", PRICE AS
"PRODUCT PRICE" FROM PRODUCTS;
-- CONCATENATING PRODUCT_NAME AND CATEGORY
SELECT CONCAT(PRODUCT_NAME, CATEGORY) AS "CONCATENATED" FROM PRODUCTS;

SELECT CONCAT(PRODUCT_NAME, ' - ', CATEGORY) AS "CONCATENATED" FROM PRODUCTS;

-- USING CONCAT_WS TO CONCATENATE PRODUCT_NAME AND CATEGORY WITH A


COMMA SEPARATOR
SELECT CONCAT_WS(', ', PRODUCT_NAME, CATEGORY) AS "CONCATENATED WITH
SEPARATOR" FROM PRODUCTS;

-- CONVERTING PRODUCT_NAME TO LOWERCASE AND CATEGORY TO UPPERCASE


SELECT LOWER(PRODUCT_NAME) AS "LOWERCASE", UPPER(CATEGORY) AS "UPPERCASE"
FROM PRODUCTS;

-- CALCULATING CHARACTER LENGTH OF PRODUCT_NAME AND EXTRACTING


SUBSTRINGS
SELECT PRODUCT_NAME,
LENGTH(PRODUCT_NAME) AS "LENGTH",
SUBSTRING(PRODUCT_NAME, 2, 3) AS "SUBSTRING"
FROM PRODUCTS;

# 2: THE STARTING POSITION IN THE PRODUCT_NAME


# 3: THE LENGTH OF THE SUBSTRING TO EXTRACT.

-- REVERSING PRODUCT_NAME AND REPLACING 'ELECTRONICS' WITH 'GADGETS'


SELECT REVERSE(PRODUCT_NAME) AS "REVERSED",
REPLACE(CATEGORY, 'ELECTRONICS', 'GADGETS') AS "REPLACED"
FROM PRODUCTS;

-- OTHER STRING FUNCTIONS


SELECT PRODUCT_NAME,
LEFT(PRODUCT_NAME, 3) AS "LEFT", -- EXTRACT LEFTMOST 3 CHARACTERS
RIGHT(CATEGORY, 2) AS "RIGHT", -- EXTRACT RIGHTMOST 2 CHARACTERS
TRIM(BOTH ' ' FROM CATEGORY) AS "TRIMMED", -- REMOVE LEADING AND TRAILING
SPACES
LPAD(PRODUCT_ID, 5, '0') AS "PADDED" -- LEFT PAD WITH ZEROS
FROM PRODUCTS;

CONSTRAINTS
They are used to limit the type of data that can go into a table.
Constraints are used to specify rules for the data in a table.
These ensures the accuracy and reliability of the data in the table.
The constraints are

 NOT NULL
 UNIQUE
 PRIMARY KEY
 DEFAULT
 CHECK
 FOREIGN KEY

CREATE TABLE NEW_TABLE_NAME(


COLUMN_NAME1 DATATYPE CONSTRAINT,
COLUMN_NAME2 DATATYPE CONSTRAINT,
……);
 NOT NULL
The NOT NULL constraint is used to ensure that a column cannot contain NULL values. It
means that every record in the table must have a value for the column.

 DEFAULT
The DEFAULT constraint is used to provide a default value for a column if no value is
explicitly specified during an INSERT operation. It is optional.

 PRIMARY KEY
It is a unique identifier for each Record in a table ensuring that no 2 rows have the same
values in the desired column.
 UNIQUE
The UNIQUE constraint ensures that all values in the specified column are distinct.
Preventing duplicate entries within that column in a table.
A table can have only one primary key.
A table can have multiple unique keys constraints.
A primary key column cannot contain null values.
A unique key can have null values.
 AUTO INCREMENT
AUTO INCREMENT is used to automatically generate unique, incremental values for a
column, typically it is a primary key.

 CHECK
CHECK constraint is used to enforce conditions on the values. That can be inserted into a
column.
It ensures that the data enter into a specific column meets certain criteria specified by the
CHECK constraint.

 FOREIGN KEY
It is a field or collection of fields in one table that refers to the primary key of another table.
The table with the foreign key is called the child table and the table with the primary is called
the reference or parent table.

CREATE TABLE new_table_name (


col_name1 datatype constraint,
col_name2 datatype constraint,
col_name3 datatype constraint,
.........
);

-- NOT NULL
SHOW DATABASES;
USE CODEGNAN;
SHOW TABLES;

CREATE TABLE STUDENT(


-> ID INTEGER,
-> LASTNAME TEXT NOT NULL,
-> FIRSTNAME TEXT NOT NULL
-> );

DESC STUDENT;

INSERT INTO STUDENT VALUES(1,'HANKS','PETER');


INSERT INTO STUDENT VALUES(2, NULL , 'JAMES');
INSERT INTO STUDENT VALUES(NULL, 'CAMEROON' , 'JAMES');
-- DEFAULT VALUE

CREATE TABLE PERSONS(


-> ID INT NOT NULL,
-> NAME VARCHAR(45) NOT NULL,
-> AGE INT,
-> CITY VARCHAR(25) DEFAULT 'NEWYORK'
-> );

DESC PERSONS;

INSERT INTO PERSONS(ID,NAME,AGE,CITY)


-> VALUES(1,'ROBERT',15,'FLORIDA'),
-> (2,'JOSEPH',35,'CALIFORNIA');

SELECT * FROM PERSONS;

INSERT INTO PERSONS(ID,NAME,AGE)VALUES


-> (1,'BEWON',15);

SELECT * FROM PERSONS;

-- PRIMARY KEY
CREATE TABLE Persons1 (
-> ID int NOT NULL PRIMARY KEY,
-> Name varchar(45) NOT NULL,
-> Age int,
-> City varchar(25));

DESC PERSONS1;

INSERT INTO Persons1(Id, Name, Age, City)VALUES


-> (1,'Robert', 15, 'Florida') ,
-> (2, 'Joseph', 35, 'California'),
-> (3, 'Peter', 40, 'Alaska');
SELECT * FROM PERSONS1;

INSERT INTO Persons1(Id, Name, Age, City)VALUES


-> (1,'Stephen', 15, 'Florida');
ERROR 1062 (23000): Duplicate entry '1' for key 'persons1.PRIMARY'

ALTER TABLE PERSONS1


-> DROP PRIMARY KEY;

DESC PERSONS1;

INSERT INTO Persons1(Id, Name, Age, City)VALUES


-> (2,'Stephen', 25, 'Florida');

SELECT * FROM PERSONS1;

-- UNIQUE

CREATE TABLE ShirtBrands(Id INTEGER, BrandName VARCHAR(40) UNIQUE, Size VARCHAR(30));

DESC SHIRTBRANDS;

INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Pantaloons', 38), (2, 'Cantabil', 40);

SELECT * FROM SHIRTBRANDS;

INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Raymond', 38);


INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(3,'Cantabil',25);

A table can have only one primary key.


A table can have multiple unique key constraints.

a primary key column cannot contain NULL values.


A unique key can have NULL values
-- AUTO_INCREMENT

CREATE TABLE Animals(


-> id int NOT NULL AUTO_INCREMENT,
-> name CHAR(30) NOT NULL,
-> PRIMARY KEY (id));

DESC ANIMALS;

INSERT INTO Animals (name) VALUES


-> ('Tiger'),('Dog'),('Penguin'),('Camel'),('Cat'),('Ostrich');

SELECT * FROM ANIMALS;

-- CHECK

CREATE TABLE Persons2(


-> ID int NOT NULL,
-> Name varchar(45) NOT NULL,
-> Age int CHECK (Age>=18)
-> );

DESC PERSONS2;
INSERT INTO Persons2(Id, Name, Age)
-> VALUES (1,'Robert', 28), (2, 'Joseph', 35), (3, 'Peter', 40);

SELECT * FROM PERSONS2;

INSERT INTO Persons2(Id, Name, Age) VALUES (1,'Robert', 15);


-- FOREIGN KEY

CREATE TABLE Persons3 (


Person_ID INT NOT NULL PRIMARY KEY,
Name VARCHAR(50),
Age INT,
City VARCHAR(50)
);

DESC PERSONS3;

INSERT INTO Persons3 (Person_ID, Name, Age, City) VALUES


(1, 'Robert', 15, 'Florida'),
(2, 'Joseph', 35, 'California'),
(3, 'Peter', 40, 'Alaska');

SELECT * FROM PERSONS3;

CREATE TABLE Orders (


Order_ID INT NOT NULL PRIMARY KEY,
Order_Num INT NOT NULL,
Person_ID INT,
FOREIGN KEY (Person_ID) REFERENCES Persons3(Person_ID)
);

DESC ORDERS;
INSERT INTO Orders (Order_ID, Order_Num, Person_ID) VALUES
-> (1, 5544, 2),
-> (2,3322,3),
-> (3,2135,2),
-> (4,3432,1);

SELECT * FROM ORDERS;


RELATIONSHIPS IN DBMS
In DBMS relationships between the tables are defined to establish connections between the data in different
tables.

 ONE TO ONE RELATIONSHIP (1:1)


In one-to-one relationship, each record in one table is related to exactly one record in another
table and vice versa.
Example, a table for employees and a table for employee details where each employee has
only one set of details.
 ONE TO MANY RELATIONSHIP (1:N)
In one-to-many relationship, each record in the primary table can be related to multiple
records in the related table, but each record in the related table is related to only one record in
the primary table.
Example, a table for customers and a table for orders where each customer can have multiple
orders but each order belongs to only one customer.

 MANY TO ONE RELATIONSHIP (N:1)


This relationship is the inverse of one-to-many relationship.
Many records in the primary table can be related to single record in the related table.
Example, a table for orders and a table for customers where many orders belongs to single
customer.

 MANY TO MANY RELATIONSHIP (N:N)


In many-to-many relationship, each record in the primary table can be related to multiple
records in the related table and vice versa.
Example, a table for students and a table for course where each student can enroll in multiple
courses and each course can have multiple students.
MYSQL CLAUSES
 DISTINCT
It means to retrieve unique values from a column.
Example, SELECT DISTINCT COLUMN_NAME FROM TABLE_NAME.

 ORDER BY
It means to sort the result based on one or more conditions.
Example, SELECT * FROM TABLE_NAME ORDER BY COLUMN_NAME ASE/DESC;

 LIMIT
It means to limit the number of rows return in the result set.
Example, SELECT * FROM TABLE_NAME LIMIT 10;

 LIKE
It means to filter based on a pattern. To find rows where a column starts with a specific value.
Example, SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE ‘L%’;
SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE ‘%CHAIR%’;

CREATE TABLE PRODUCTS (


PRODUCT_ID INT PRIMARY KEY,
PRODUCT_NAME VARCHAR(50) NOT NULL,
CATEGORY VARCHAR(30) NOT NULL,
PRICE DECIMAL(10, 2) NOT NULL
);

-- INSERTING SAMPLE DATA


INSERT INTO PRODUCTS VALUES
(1, 'LAPTOP', 'ELECTRONICS', 1200.00),
(2, 'HEADPHONES', 'ELECTRONICS', 50.00),
(3, 'COFFEE MAKER', 'APPLIANCES', 80.00),
(4, 'RUNNING SHOES', 'CLOTHING', 75.00),
(5, 'BACKPACK', 'ACCESSORIES', 40.00);

DISTINCT: To retrieve unique values from a column.


SELECT DISTINCT CATEGORY FROM PRODUCTS;
ORDER BY: To sort the result set.
SELECT * FROM PRODUCTS ORDER BY PRICE DESC;

LIMIT: To limit the number of rows returned.


SELECT * FROM PRODUCTS LIMIT 2;

LIKE:
To filter based on a pattern.
To find rows where a column starts with a specific value:
Starts with 'L'
SELECT * FROM PRODUCTS WHERE PRODUCT_NAME LIKE 'L%';
Contains 'Electronics'
SELECT * FROM PRODUCTS WHERE CATEGORY LIKE '%ELECTRONICS%';

AGGREGATE FUNCTIONS
 COUNT
It counts the total number of rows in a table.
Example, SELECT COUNT(*) FROM TABLE_NAME;

 GROUP BY
It groups rows based on the specified column.
Example, SELECT COLUMN_NAME, COUNT(*) FROM TABLE_NAME GROUP BY
COLUMN_NAME;
 MIN AND MAX
it finds the min and maximum values in a column.
Example, SELECT MIN(COLUMN_NAME), MAX(COLUMN_NAME) FROM
TABLE_NAME;
 GROUP BY WITH MIN AND MAX
It groups rows and finds the min and maximum values for each group.
Example, SELECT COLUMN_NAME, MIN(VALUE), MAX(VALUE) FROM
TABLE_NAME GROUP BY COLUMN_NAME;
 SUM AND AVG
It calculates the total sum and average of values in a column.
Example, SELECT SUM(COLUMN_NAME), AVG(COLUMN_NAME) FROM
TABLE_NAME;
 GROUP BY WITH SUM AND AVG
It groups rows and calculate the total sum and average for each group.
Example, SELECT COLUMN_NAME, SUM(VALUE), AVG(VALUE) FROM
TABLE_NAME GROUP BY COLUMN_NAME;
 SUBQUERIES
It uses a query within another to retrieve data or perform calculations.
Example, SELECT * FROM TABLE_NAME
WHERE COLUMN NAME = (SELECT MAX(COLUMN_NAME) FROM
TABLE_NAME);

-- Create Database
CREATE DATABASE SALES;

-- Use the Database


USE SALES;

-- Create Table
CREATE TABLE ORDERS (
ORDER_ID INT PRIMARY KEY,
PRODUCT_NAME VARCHAR(50),
QUANTITY INT,
PRICE DECIMAL(8, 2),
ORDER_DATE DATE
);

-- Insert Sample Data


INSERT INTO ORDERS VALUES
(1, 'WIDGET', 10, 20.00, '2024-01-01'),
(2, 'GADGET', 5, 15.00, '2024-01-02'),
(3, 'WIDGET', 8, 25.00, '2024-01-03'),
(4, 'DEVICE', 12, 10.00, '2024-01-03'),
(5, 'GADGET', 6, 18.00, '2024-01-04');

1) Count: Count the total number of orders.


SELECT COUNT(*) AS TOTAL_ORDERS
FROM ORDERS;
Explanation: The COUNT(*) function counts the total number of rows in the Orders table.
2) Group By: Count the number of orders for each product.
SELECT PRODUCT_NAME, COUNT(*) AS TOTAL_ORDERS
FROM ORDERS
GROUP BY PRODUCT_NAME;
Explanation: The GROUP BY clause groups the result set by the product_name column, and the COUNT(*)
function counts the number of orders in each group.

3) Min and Max: Find the minimum and maximum quantity of products ordered.
SELECT MIN(QUANTITY) AS MIN_QUANTITY, MAX(QUANTITY) AS MAX_QUANTITY
FROM ORDERS;
Explanation: The MIN() and MAX() functions retrieve the minimum and maximum values of the quantity
column, respectively.

4) Group By with Min and Max: Find the minimum and maximum price for each product.
SELECT PRODUCT_NAME, MIN(PRICE) AS MIN_PRICE, MAX(PRICE) AS MAX_PRICE
FROM ORDERS
GROUP BY PRODUCT_NAME;
Explanation: This query uses GROUP BY to group the result set by product_name and then calculates the
minimum and maximum prices for each product.

5) Sum and Avg: Calculate the total quantity and average price of all orders.
SELECT SUM(QUANTITY) AS TOTAL_QUANTITY, AVG(PRICE) AS AVERAGE_PRICE
FROM ORDERS;
Explanation: The SUM() function calculates the total quantity, and the AVG() function calculates the average
price across all orders.

6) Group By with Sum and Avg: Calculate the total quantity and average price for each product.
SELECT PRODUCT_NAME, SUM(QUANTITY) AS TOTAL_QUANTITY, AVG(PRICE) AS
AVERAGE_PRICE
FROM ORDERS
GROUP BY PRODUCT_NAME;
Explanation: This query uses GROUP BY to group the result set by product_name and then calculates the
total quantity and average price for each product.

7) Subqueries: Find the product(s) with the highest total quantity.


SELECT PRODUCT_NAME, SUM(QUANTITY) AS TOTAL_QUANTITY
FROM ORDERS
GROUP BY PRODUCT_NAME
HAVING SUM(QUANTITY) = (SELECT MAX(TOTAL_QUANTITY) FROM (SELECT
SUM(QUANTITY) AS TOTAL_QUANTITY FROM ORDERS GROUP BY PRODUCT_NAME) AS
SUBQUERY);
Explanation: The subquery calculates the total quantity for each product, and the main query finds the
product(s) with the highest total quantity using the HAVING clause. The subquery is used to find the maximum
total quantity.

DATE AND TIME FUNCTIONS


 DATE( ):
It extracts the date part of a date or datetime expression.
Example, SELECT DATE(‘2024-01-09 15:30:45’);
Output - 2024-01-09

 TIME( ):
It extracts the time part of a date or date-time expression.
Example, SELECT TIME(‘2024-01-09 15:30:45’);
Output - 15:30:45
 YEAR( ), MONTH( ), DAY( ):
It extracts the year, month or day from a date.
Example, SELECT YEAR(‘2024-01-09’),
MONTH(‘2024-01-09’),
DAY(‘2024-01-09’);
 NOW( ):
It returns the current date and time.
Example, SELECT NOW( );
 CURDATE( ):
This functions returns the current date in ‘YYYY-MM-DD’ format.
Example, SELECT CURDATE( );
 CURTIME( ):
This functions returns the current time in ‘HH:MM:SS’ format.
Example, SELECT CURTIME( );
 CURRENT_TIMESTAMP( ):
This function returns the current date and time in ‘YYYY-MM-DD HH:MM:SS’ format.
Example, SELECT CURRENT_TIMESTAMP( );
 DATE FORMAT:
It formats the date as specified.
Example, SELECT DATE_FORMAT(‘2024-01-09’,’%w,%m,%e,%y’);
%w – Full weekday name
%m – Full month name
%e – day of the month
%y – four digit year
 DATEDIFF( ):
It calculates the difference between two dates.
Example, SELECT DATEDIFF(‘2024-01-09’,’ 2024-01-14’);
 DATE_ADD( ) AND DATE_SUB( ):
It adds or subtract a specified time interval from a date.
Example, SELECT DATE_ADD(‘2024-01-09’,INTERVAL 5 DAY);
2024-01-09 : Start date
INTERVAL: It is a keyword indicating that you are adding a time interval.
5 : value, which means the number of intervals to add.
DAY : unit, it is the unit of intervals.
Example, SELECT DATE_ADD(‘2024-01-09’,INTERVAL 3 MONTH);
SELECT DATE_SUB(‘2024-01-09’,INTERVAL 3 MONTHS);
 EXTRACT( ):
It extracts a part of a date or time.
Example, SELECT EXTRACT(HOUR FROM ‘2024-01-09 11:30:45’);
 TIMESTAMPDIFF( ):
It calculates the difference between two timestamps.
Example, SELECT TIMESTAMPDIFF(SECOND, ‘2024-01-09 11:30:45’,
‘2024-01-09 15:30:45’);
 TIMEDIFF( ):
It calculates the difference between two times.
Example, SELECT TIMEDIFF(‘11:30:45’, ‘15:30:45’);
 ADDTIME( ) AND SUBTIME( ):
Adds or subtracts a time interval to a time or date-time expression.
Example, SELECT ADDTIME(‘11:30:45’, ‘15:30:45’);
Example, SELECT SUBTIME(‘11:30:45’, ‘15:30:45’);

 FORMATTING DATES:
SELECT DATE_FORMAT(‘2024-01-09 11:30:45’,’%Y-%M-%D %H:%I:%S’);
%H – 2 digit hour in 24 hour format
%I – 2 digit minutes (00-59)
%S – 2digit second (00-59)
SELECT DATE_FORMAT(‘2024-01-09 11:30:45’,’DATE - %Y-%M-%D’);
DATE():
Extracts the date part of a date or datetime expression.
SELECT DATE('2024-01-08 15:30:45');

TIME():
Extracts the time part of a date or datetime expression.
SELECT TIME('2024-01-08 15:30:45');

YEAR(), MONTH(), DAY():


Extracts the year, month, or day from a date.
SELECT YEAR('2024-01-08'), MONTH('2024-01-08'), DAY('2024-01-08');

NOW():
Returns the current date and time.
SELECT NOW();

CURDATE():
This function returns the current date in 'YYYY-MM-DD' format.
SELECT CURDATE();

CURTIME():
This function returns the current time in 'HH:MM:SS' format.
SELECT CURTIME();

CURRENT_TIMESTAMP():
This function returns the current date and time in 'YYYY-MM-DD HH:MM:SS' format.
SELECT CURRENT_TIMESTAMP();

DATE_FORMAT():
Formats a date as specified.
SELECT DATE_FORMAT('2024-01-08', '%W, %M %e, %Y');

%W: Full weekday name (Wednesday)


%M: Full month name (January)
%e: Day of the month as a single digit (8)
%Y: Four-digit year (2024)

DATEDIFF():
Calculates the difference between two dates.
SELECT DATEDIFF('2024-01-15', '2024-01-08');

DATE_ADD() and DATE_SUB():


Adds or subtracts a specified time interval from a date.
SELECT DATE_ADD('2024-01-08', INTERVAL 5 DAY);
SELECT DATE_SUB('2024-12-08', INTERVAL 3 MONTH);

start_date: '2024-01-08'
INTERVAL: Keyword indicating that you're adding a time interval.
value: The number of intervals to add (5 in this case).
unit: The unit of the interval (DAY in this case).
So, the query adds 5 days to '2024-01-08', resulting in a new date. The output of this query would be:

EXTRACT():
Extracts a part of a date or time.
SELECT EXTRACT(HOUR FROM '2024-01-08 15:30:45');

TIMESTAMPDIFF():
Calculates the difference between two timestamps.
SELECT TIMESTAMPDIFF(SECOND, '2024-01-08 12:00:00', '2024-01-08 15:30:45');

TIMEDIFF():
Calculates the difference between two times.
SELECT TIMEDIFF('15:30:45', '12:00:00');

ADDTIME() and SUBTIME():


Adds or subtracts a time interval to a time or datetime expression.
SELECT ADDTIME('12:00:00', '03:30:45');
Formatting dates
SELECT DATE_FORMAT('2024-01-08 15:30:45', '%Y-%m-%d %H:%i:%s');
%Y: Four-digit year
%m: Two-digit month (01-12)
%d: Two-digit day of the month (01-31)
%H: Two-digit hour in 24-hour format (00-23)
%i: Two-digit minutes (00-59)
%s: Two-digit seconds (00-59)

-- Display the month name and year


SELECT DATE_FORMAT('2024-01-08', '%M %Y');

-- Display the day of the week and abbreviated month name


SELECT DATE_FORMAT('2024-01-08', '%W, %b %d');

-- Display the date in a custom format


SELECT DATE_FORMAT('2024-01-08', 'Date: %m/%d/%Y');
JOINS INTRODUCTION
In relational databases, tables are used to organise and store data. When designing database its common to
distribute information across multiple tables to avoid data redundancy and maintain well organised structures.
However, there are scenarios where you need to combine data from multiple tables to retrieve meaningful
information. This is where SQL joins come into play.

JOINS
Join in MySQL that allows you to retrieve data from 2 or more tables based on a related column. That related
column is a foreign key that establish a connection between the tables.
The result of a join is a new temporary table that combines column from the tables.

 CROSS JOIN
It combines all rows from table 1 with all rows from Table 2.

EMP DEPT
ID NAME DEPT ID EMP_ID SALARY
1 A HR 1 1 50000
2 B IT 2 2 60000
3 C SALES 3 3 45000

ID NAME DEPARTMENT ID EMP_ID SALARY


3 C SALES 1 1 50000
2 B IT 1 1 50000
1 A HR 1 1 50000
3 C SALES 2 2 60000
2 B IT 2 2 60000
1 A HR 2 2 60000
3 C SALES 3 3 45000
2 B IT 3 3 45000
1 A HR 3 3 45000

Syntax,
SELECT * FROM TABLE1 CROSS JOIN TABLE 2;
 INNER JOIN
It retrieves rows where there is a match in both the tables based on a specified condition.

ID NAME DEPT ID EMP_ID SALARY

1 A HR 1 1 50000

2 B IT 2 2 60000

3 C SALES 3 3 45000

ID NAME DEPT SALARY


1 A HR 50000
2 B IT 60000
3 C SALES 45000

Syntax,
SELECT * FROM TABLE1 INNER JOIN TABLE2 ON TABLE1.COLUMN
=TABLE2.COLUMN;

 OUTER JOIN
Left/left outer join
It retrieves all rows from table1 in matching the rows from table 2. Non matching rows in table
2 will have null values.
EMP DEPT
NAME DEPTNO DNAME DEPTNO
A 20 D1 10
B null D2 20
C 10 D3 30
D null D4 40

A 20 D2
B null null
C 10 D1
D null null

Syntax,
SELECT * FROM TABLE1 LEFT JOIN TABLE2 ON TABLE1.COLUMN
=TABLE2.COLUMN;
 RIGHT JOIN
Retrieve all rows from table2 and the matching rows from table1.
Non matching in table1 will have null values.

EMP DEPT
NAME DEPTNO DNAME DEPTNO
A 20 D1 10
B null D2 20
C 10 D3 30
D null D4 40

C 10 D1
A 20 D2
NULL NULL D3
NULL NULL D4

Syntax,
SELECT * FROM TABLE1 RIGHT JOIN TABLE2 ON TABLE1.COLUMN
=TABLE2.COLUMN;

CREATE DATABASE company;


USE company;

-- Employees Table
CREATE TABLE employees (
-> id INT PRIMARY KEY,
-> name VARCHAR(255),
-> department VARCHAR(255)
-> );

-- Salaries Table
CREATE TABLE salaries (
-> id INT PRIMARY KEY,
-> employee_id INT,
-> salary INT,
-> FOREIGN KEY (employee_id) REFERENCES employees(id)
-> );
-- Insert values into Employees table
INSERT INTO employees (id, name, department) VALUES
-> (1, 'Alice', 'HR'),
-> (2, 'Bob', 'IT'),
-> (3, 'Charlie', 'Sales');

-- Insert values into Salaries table


INSERT INTO salaries (id, employee_id, salary) VALUES
-> (1, 1, 50000),
-> (2, 2, 60000),
-> (3, 3, 45000);

select * from employees;

select * from salaries;

-- Cross Join (Cartesian Product)


SELECT * FROM employees CROSS JOIN salaries;

-- Inner Join
SELECT employees.id, name, department, salary
-> FROM employees
-> INNER JOIN salaries ON employees.id = salaries.employee_id;

-- Create the emp table


CREATE TABLE emp (
-> Ename VARCHAR(255),
-> DeptNo INT
-> );

-- Create the dept table


CREATE TABLE dept (
-> DNAME VARCHAR(255),
-> DeptNo INT
-> );
-- Insert values into emp table
INSERT INTO emp (Ename, DeptNo) VALUES
-> ('A', 20),
-> ('B', NULL),
-> ('C', 10),
-> ('D', NULL);

-- Insert values into dept table


INSERT INTO dept (DNAME, DeptNo) VALUES
-> ('D1', 10),
-> ('D2', 20),
-> ('D3', 30),
-> ('D4', 40);

select * from emp;


select * from DEPT;

-- Perform LEFT JOIN


SELECT emp.Ename, emp.DeptNo, dept.DNAME
-> FROM emp
-> LEFT JOIN dept ON emp.DeptNo = dept.DeptNo;

-- Perform RIGHT JOIN


SELECT emp.Ename, emp.DeptNo, dept.DNAME
-> FROM emp
-> RIGHT JOIN dept ON emp.DeptNo = dept.DeptNo;

You might also like