- π± Introduction
- π± Database-Table
- π± Inserting-Data
- π± Select-And-Where
- π± Constraints
- π± AND-OR-NOT
- π± In-Operator
- π± LIKE-Operator
- π± Between-NOT-Between
- π± Order-By-And-Distinct
- π± Is-Null-And-Is-Not-Null
- π± Limit-And-Offset
- π± Aggregate-Functions
- π± Update-Query
- π± Delete-Query
- π± Primary-And-Foreign-Key
- π± Joins
- π± Sub-Query
- π± Exists-And-Not-Exists
A database is an organized collection of structured information or data.
Database Management Systems (DBMS) are software systems used to store, retrieve, and run queries on data.
It is of two types:
-
Relational (SQL)
A relational database is a collection of data items with pre-defined relationships between them, stored in the form of tables, rows, and columns.
Examples: MySQL, Oracle, PostgreSQL.
-
Non-Relational (No-SQL)
NoSQL databases are non-relational, offering flexible schemas, scalability, and support for diverse data models. Commonly used in web development, analytics, and content management for handling large and dynamic data.
Examples: MongoDB, Cassandra, Redis.
MySQL is a relational database management system (RDBMS) developed by Oracle i.e. based on structured query language (SQL).
A database table is a collection of rows and columns that contains relational data.
CREATE DATABASE database_name;
CREATE DATABASE mydatabase;
USE database_name;
USE mydatabase;
Define table structure with columns and data types.
CREATE TABLE table_name
(
column1 datatype1,
column2 datatype2,
...
);
CREATE TABLE users
(
id int unsigned,
name varchar(100),
email varchar(150),
password varchar(100),
contact varchar(15),
address text,
dob date,
gender enum("M", "F", "O"),
status boolean
);
- Strings
- Numeric
- Date & Time
π String Data Types
-
CHAR(n): Fixed-length character string.
-
VARCHAR(n): Variable-length character string.
-
TEXT: Variable-length character string with no specified limit.
-
TINYTEXT: A very small variable-length character string.
-
MEDIUMTEXT: A medium-sized variable-length character string.
-
LONGTEXT: A long variable-length character string.
-
BINARY(n): Fixed-length binary string.
-
VARBINARY(n): Variable-length binary string.
-
BLOB: Variable-length binary large object.
-
TINYBLOB: A very small variable-length binary large object.
-
MEDIUMBLOB: A medium-sized variable-length binary large object.
-
LONGBLOB: A long variable-length binary large object.
-
ENUM('value1', 'value2', ...): Enumerated type, representing one of a predefined set of values.
-
SET('value1', 'value2', ...): Set type, representing a collection of values chosen from a predefined set.
π Number Data Types
-
INTEGER or INT: Represents whole numbers.
-
TINYINT: A very small integer.
-
SMALLINT: Small-sized integer.
-
MEDIUMINT: Medium-sized integer.
-
BIGINT: Large-sized integer.
-
DECIMAL(p, s) or NUMERIC(p, s): Fixed-point decimal numbers with precision (total digits) and scale (decimal places).
-
FLOAT(p): Floating-point number with single-precision.
-
DOUBLE(p): Floating-point number with double-precision.
-
REAL: A synonym for DOUBLE.
-
BIT(n): A bit-field type, representing a fixed number of bits.
π Date-Time Data Types
In MySQL, the specific date and time data types include:
-
DATE: Represents a date in the format YYYY-MM-DD.
-
TIME: Represents a time of day in the format HH:MM:SS.
-
DATETIME: Represents a combination of date and time in the format YYYY-MM-DD HH:MM:SS.
-
TIMESTAMP: Similar to DATETIME but with a narrower range and automatically converts to the current timestamp on insert or update.
-
YEAR: Represents a four-digit year value.
π₯ Syntax:
INSERT INTO table_name
(column1, column2, column3, ...)
VALUES
(value1, value2, value3, ...);
π Example:
INSERT INTO users
(id, name, email, password, contact, address, dob, gender, status)
VALUES
(1, 'John Doe', 'john@example.com', 'hashed_password', '+123456789', '123 Main St, City', '1990-01-15', 'M', 1);
π₯ Syntax:
INSERT INTO table_name
(column1, column2, column3, ...)
VALUES
(value1, value2, value3, ...),
(value1, value2, value3, ...),
(value1, value2, value3, ...)
π Example:
INSERT INTO users
(id, name, email, password, contact, address, dob, gender, status)
VALUES
(2, 'Jane Smith', 'jane@example.com', 'hashed_password2', '+987654321', '456 Oak St, Town', '1995-03-22', 'F', 1),
(3, 'Alex Johnson', 'alex@example.com', 'hashed_password3', '+1122334455', '789 Pine St, Village', '1988-07-10', 'M', 0),
(4, 'Avery Taylor', 'avery@example.com', 'hashed_password4', '+9988776655', '321 Elm St, City', '2000-09-05', 'O', 1),
(5, 'Chris Anderson', 'chris@example.com', 'hashed_password5', '+1122334466', '567 Birch St, Town', '1992-12-18', 'M', 0),
(6, 'Taylor Davis', 'taylor@example.com', 'hashed_password6', '+1122334477', '876 Maple St, Village', '1985-05-30', 'F', 1);
In MySQL, you use the SELECT statement to retrieve data from one or more tables.
π₯ Syntax:
SELECT column1, column2, ...
FROM table_name;
π Example:
SELECT name, email
FROM users;
If you want to select all columns from a table, you can use the wildcard *
π₯ Syntax:
SELECT *
FROM table_name;
π Example:
SELECT *
FROM users;
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
π₯ Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition
π Example:
SELECT id, name, email
FROM users
WHERE gender = 'M' AND status = 1;
In SQL, the WHERE clause is used to filter the rows returned by a query based on specified conditions. Here are common conditions that can be used in conjunction with the WHERE clause:
-
Equality (
=
):- Used to filter rows where a specified column is equal to a specific value.
- Example:
WHERE column_name = value;
-
Inequality (
!=
or<>
):- Used to filter rows where a specified column is not equal to a specific value.
- Example:
WHERE column_name <> value;
-
Comparison Operators (
<
,>
,<=
,>=
):- Used to filter rows based on numerical or date comparisons.
- Example:
WHERE column_name > value;
-
LIKE Operator:
- Used to perform pattern matching with wildcard characters (
%
for any sequence of characters,_
for a single character). - Example:
WHERE column_name LIKE 'pattern';
- Used to perform pattern matching with wildcard characters (
-
BETWEEN Operator:
- Used to filter rows within a specified range.
- Example:
WHERE column_name BETWEEN value1 AND value2;
-
IN Operator:
- Used to filter rows where a column matches any value in a specified list.
- Example:
WHERE column_name IN (value1, value2, ...);
-
IS NULL and IS NOT NULL:
- Used to filter rows where a column is (or is not) NULL.
- Example:
WHERE column_name IS NULL;
-
Logical Operators (AND, OR, NOT):
- Used to combine multiple conditions.
- Example:
WHERE condition1 AND condition2;
-
EXISTS Operator:
- Used to check if a subquery returns any results.
- Example:
WHERE EXISTS (SELECT * FROM another_table WHERE condition);
-
ANY and ALL Operators:
- Used with subqueries for comparing values.
- Example:
WHERE column_name > ANY (SELECT column_name FROM another_table);
In SQL, an alias is a temporary name. It is used to provide a more readable or meaningful name to a table or column, especially when dealing with complex queries or when working with the result of a query.
There are two main types of aliases:
-
Table Alias:
-
Used to give a table a temporary, alternative name in a query.
-
π₯ Syntax:
SELECT column1, column2, ... FROM table_name AS alias_name WHERE condition;
-
π Example:
SELECT name, id FROM users AS Active_Users WHERE status = 1;
-
-
Column Alias:
-
Used to assign a temporary name to a column in the result set.
-
π₯ Syntax:
SELECT column_name AS alias_name, ... FROM table_name WHERE condition;
-
π Example:
SELECT name AS E_Name, id AS U_ID FROM users WHERE status = 1;
-
In MySQL, table constraints are rules or conditions applied to the columns in a table to maintain the integrity, accuracy, and relationships of the data.
They are specified during the table creation using the CREATE TABLE
statement. Constraints can also be added or modified later using the ALTER TABLE
statement.
-
PRIMARY KEY Constraint:
-
Ensures that a column or a combination of columns uniquely identifies each row in the table.
-
π Example:
CREATE TABLE employees ( employee_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50) );
-
-
FOREIGN KEY Constraint:
-
Establishes a link between two tables, enforcing referential integrity.
-
π Example:
CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) );
-
-
UNIQUE Constraint:
-
Ensures that all values in a column (or a combination of columns) are unique.
-
π Example:
CREATE TABLE products ( product_name VARCHAR(100) UNIQUE, price DECIMAL(10, 2) );
-
-
CHECK Constraint:
-
Specifies a condition that must be satisfied for each row in the table.
-
π Example:
CREATE TABLE employees ( employee_id INT, salary DECIMAL(10, 2) CHECK (salary >= 0) );
-
-
DEFAULT Constraint:
-
Provides a default value for a column if no value is specified during an INSERT operation.
-
π Example:
CREATE TABLE students ( id INT NOT NULL UNIQUE, name VARCHAR(100) NOT NULL, email VARCHAR(150) NOT NULL UNIQUE, age TINYINT CHECK (age >= 18), status BOOLEAN DEFAULT 1 );
-
-
NOT NULL Constraint:
-
Ensures that a column cannot have a NULL value.
-
π Example:
CREATE TABLE orders ( order_id INT, order_date DATE NOT NULL );
-
-
AND Operator:
-
The
AND
operator is used to retrieve rows that satisfy multiple conditions simultaneously. -
π Example: Retrieve students who are both active (
status = 1
) and have an age greater than or equal to 20.SELECT * FROM students WHERE status = 1 AND age >= 20;
-
-
OR Operator:
-
The
OR
operator is used to retrieve rows that satisfy at least one of multiple conditions. -
π Example: Retrieve students who are either inactive (
status = 0
) or have an age less than 18.SELECT * FROM students WHERE status = 0 OR age < 18;
-
-
NOT Operator:
-
The
NOT
operator is used to negate a condition, retrieving rows that do not satisfy a particular condition. -
π Example: Retrieve students who are not active (
status = 0
).SELECT * FROM students WHERE NOT status = 0;
-
The SQL IN operator is used to specify multiple values in a WHERE clause for a SELECT, UPDATE, DELETE, or INSERT statement. It is typically used to reduce the use of multiple OR conditions in a query.
π₯ Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE column_name IN (value1, value2, ...);
-
column1, column2, ...
: The columns you want to retrieve in the SELECT statement. -
table_name
: The name of the table from which to retrieve the data. -
column_name
: The column against which you want to compare values. -
(value1, value2, ...)
: The list of values to compare with the specified column.π Example:
SELECT * FROM students WHERE age IN (19,20);
The LIKE Operator is used in a WHERE Clause to search for a specified pattern in a column.
-
The percent sign (%) represents zero, one, or multiple characters.
-
The underscore sign (_) represents one, single character.
π₯ Syntax:
SELECT column1, column2, ... FROM table_name WHERE column_name LIKE pattern;
π Example:
SELECT name FROM students WHERE name LIKE "a%";
'a%' : Starts with "a".
'%a' : End with "a".
'%or%' : Have "or" in any position.
'_r%' : Have "r" in the second position.
'a_%' : Starts with "a" and are at least 2 characters in length (including a).
'a__%' : Starts with "a" and are at least 3 characters in length (including a).
'a%o' : Starts with "a" and ends with "o".
The BETWEEN and NOT BETWEEN operators in SQL are used to filter the result set based on a range of values. These operators are typically used in the WHERE clause of a SQL query.
π₯ Syntax (BETEEN):
SELECT column1, column2, ...
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
π Example:
SELECT *
FROM students
WHERE age BETWEEN 20 AND 30;
π₯ Syntax (NOT BETWEEN):
SELECT column1, column2, ...
FROM table_name
WHERE column_name NOT BETWEEN value1 AND value2;
π Example:
SELECT *
FROM students
WHERE age NOT BETWEEN 20 AND 30;
The ORDER BY clause in SQL is used to sort the result set of a query based on one or more columns. It is typically used at the end of a SELECT statement.
Remember that you can sort in ascending order (ASC) or descending order (DESC). If you don't specify the order, ASC is assumed by default.
π₯ Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
π Example :
SELECT id, name, age, status
FROM students
ORDER BY age ASC;
The DISTINCT keyword in SQL is used in a SELECT statement to eliminate duplicate rows from the result set. It returns only unique values for the specified columns.
π₯ Syntax:
SELECT DISTINCT column1, column2, ...
FROM table_name
WHERE condition;
π Example:
SELECT DISTINCT status
FROM students;
The IS NULL operator is used to filter rows where a specified column contains a null value.
π₯ Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE column_name IS NULL;
π Example:
SELECT *
FROM students
WHERE age IS NULL;
The IS NOT NULL operator is used to filter rows where a specified column does not contain a null value.
π₯ Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE column_name IS NOT NULL;
π Example:
SELECT *
FROM students
WHERE age IS NOT NULL;
If want to LIMIT, the number of results that are returned you can simply use the LIMIT command with several rows to LIMIT by.
π₯ Syntax:
SELECT *
FROM table_name
LIMIT number_to_limit_by;
π Example:
SELECT *
FROM students
LIMIT 3;
You can also specify an OFFSET from where to start returning the Data.
π₯ Syntax:
SELECT *
FROM table_name
LIMIT number_to_limit_by OFFSET number_of_rows_to_skip;
π Example:
SELECT *
FROM students
LIMIT 3 OFFSET 2;
In MySQL, aggregate functions are used to perform a calculation on a set of values and return a single value.
Here are some common aggregate functions in MySQL:
-
COUNT():
- Counts the number of rows in a result set.
π₯ Syntax:
SELECT COUNT(column_name) FROM table_name WHERE condition;
-
SUM():
- Calculates the sum of values in a numeric column.
π₯ Syntax:
SELECT SUM(column_name) FROM table_name WHERE condition;
-
AVG():
- Calculates the average of values in a numeric column.
π₯ Syntax:
SELECT AVG(column_name) FROM table_name WHERE condition;
-
MIN():
- Finds the minimum value in a column.
π₯ Syntax:
SELECT MIN(column_name) FROM table_name WHERE condition;
-
MAX():
- Finds the maximum value in a column.
π₯ Syntax:
SELECT MAX(column_name) FROM table_name WHERE condition;
π Example:
SELECT SUM() AS total_sales, AVG(sale_amount) AS average_sale, COUNT(order_id) AS order_count FROM sales WHERE sale_date >= '2022-01-01';
-
An update query is a database operation that modifies existing records in a table.
-
Specify a condition that determines which records to update. If you omit the WHERE clause, all records in the table will be updated.
π₯ Syntax:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
π Example:
UPDATE employees SET salary = salary * 1.1 WHERE bonus > 5000;
-
A delete query is used in SQL to remove records from a table based on specified conditions.
-
Please be careful when using delete queries, especially without a WHERE clause, as it can result in the removal of all records from the specified table.
π₯ Syntax:
DELETE FROM table_name WHERE condition;
π Example:
DELETE FROM employees WHERE salary < 30000;
-
A primary key is a unique identifier for a record in a database table.
-
It must contain unique values and cannot have NULL values.
-
Each table in a relational database typically has a primary key that uniquely identifies each record in that table.
-
The primary key is used to establish relationships between tables.
π Example
CREATE TABLE cities ( city_id INT PRIMARY KEY, city_name VARCHAR(50), country VARCHAR(50) ); INSERT INTO cities (city_id, city_name, country) VALUES (1, 'New York', 'USA'), (2, 'London', 'UK'), (3, 'Tokyo', 'Japan'), (4, 'Paris', 'France');
-
A foreign key is a field in a database table that is a primary key in another table.
-
It establishes a link between the data in two tables.
-
The foreign key in one table points to the primary key in another table.
-
It is used to maintain referential integrity between the two related tables.
π Example
CREATE TABLE students ( student_id INT PRIMARY KEY, student_name VARCHAR(50), age INT, city_id INT, FOREIGN KEY (city_id) REFERENCES cities(city_id) ); INSERT INTO students (student_id, student_name, age, city_id) VALUES (101, 'John Doe', 20, 1), (102, 'Jane Smith', 22, 2), (103, 'Ken Yamada', 21, 3), (104, 'Emma Johnson', 23, 4);
Joins are operations that combine rows from two or more tables based on a related column between them. The purpose of joins is to retrieve data from multiple tables in a single result set.
1. Inner Join:
-
Returns only the rows where there is a match in both tables based on the specified condition.
π₯ Syntax SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column; π Example SELECT * FROM students INNER JOIN cities ON students.city_id = cities.city_id;
2. Left Join (or Left Outer Join):
-
Returns all rows from the left table (
students
) and the matched rows from the right table (cities
). If there is no match, NULL values are returned for columns from the right table.π₯ Syntax SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column; π Example SELECT * FROM students LEFT JOIN cities ON students.city_id = cities.city_id;
3. Right Join (or Right Outer Join):
-
Returns all rows from the right table (
cities
) and the matched rows from the left table (students
). If there is no match, NULL values are returned for columns from the left table.π₯ Syntax: SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column; π Example SELECT * FROM students RIGHT JOIN cities ON students.city_id = cities.city_id;
4. Cross Join:
-
Returns the Cartesian product of both tables, meaning every row from the left table is combined with every row from the right table.
π₯ Syntax: SELECT * FROM table1 CROSS JOIN table2; π Example SELECT * FROM students CROSS JOIN cities;
A subquery, also known as an inner query or nested query, is a query within another SQL query. Subqueries are enclosed in parentheses and can be used in various parts of a SQL statement, such as the SELECT, FROM, WHERE, and HAVING clauses.
π₯ Syntax
SELECT column_name
FROM table_name
WHERE
(SELECT column_name FROM table_name)
π Example
SELECT student_name
FROM students
WHERE age > (SELECT AVG(age) FROM students);
The EXISTS operator is used to check if a subquery returns any rows. If the subquery returns at least one row, the condition is considered to be true, and the outer query continues.
π₯ Syntax:
SELECT column_name
FROM table1
WHERE EXISTS
(SELECT column_name FROM table_name2);
π Example:
SELECT name
FROM students
WHERE EXISTS
(SELECT id FROM cities WHERE name = 'London');
The NOT EXISTS operator is the opposite of EXISTS. It is used to check if a subquery returns no rows. If the subquery returns no rows, the condition is considered to be true, and the outer query continues.
π₯ Syntax
SELECT column_name
FROM table1
WHERE NOT EXISTS
(SELECT column_name FROM table_name2);
π Example
SELECT name
FROM students
WHERE NOT EXISTS
(SELECT id FROM cities WHERE name = 'London');