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

DBNotes Updated

The document discusses MySQL, a relational database management system. It covers basic concepts like what is a database and database management system. It then explains key aspects of MySQL like the different types of databases it supports, SQL queries for creating and interacting with databases and tables, different data types, keys and constraints. The document also provides examples of various SQL queries for performing CRUD operations, joining tables, altering schemas and truncating data.

Uploaded by

kamlesh asolkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

DBNotes Updated

The document discusses MySQL, a relational database management system. It covers basic concepts like what is a database and database management system. It then explains key aspects of MySQL like the different types of databases it supports, SQL queries for creating and interacting with databases and tables, different data types, keys and constraints. The document also provides examples of various SQL queries for performing CRUD operations, joining tables, altering schemas and truncating data.

Uploaded by

kamlesh asolkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

MySQL

Link for the video - https://www.youtube.com/watch?v=hlGoQC332VM

What is Database?
DB is collection of data in a format that can be easily accessed (digital).
A Software application used to manage our DB is called DBMS (database management
system).

We don’t directly access the db it is accessed by a software application called as DBMS.


We use SQL for the DBMS to interact.

Type of DataBase –
1. Relational (RDMS) – Data stored in table and we use sql to interact. Some ex. Of
relational db are – MySQL, ORACLE, Microsoft SQL SERVER, and PostgreSQL.

2. Non-Relational (NoSQL) - Data not stored in table form. Ex mongo DB.

What is SQL?
SQL (Structured Query Language) is programming language use to interact with relational
database.
SEQUEL and SQL both are same.
It is use to perform CRUD operation.
 C - Create
 R – Read
 U – Update
 D – Delete

1
Queries (queries are not case sensitive) -

1. Create Database –

Syntax – CREATE DATABASE db_name;

This query is used to create database.


Database called classroom is created.

2. Show Databases-
Syntax – SHOW DATABASES;

This query is used to get/show all the databases present in MySQL.


Here we run this query to see whether the classroom database is created or not.

3. Drop Database –
Syntax – DROP DATABASE db_name;

2
This query is to drop/delete the existing database present in MySQL.
Here from show database query we have checked whether the database we wanted
To drop is dropped or not.

4. Use Database -
Syntax – USE db_name;

This query is used to work in database that we have selected in MySQL.


Here firstly we have created a database named college to interact with it by USE
query.

5. Create Table –
Syntax – CREATE TABLE table_name (
Column_name1 datatype constraint,
Column_name2 datatype constraint,
Column_name3 datatype constraint
);

3
This query is used to create table under the chosen database.
In this syntax we use data types and constraint to create table.
About constraint we will discuss later in detail.

6. Show fields–
Syntax – SHOW fields FROM table_name;
SHOW columns FROM table_name;

This query is used to see all the field, data types, and the constraints.

7. Insert data in table-

Syntax – INSERT INTO table_name VALUES (column1_v1, column2_v2,


column3_v2), (column1_v1, column2_v2, column3_v3);

4
Here we have inserted to 2 column using this query. Remember Column
constraint containing Primary key should be different to avoid ERROR.

8. Show table –
Syntax –SELECT * FROM table_name;

This query is to get all the row and column from the table.
‘*’ means all in SELECT related queries.

Data Types in MySQL -

Difference in CHAR and VARCHAR –


 CHAR is inefficient beacause it reserve the given length whether it is needed or not
but
 VARCHAR is efficient and preffered because it uses the required length.

Signed and Unsigned Data types –


5
Unsigned data types is used for positive integer and to increase the range.
Signed data types is used to both +ve and –ve integer.
For Ex. TINYINT UNSIGNED (0 TO 255)  the –ve number were occupying the range has
been send to +ve int.
TINYINT (-127 TO 128).

Types of SQL Commands –

1. DDL (Data Definition Language): Create, alter, rename, truncate & drop.
2. DQL (Data Query Language) : Select
3. DML (Data Manipulation Language) : , insert, update & delete
4. DCL (Data Control Language): grant & revoke permission to users
5. TCL (Transaction Control Language): start transaction , commit, rollback

