0% found this document useful (0 votes)
43 views22 pages

My SQL

This document provides an overview of key concepts in relational databases and MySQL including: - Databases are used to store, organize, and manipulate data through the use of tables, rows, and columns. Relational databases like MySQL use SQL and non-relational databases store data in other formats like key-value pairs. - MySQL is a relational database management system that uses SQL. It follows a client-server model where clients send requests to servers holding the database. - Data types, queries, commands, constraints and functions are some fundamental elements covered as well as joins, indexes and transactions. - DDL, DML and TCL statements are explained as they relate to defining,

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views22 pages

My SQL

This document provides an overview of key concepts in relational databases and MySQL including: - Databases are used to store, organize, and manipulate data through the use of tables, rows, and columns. Relational databases like MySQL use SQL and non-relational databases store data in other formats like key-value pairs. - MySQL is a relational database management system that uses SQL. It follows a client-server model where clients send requests to servers holding the database. - Data types, queries, commands, constraints and functions are some fundamental elements covered as well as joins, indexes and transactions. - DDL, DML and TCL statements are explained as they relate to defining,

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

INDEX:

Datatypes

Database

Commands

Constraints

Operators

Clauses

Functions (Math, String, Aggregation, Date and Time Normal Function)

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.

We have different kind of databases.

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.

Ex: MySQL, oracle, Microsoft SQL server, postgresql.

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.

Ex: MongoDB, Cassandra

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.

M—length of the number


D---number of decimals.

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)

DATE AND TIME DATA TYPE:

YEAR—‘ 2001’ and range is 2 to 4 digits.

DATE ---- ‘ year – month – date and ‘ and Range is 1000-01-01------9999-12-31.

TIME---- ‘ HH:MM:SS’ and Range is 838:59:59 –838059-59.

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

Each row represents the new data entry.

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.

First we have to Create the Database with create database database_name:

After select the database with use database_name;

Know the Database with use Show databases;

Delete the database then use Drop Database database_name;

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.

Create table new_database_name.table_name

Select * from Old_database_name.table_name;

Change the Database name with rename database old_name to new_name;

We give the permission to particular user to access the Database we use

Grant and revoke commands.

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:

select * from student where condition;

Command: command is a instruction that is used to perform a specific action on the database and table.

Example:

DROP TABLE employees;

Statement: Statement means the completed instructions which contains Queries and commands.

Example:

SELECT id, name, age

FROM employees

WHERE age > 25;

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.

Table consist of 2 things


Name of the table

Column Definitions ---it specifies the column name along with data type and constraints also included.

DDL: DATA DEFINATION LANGUAGE

This command is used to define structure and remove the structure and manage the structure of the database and
table.

CREATE—Create the new database, table, views, indexes, procedures, triggers.

ALTER--modify the structure of 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.

create table student(

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

alter table student

add address varchar(40)

adding the multiple columns

alter table student

add address varchar(40) ,


add age varchar(40) ;

add the column after a desired column then use

alter table student

add number int after age;

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.

alter table student

MODIFY age int(40)

CHANGE: Change command is used to is Changes the column name and datatype name also.

alter table student

CHANGE student_Age int;

Change multiple columns names and datatypes.

alter table practice_table

change new_address address varchar(20) ,change Passout_Year new_passoutyear int;

DROP: Drop command is used to Delete the column definition of the table.

alter table student

DROP age int(40)

RENAME: Rename command is used to Change the name of the table.

alter table student


RENAME new_student;

SHOW:

SHOW Statement which is used display information like database, tables, columns, Index, users, status. Variables
Grants

Display the tables in the database we use

Show tables;

Show tables in database_name;

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.

Eg: drop table Table_name

DML: DATA MANUPULATION LANGUAGE

These commands are used to change stored data into the database and retrieve the data or removes the data from
the database.

SELECT-Retrieve data from the tables.

INSERT-insert new row of data into the tables.


UPDATE-modify the existing data from table

DELETE—delete rows from the table.

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.

SELECT column1, column2, column3

FROM table_name;

SELECT column1, column2

FROM table_name

WHERE condition;

INSERT:

INSERT Statement is used to add data into the table

SINGLE ROW

INSERT INTO People (id, name, occupation, age)

VALUES (101, 'Peter', 'Engineer', 32);

MULTIPLE ROW

INSERT INTO People VALUES

(102, 'Joseph', 'Developer', 30),

(103, 'Mike', 'Leader', 28),

(104, 'Stephen', 'Scientist', 45);

INSERT SOME VALUES IN TABLE

INSERT into people (name, occupation)

values ('stephen', 'scientist'), ('bob', 'actor');


UPDATE:

Update statement which is used to modify the existing table data. We can update the single row or multiple row

Update statement is using the SET and WHERE CLAUSES.

Set clauses used to change the value of specified column

Where clauses specify which column what to change.

UPDATE trainer

SET name = “new name” / / single column update

WHERE name = old name;

UPDATE trainer

SET name = “new name” , age=new age //multiple columns update

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.

Delete from table_name // 2nd row data Deleted from table.

Where id=2;

TCL: TRANSACTION CONTROL LANGUAGE

This command is used to Manage the Transactions in the Database

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,

3. SET autocommit = OFF: //On

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.

DCL:DATA CONTROL LANGUAGE:

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 <permission> on <table name> to <user list>.

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.

Revoke <permission> on <tablename> from <user_list>

Revoke select , insert on std_table from user_1 , user_2;

SESSION CONTROL COMMANDS:

This command is used to manage the MySQL session

USE—select the specific database.

SET—set used to assign the value to variable or column


CONSTRAINTS:

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:

Column level Constraints: These constrains are applied to single columns

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:

CREATE TABLE parent_table (

id INT PRIMARY KEY,

...

);

Foreign key table:

CREATE TABLE child_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.

);

