My SQL
My SQL
Datatypes
Database
Commands
Constraints
Operators
Clauses
Regular Expression
Joins
Database:
Data base is used to store the data, organize the data, retrieve, and manipulate the data.
Database is Managed by Database management system which provides the tools for creating the database, table and
perform the operations on the table.
The Main use of DBMS is used to handles the data storage, security.
Relational database:
These databases store the data in the table and it use the structured query language for creating table, manipulating
the data and performing the operations on the table.
NoSQL Database:
These databases stored the data in not in the form of tables they are stored like key-value pair, json format, xml
format.
MySQL:
MySQL is a relational database management system which uses the structured query language for performing the
operations on the data.
MySQL work on the client-side architecture and when the client sends the request to see his data and the request goes
to the server then server is having the database so that database is giving the response to in the form of data.
Datatypes:
Datatypes specify what kind of data is going to store like integer, float, Boolean, String.
INTEGER:
TINYINT—(1 byte )
SMALLINT—(2 byte)
MEDIUMINT—(3 bytes)
INT – (4 bytes_
BIGINT — (8 bytes)
Float and double, decimal values cannot be unsigned i.e., no negative numbers.
FLOAT(M,D) or Float()—(2 bytes) --- we can specify the precision (4,2) it take only 4 values then try to give more
error then give 3 values then it take 44.40 –0 by default is added.
DOUBLE(M,D)—(8 bytes)
BOOLEAN—(true or false or 0 or 1) – if we insert true or false then it stores 1 0r 0 values in the table.
STRING:
CHAR(SIZE)
VARCHAR(SIZE)
DATETIME –Combination of Data and time and Range will be same for both.
Database:
Mysql is the case-sensitive that means you can write uppercase or lowercase it works.
Database is uses tables to store the data and table consist of row and columns
Column is representing the what kind of data specific data should enter.
All the Tables are linked together though relationship with the help of these we can access the data from the different
table.
Know the database is exited or not we use show databases like ‘database_name’ if it is return the database names if
the same is there then database is exited.
Copy one database table into another database .
Create database new_database_name; ---first create new database and use the database after create the tables with
exiting database table.
Query: Queries means the instructions that are used to retrieve the data from a database. They are used to fetch
information from one or more tables based on the specified criteria.
Example:
Command: command is a instruction that is used to perform a specific action on the database and table.
Example:
Statement: Statement means the completed instructions which contains Queries and commands.
Example:
FROM employees
COMMANDS:
Table:
Table is used to organize the data in the form of row and columns and with the help of table we can store the data and
display the data.
Column Definitions ---it specifies the column name along with data type and constraints also included.
This command is used to define structure and remove the structure and manage the structure of the database and
table.
DROP—Deleted the database, table, views, indexes, procedures and removes the structure completely
TRUNCATE----Removes the all data from the table without removing the structure
CREATE:
Create command which is used to create the database, table, view, index, procedure, function,triggers.
rollno int,
name varchar(30),
college varchar(40)
);
ALTER:
Alter statement which is used to add or remove or modify or Rename the table columns
ADD: add command is used the new column definition into the table
Not possible to add the element before a desired column. To achieve these create a new table..
MODIFY: Modify command is used to changes the column datatype or datatype size and not changes the column
name.
CHANGE: Change command is used to is Changes the column name and datatype name also.
DROP: Drop command is used to Delete the column definition of the table.
SHOW:
SHOW Statement which is used display information like database, tables, columns, Index, users, status. Variables
Grants
Show tables;
Show tables from database_name; /// both get same result get. And we can know the different database tables also.
Find the table in the full of tables then we use show tables like ‘student’;
Display the columns in the table we use show columns from table_name;
TRUNCATE:
Truncate statement which is used to removes the all the rows data from the table and it is maintains the table
structure that means it not delete the table structure.
Truncate statement is not work the tables with having foreign key as column constraint so until you not remove that
column table with drop or disable the constraint.
DROP:
Drop statement which is used to delete the current table, database , Index , Triggers, Function, Procedures ,
Events and it removes the complete table from the database. Once the table is delete we cannot recover the data after
deleting.
These commands are used to change stored data into the database and retrieve the data or removes the data from
the database.
SELECT:
These statement which is used to retrieve data from one or more tables in the database.
We can use the where clause to specify what kind of specific column to be retrieve.
FROM table_name;
FROM table_name
WHERE condition;
INSERT:
SINGLE ROW
MULTIPLE ROW
Update statement which is used to modify the existing table data. We can update the single row or multiple row
UPDATE trainer
UPDATE trainer
WHERE id = 33;
DELETE:
Delete statement which is used to removes the row data from the table. We can delete the data from single or more
row , Once delete the date we cannot recover.
Where id=2;
Transaction in MySQL is a sequential group of statements, queries, or operations such as select, insert, update or
delete to perform as a one single work unit .
MySQL Automatically commit the every Transaction and it saves the transaction permanently.
With the help of set auto commit statement, we disable or enable auto commit transaction.
1. SET autocommit = 0; // off // 1 //on
2. OR,
We Manually use the COMMIT command to save the current Transaction and store in the database.
ROLLBACK command is used to undo the transaction and removes the operations applies on the table.
SAVE POINT command is used to set the point when the rollback function is undoing the transaction up to the point
after the save point the transaction rollback cannot undo the Transaction.
Once Transaction is commit then we cannot rollback to the previous Transaction. Because the Transaction is already
saved in the database.
Tables are stored in the Database and Database is stored in the MySQL server
MySQL server is database management system that provides the things to storing and manging, accessing the
database.
These commands are used to control the access to the database and table. Tha means We provides access to the
database, table for some people these useful in these situations’
GRANT –These commands is used to Gives the Access and Permission to the Database
Grant select, insert on std_table to user1, user2; //Only these two people can perform the select , insert operation on
the table std.
REVOKE--- It used to Cancel or remove the Access and permission to the database and table.
Constraints are used to specify the condition or Rule then that condition is allowing the data or restrict the data to store
in the table.
With the help of constraints specifies that what kind of data should stored in the table and unnecessary is restricted.
Data is not meet the condition then data will not be stored in stored the generates an error.
Types of Constraints:
Table level Constrains: These constraints are applied to entire table then entire columns follow the conditions.
NOT NULL: These constrains specifies the condition that column cannot stores the NULL values for every row.
Every entered row value must be needed.
UNIQUE: These constraints specify the condition that values stored in the column must be UNIQUE. So use is it
prevent the values not duplicated.
AUTO_INCREMENT: These constrains is used with integer column , it automatically generates the unique
increment values for every row data is entered in the table. It must need the PRIMARY KEY OR UNIQUE because
those constrains are generates the unique value every time new row data is entered.
DEFUALT: these constrains is used to stores provides the default value to the column if the no value is entered for
that particular column value then these default value is automatically inserted into the table.
CHECK: These constrains specifies the condition for column it is uses is Before storing an value in column that
condition must be satisfied then only the data is stored condition is not satisfied then it throw an error. Like condition
is not meet.
PRIMARY KEY: These contains specifies the condition that column can stores the accept the UNIQUE VALUES
AND NOT NULL VALUES.
FOREIGN KEY: This foreign key is used to establish the link between two tables with the help of primary key
When we connect the foreign key with primary key then we store only the primary key values in the foreign key table
when you try to include the new values then in the foreign key it throws an error .
Primary Table:
...
);
id INT,
parent_id INT,
...
FOREIGN KEY (parent_id) REFERENCES parent_table(id) // Link the two tables with the foreign key based on
the primary key we link the that primary key with present table id.
);
Primary key is set for the column in the table that specify the condition that it accept only the unique values In the
columns table.
Foreign key is set of column that it establish a link between the tow tables.
Table can have the multiple foreign keys used to link the multiple tables in the single table.
Primary key cannot allow the duplicates values into the columns in table
Foreign key accepts the duplicate values into the columns in the table.
OPERATORS:
Arithmetic operators
Logical operator
Comparison operators
Arithmetic Operator:
Logical Operator:
AND: It is specifying the two or more conditions and all conditions are must satisfies or true then that particular data
is retrieved or stored.
OR: It specifies the two or more conditions then at least one condition is satisfying and true then data is retrieved.
SELECT *
FROM officers
OR officer_name = 'Vimal'
OR officer_name = 'Deepika';
IN: It reduces the multiple or condition then directly specifies the all the condition ones.
SELECT *
FROM officers
LIKE condition is used to find the data is present in the table or database. And it is used to perform the pattern
matching with wildcard character.
With the help of like condition we find the data from the table.
escape character—if we don’t specify the any escape character / is default escape character. we have % and _
% (percent)--It represent the sequence of character –some pattern is match with the table data then value is prints.
select emp name from emp where emp_name like "a_hi"; // only single character not need to mention it
automatically
BETWEEN:
Between specifies the condition that data retrieve between the given range.
SELECT *
FROM officers
NULL:
This condition is used to check if the value is null then data then operation is performed.
SELECT *
FROM officers
NOT NULL:
This condition is used to check if the value is null then data then operation is performed.
SELECT *
FROM officers
Comparison Operator: Comparison operators are used to compare two. They return a Boolean result based on the
comparison.
Not equal to (!= or <>): Checks if two operands are not equal.
Greater than (>): Checks if the left operand is greater than the right operand.
Less than (<): Checks if the left operand is less than the right operand.
Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right operand.
Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.
VIEW:
The main advantage of view we can able to create the table on for the specified columns for the table like We have the
table contains 5 columns so I want to create the new table only for 2 columns then that situations view is used.
The Main advantage of the view is any updates on rows in the table then automatically Updated in the View Table.
What ever the changes are done in the view be automatically updated on the original table
We can use all the statement with view also like alter, modify, insert, delete etc..
As select columns_name_specify
From parent_table_name
Where condition_optional // used when I want to store the particular columns data with matched data.
CLAUSE:
Clause is a specific part of SQL statement and Clauses are used to provides the specific instruction of condition on the
columns of the table.
Clause is used to Filtering data, sorting data, joining table, group the data, retrieve the data
SELECT CLUASES:
FILTERING CLAUSES:
LIMIT: limit clause is used to specify the how many rows want to print.
SELECT name
FROM student
DISTINCT: It is used to display only the unique data from the table and not display the duplicate values. It is used
only with the SELECT statement.
SORTING CLUASES:
ORDER BY: Order clause is used to sort the data in ascending or descending order.
GROUPING BY: This clause is used to collect the data from multiple rows and group the multiple rows into one
single column or more columns.
We can use the aggregate function like count, sum, min, max, avg.
Example: where data enter in the database is different so we need to combine all the same kind of data and show their
values. It shows only unique data in the table not repeat the names.
aggregate_function (expression)
FROM tables
[WHERE conditions]
HAVING:
group by clauses produces the result data by combining the multiple row into single column after With the help of
having clause we Filter the result data based on conditions.
UNION:
Union clause is used to print the common data between the two tables without duplicate data.
Where codition.
AGGREAGATE FUNCTIONS:
Aggregate function are used to perform the calculations on the multiple row values and return the a single row value.
Example: know the average salary of employee, Total number of employees in the company, min salary from
company.
All these functions perform the operations and return the value as result.
COUNT() –It Return the number of row with row contains null values also the row count is print.
SUM()
AVG()
MIN()
MAX()
MATH FUNCTIONS:
Round()—is specifies the number of decimal values after the number --- (4.155 , 2) –4.15
Ceil()—It round the number up to nearest number greater number or equal 2.4 -- 3
Floor() – it round the number down to neat number lesser than or equal 2.4 – 2
DATE()
YEAR ()
MOTH()
DAY()
String Functions:
RIGHT()—these function used to extract a specified number of characters from right side of a string
RIGHT(string, number_of_characters);
LEFT()---- These function is extract the specified number of characters from left side of a string.
LEFT(string, number_of_characters);
REGULAT EXPRESSION:
Regexp operator which is compares a column values with regular expression pattern and return the matching row.
regexp support the various meta character and meta character are used to define that pattern
meta characters means they are special characters and which is used to match the specific type of character
.(dot)------matches any single character in the present string and not match the new line character----eg:”a.b” a and
b word are print like axb , aaab, a534534b, a\nb---not match bcz newline character is there
Preceding means character or group of character that appears before the meta character. It specifies what character or
String be matched or repeated.
ab*c pattern
a" is the preceding character. It is a literal character that should be matched exactly once.
"b" is the preceding character followed by the * meta character. It means "b" can occur zero or more times.
? (question mark): Matches zero or one occurrence of the preceding character or group.
For example, the pattern "colou?r" would match both "color" and "colour". U there or not it return the word.
[](Square brackets): Defines the character , it matching any single character within the bracket then String or
character is prints.
Example pattern "[^0-9]" would match any character that is not a digit.
JOINS CLAUSE:
Joins are used to combine the two or more tables with the help of common fields and with help of joining we can
retrieve data from multiple tables
Join the tables with select statement without joining and with help of operator we join the tables. < , > = not null
between , = , like , not.
EXAMPLE:
Take an example like software company it maintains the database to store the information so they created the different
tables to store different kind of information such as employee information in employee table, department info in
department table, project, managers so after created individually when ever we need to combine the tables so with the
help of join we combines the tables.
Types of Joins:
Outer Join
Full Join
Self-Join
Cartesian Join
Natural Join
The most used join is inner join because It returns the records when there is common data between both tables based
on the condition.
EXAMPLE: we need to fetch the employee name and department so with the help of inner join we get the result.
FROM table1
ON table1.common_field = table2.common_field;
LEFT JOIN:
Left join return all records from the left table and even if there is no match in the right table.
Example: These joins used to fetch the all the employee information along with their project and not depending upon
the condition even though condition is failed it still fetch the values it returns the null value.
Left join=inner join (common records) + addition records in the left table.
FROM table1
RIGHT JOIN:
Right join returns all rows from the right table and even if there is no match in the left table.
Right join=inner join (common records) + addition records in the Right table.
FROM table1
FULL JOIN:
Full Join combines the both left and right tables and print the matching common data.
FROM table1
ON table1.common_field = table2.common_field
SELF JOIN:
Self-join is used to join the a table itself and is used to Retrieve data from a single table based on condition.
FROM TABLE_1
JOIN TABLE_1
ON TABLE1.COLUMN1=TABLE2.COLUMNS1;
CROSS JOIN:
Cross join combines where each row from one table and each row from another table without any condition. It returns
the all-combined data.