Database Related Queries:

1. If Not Exists-
Syntax – CREATE DATABASE IF NOT EXISTS db_name;

2. If Exists-
Syntax – DROP DATABASE IF EXISTS db_name;

This used to avoid error in MySQL but it shows warning as you can see in above image
This is count as good practice in MySQL.

Practice Question at time-lapse (51:54) Solved ----

6
Keys:

1. Primary keys – It is a column or set of column in a table that identifies each row.(a
unique id). There is only 1 Primary key and it should be NOT null.
2. Foreign keys- A foreign key is a column or set of columns in a table that refers to the
primary key in different table. There can be multiple FKs and can have duplicate and
null values. (iska use samj aur sikh nhi paya)

Constraints:

1. NOT NULL: Columns cannot have a null value.

2. UNIQUE: All Values in column are different.

7
3. PRIMARY KEY: makes a column unique and not null used only for one.

4. FOREIGN KEY: prevent actions that would destroy links between tables.
5. DEFAULT: sets the default value of a column.

6. CHECK: allows to limit the values entered in table.

8
As you can see we use check as a constrainst in age and it act as a limit to enter data in table.
When i try to cross the limit it shows the error and didn’t insert the values.

 SELECT COMMAND :

This command is used to select the data from the table.


Note:We Created a table to perform all the task.

 Here ‘ * ‘(asterisk) in Select command means to select all.


Syntax: SELECT * FROM table_name;

9
 DISTINCT is used to select only the unique ones.
Syntax: SELECT DISTINCT col_name FROM table_name;

 WHERE CLAUSE is used to define some conditions.


Syntax: SELECT col1,col2, from table_name
WHERE conditions;

Basic Operator generally used in WHERE CLAUSE :

10
AND & OR Operator : AND is used when both the condition satisfy. OR is used when any
one of the conditions we want to get satisfy.

BETWEEN,IN &NOT: BETWEEN selects for a given range.IN matches any value in the list
If not return nulls .NOT to negate the given condition.

11
 LIMIT CLAUSE:

Use to limit the value to select.We can use the WHERE condition in it as well.

 ORDER BY CLAUSE:

To sort in ascending(ASC) or Descending(DESC) Order.

 AGGREGATE FUNCTIONS :

To perform a calculation on a set of values, and return a single value.


Some Most Popular Func. Are : COUNT(),MAX(),MIN(),SUM(),AVG().

12
MAX Func. Return max value.

AVG Func. Return avg.

 GROUP By Clause :

It collects data from multiple records and groups that result by one or more
column.Generally we use group by with some aggregation func.

 Having Clause:

Similar to WHERE i.e applies some condition on row. Used when we want to apply
any cond. After grouping.

13
 .General Order :

9. UPDATE QUERY (table related) :

To update the existing row in a table.


Syntax: UPDATE table_name
SET col1=val1, col2=val2
WHERE conditions;

10.DELETE QUERY (table related):

Use to delete the existing row.


Syntax: DELETE FROM table_name
WHERE conditions;

14
As it deleted a row you can see the id 3 is deleted.

Revisiting Foreign key

Basically it link the two different table.

CASCADING IN FOREIGN KEY: Basically means it we update or delete from one table
(parent table) it should reflect in other table (child table) also.

Like you can see we use cascade in FK. Let represent both the tables –

15
Now we delete the deptId which is equal to 1 and that will affect the other table.

Data delete in both the table.

11. ALTER QUERY:

Basically to update the schema and design of the existing table.


Feature of ALTER Query: ADD Column, DROP Column, RENAME Table,
MODIFY Column.

 Add Column :

Syntax: ALTER TABLE table_name


ADD COLUMN column_name dataType constraints;

16
Here we have added an extra Column for the table called stu_detail.

 Drop Column:

Syntax: ATLER TABLE table_name


DROP column_name;

We delete the Column Called city.

 Rename Table :