DIFFERENCE BETWEEN THE FOREIGN KEY AND PRIMARY KEY:

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 have only one Primary key

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:

Arithmetic operators are used to perform mathematical operations

 Addition (+): Adds two operands together.

 Subtraction (-): Subtracts one operand from another.

 Multiplication (*): Multiplies two operands together.

 Division (/): Divides one operand by another.

 Modulo (%): Returns the remainder after division.

Logical Operator:

Logical operators are used to combine or modify Boolean expressions.

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

WHERE officer_name = 'Ajeet'

OR officer_name = 'Vimal'

OR officer_name = 'Deepika';

NOT: Not conditions opposite of In condition

IN: It reduces the multiple or condition then directly specifies the all the condition ones.

SELECT *

FROM officers

WHERE officer_name IN ('Ajeet', 'Vimal', 'Deepika');


LIKE:

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.

expression LIKE pattern [ ESCAPE 'escape_character' ]

patten—row value or column name or table name or database name

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.

% pattern—pattern must end then only data is print

Patten % ---pattern must start then data is print.

%pattern%--pattern match if the data is center and first and last

_ (underscore)—it represents a single character.

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

WHERE officer_id BETWEEN 1 AND 3;

NULL:

This condition is used to check if the value is null then data then operation is performed.
SELECT *

FROM officers

WHERE officer_name IS NULL;

NOT NULL:

This condition is used to check if the value is null then data then operation is performed.

SELECT *

FROM officers

WHERE officer_name IS NOT NULL;

Comparison Operator: Comparison operators are used to compare two. They return a Boolean result based on the
comparison.

 Equal to (== or =): Checks if two operands are equal.

 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:

View is a virtual Table it is created from one or more tables.

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..

Create view view_table_name

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:

SELECT: Used Specifies the columns to be retrieved from a table.

FROM: Used to specify the table to retrieve the data.

FILTERING CLAUSES:

WHERE: it is used to filter the row based on the condition

LIMIT: limit clause is used to specify the how many rows want to print.

SELECT name

FROM student

LIMIT 1; /// one row is print

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.

Select distinct names from student_table;

SORTING CLUASES:

ORDER BY: Order clause is used to sort the data in ascending or descending order.

Select * from table_name where name=”abhi” ordered by names ASC || DESC ;

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.

SELECT expression1, expression2, ... expression_n,

aggregate_function (expression)

FROM tables

[WHERE conditions]

GROUP BY expression1, expression2, ... expression_n;

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.

We use can use the aggregate function as a condition.

UNION:

Union clause is used to print the common data between the two tables without duplicate data.

Select coulmn1, coulmn2

From table1, table 2

Where codition.

AGGREAGATE FUNCTIONS:

Aggregate function are used to perform the calculations on the multiple row values and return the a single row value.

We use the aggregate function with select statement mostly

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()

GROUP_CONCAT – It adds the String words.

MATH FUNCTIONS:

Round()—is specifies the number of decimal values after the number --- (4.155 , 2) –4.15

Abs()---Removes the sign

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 AND TIME FUNCTIONS:

NOW() -- Returns the data and time

DATE()

YEAR ()

MOTH()

DAY()

DATE_FORMAT() – Change the data and time.

String Functions:

CONCAT(): Concatenates two or more strings.

SUBSTRING(): Extracts a substring from a string.


REPLACE(): Replaces all occurrences of a substring within a string.

UPPER() / LOWER(): Converts a string to uppercase or lowercase.

LENGTH(): Returns the length of a string.

RIGHT()—these function used to extract a specified number of characters from right side of a string

It takes two parameters string name, number of characters.

RIGHT(string, number_of_characters);

SELECT RIGHT('Hello World', 5);---output is World

LEFT()---- These function is extract the specified number of characters from left side of a string.

LEFT(string, number_of_characters);

SELECT Left('Hello World', 5);---output is Hello

REGULAT EXPRESSION:

Regular expression used to find the pattern.

Patten may be consist of character, word

REGEXP operator is used to perform the pattern matching within queries.

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.

"c" is a literal character that should be matched exactly once.

*(asterisk)------ Match zero or more occurrences of preceding character or group.


pattern "ab*c" would match "ac", "abc", "abbc", "abbbc",

+(plus)---- Match one or more occurrence of group preceding character or group.

pattern "ab+c" would match "abc", "abbc", "abbbc"

? (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.

()(parenthises): Groping patterns together.

Example pattern "(abc)+" would match "abc", "abcabc", "abcabcabc"

^ ---- it matches the Sting or character at beginning

$ ----it Matches the Sting or character at End.

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.

Select id , name age

From table1, table2

Where table1.id=table2.id //not wokrs

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:

Inner join (Equi Join) (Join)


Left Join

Outer Join

Full Join

Self-Join

Cartesian Join

Natural Join

INNER JOIN: (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.

SELECT table1.column1, table2.column2...

FROM table1

INNER JOIN table2

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.

SELECT table1.column1, table2.column2...

FROM table1

LEFT JOIN table2 ON table1.common_field = table2.common_field;

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.

SELECT table1.column1, table2.column2...

FROM table1

RIGHT JOIN table2 ON table1.common_field = table2.common_field;

FULL JOIN:

Full Join combines the both left and right tables and print the matching common data.

SELECT table1.column1, table2.column2

FROM table1

FULL JOIN table2

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.

SELECT TABLE_1. COLUMNS_1

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.

SELECT table1.column1, table2.column2

FROM table1 CROSS JOIN table2 ON table1.common_field = table2.common_field;

You might also like