17
Basically renamed the table.

Syntax: ATLER TABLE table_name


RENAME new_table_name;

Before renaming the table name was stu_detail.

After running the Query –

 Modify Column :

Syntax: ATLER TABLE table_name


MODIFY column_name new_DataType new_Constrainst;

18
12.TRUNCATE QUERY(table related):

Truncate query basically delete all the data present in the table.
Diff. between Drop and truncate Query is Drop deletes the table but in truncate
the table exist but all the value flushes out.

The values of the table called student deleted. But the table still exists.

19
Joins in SQL

Joins is used to combine rows from two or more tables, based on a related column between
them.

Venn diagram:

 Inner Join: Return records that have matching value in both tables.

Syntax: SELECT column(s)


FROM tableA
INNER JOIN tableB
ON tableA.Col_name=tableB.Col_name;

Firstly We Created a table called student.

Now, we will create a second table called courses have a common column student_id.

20
Now, we will perform Inner Join with this tables.

The result table is combined to two table have common student_id.

Alias is used for alternate name in MySQL. Use in place where we have large table name
To shorten its name. Remember both table names are correct you can use any one of them.

 Left Join: return all records from the left table, and the matches records from the
right table.

Syntax: SELECT column(s)


FROM tableA
LEFT JOIN tableB
ON tableA.Col_name=tableB.Col_name;

21
Just Remember the Sequence of table in this join method because the data of tableA
with appear fully with some common/overlap data of tableB.

We have created the table you have seen in the above join method .So, we will
directly perform the query.
co

The result of tables is shown above you can see the table students represent full data
but in courses the overlapped value appear and in case of absent value printed as
NULL.

 Right Join: returns all records from the right table, and the matched records from the
left table.

Syntax: SELECT column(s)


FROM tableA
RIGHT JOIN tableB
ON tableA.Col_name=tableB.Col_name;

The resulted table is shown above we can see that the course/right side table appear
represent full data and in student table the overlapped data is printed and apart from that
prints NULL.

22
 Full Join: returns all records when there is a match in either left or right table.

Syntax:
SELECT * FROM tableA
LEFT JOIN tableB
LEFT JOIN
ON tableA.Col_name=tableB.Col_name
UNION
UNION
RIGHT JOIN
SELECT * FROM tableA
RIGHT JOIN tableB
ON tableA.Col_name=tableB.Col_name

MySQL don’t have full join so we perform using union. Oracle mei hota hai.

The resulted table Shown above.

Self-Join meko sammj nhi aaya but it exists that is why I mentioned here.

 Union: it is used to combine the result-set of two or more SELECT statements


Given UNIQUE records.

To use it:
 Every SELECT should have same no. of columns.
 Columns must have similar data types.
 Columns in every SELECT should be in same order.

23
Syntax:
SELECT column(s) FROM tableA
UNION
SELECT column(s) FROM tableB;

T
The result print all the data from both the table.

SQL Sub Queries

A Sub query is a query within another SQL query.

SELECT
Query
FROM
WHERE (Sub Query) Sub Query

24
Let’s perform a task to know better about sub query.
Like in a classroom we have to give the name of student who scored more than avg.. . So our
query will be:

SELECT AVG (marks) FROM student;


SELECT name, marks
FROM student
WHERE marks > 87.6667; (this value is the avg. value written here manually)

Suppose a condt. Arrive where we the student score got a mistaken marks given by the
teacher then the overall avg. will be disturb. So, we have to create a dynamic process.
That firstly takeout the avg. of class then perform the selection.

SELECT name, marks


FROM student
WHERE marks > (SELECT AVG (marks) FROM students);

MySQL Views

Views can be basically understand as show up data. For ex. There are multiple data in
database but we show the only data that is required.

25
Syntax: CREATE VIEW view1
SELECT column(s) FROM table_name;

SELECT * FROM view1;

View is the virtual form of table. But table and its data operations are real.

This is not a table Just a view.

THANK YOU

26

You might also like