0% found this document useful (0 votes)
7 views25 pages

Database Management System

The document provides an overview of Database Management Systems (DBMS), focusing on relational databases (RDBMS) and SQL commands for managing data. It covers key concepts such as records, fields, primary keys, foreign keys, and various SQL commands for creating, modifying, and querying databases and tables. Additionally, it explains data types, constraints, and how to use SQL commands to manipulate data effectively.

Uploaded by

bekrmsharma
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)
7 views25 pages

Database Management System

The document provides an overview of Database Management Systems (DBMS), focusing on relational databases (RDBMS) and SQL commands for managing data. It covers key concepts such as records, fields, primary keys, foreign keys, and various SQL commands for creating, modifying, and querying databases and tables. Additionally, it explains data types, constraints, and how to use SQL commands to manipulate data effectively.

Uploaded by

bekrmsharma
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/ 25

DATABASE MANAGEMENT SYSTEM

A group of programme forms a system and a system that is used to


manage files in database is DBMS.It is not possible to create a new
DBMS for Each Project rather we use the pre-build DBMS.

RDBMS is a database model where Data are Logically organized in table.


Physically they are organized in files. SQL is a language used to interact
with RDBMS software.

Record
A full row is called record, eg: BIKRAM 12 BAGLUNG SOS is a record in
table for Name Class District School. A record hold heterogeneous data,
it holds complete information about a person or item.

Field
The individual data entered in record is called field,eg;Bikram is a field or
12 is a field.It is one cell data of a row or record. A collection of Field
forms a record and A collection of records forms table.

PRIMARY KEY
Primary key is used to identify a record in a table.
In a data of students of table there may be many students of same name
so we cannot differentiate them on the basis of Name,if they are from
same family we cannot differentiate on the basis of their phone number,
May be we can differentiate on the basis of their roll no or email id.
So primary key is different for different data or different table.
Primary key cannot be Null and it cannot be same value on two different
records.
Another eg for primary key is account no in bank account, even though.
Account name can be same,date of joining is same account no is always
unique.

FOREIGN KEY
It is a column in RDBMS that creates links between tables. Generally
when a primary key of a table is used in another table it creates links
between tables and the primary key of 1st table on 2nd table is called
foreign key.
Eg: For a customer detail table in bank account no is primary key, but in
a transition table primary key is transition id but we use account no to
Know where is money transferred or from which account no transition is
made so account no acts as foreign key.Foreign key can be repeated as a
single account no can have multiple transition.
Foreign key helps to reduce redundancy as we don’t have to put all
details about customer instead we can put account no.

TYPES OF SQL COMMANDS


1. Data definition language
2. Data Query language
3. Data Manipulation language
4. Data control language
And Many More.
The DBMS software like MYSQL is called Sql server.
MySQL workbench helps to interact with sql server and send request
according to the code written by us.We can send request to server
through command line, and through programming language like php or
python. MySQL workbench,php or python and cmd line are called client
as they send request to server.

SQL Server can handle multiple and database at a time.


When we visit different website we get our data because of our login id
pass that we put, due to which only our data will be shown to us.
To login to mysql via command line do
mysql -u root -p
Root is user name

“status” command after login helps to know about database


Shows result like below
Connection id: 18
Current database: (vacant due to no selection)
Current user: root@localhost
SSL: Cipher in use is TLS_AES_256_GCM_SHA384
Using delimiter: ;
Server version: 8.0.39 MySQL Community Server - GPL
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: utf8mb4
“show databases;” command shows all database[see command
carefully]
Now it shows multiple databases to use one database apply use
command
“use database_name”
IF ANY ERROR OCCUR STUCK ON ERROR DO “\c”

Once u select a db it cannot be unselected it is selected forever,but can


be changed or switch to other. Only way to unselect is to delete
database, and current database status will be empty.
You cannot use more that one db at a time.

So apply “use db_name;” command to change db and go through


“status” command to see if db is changed.
Once you have selected a database, now Use “show tables;”
[see syntax carefully] .
After a list of tables are shown,
Use “describe table_name;” command to see all col,rows in table.

To see particular column from table do


select col_name from table_name;
If “col_name” is key word then it should be put “inside inverted comma”

In order:

Status
Show databases;
Use db_name;
Show tables;
Describe table_name;
Select col_name from table_name;

Now use following command to create and update databases and also
use above command to see if happened or not
eg create database db_name; and do show databases;
Note: Even if u create a database u are still in previous database so after
creating database u have to use “use” command to use that database to
do something onto it.

CREATE DATABASE

CREATE DATABSE DB_NAME;


EG; CREATE DATABASE SCHOOL (CREATES A DATABASE NAMED
SCHOOL)

If we want to only create a database if it doesn’t exist.


SYNTAX:
CREATE DATABASE IF NOT EXISTS DB_NAME;

DROP DATABASE

DROP DATABASE DB_NAME;


EG; DROP DATABASE SCHOOL(Deletes database school);

DROP DATABASE IF EXISTS DB_NAME;


We use this command to avoid error.

If you drop selected db and use status command,It will show current
database empty.

CREATE TABLE
CREATE TABLE TABLE_NAME
(
COL1_NAME DTYPE CONSTRAINT,
COL2_NAME DTYPE CONSTRAINT,
COL3_NAME DTYPE CONSTRAINT,
);
Eg:
CREATE TABLE EMPLOYE ( EID INT, NAME VARCHAR(255), AGE INT);
ALSO WE CAN DO AS :
CREATE TABLE DB_NAME.TABLE_NAME(COL1_NAME DTYPE
CONSTRAIN,
);
DELETE TABLE:
DROP TABLE TABLE_NAME;
EG: DROP TABLE EMPLOYE; (DELETES TABLE NAMED EMPLOYE)

SIZE:MAXIMUM NO OF DIGITS
UNDERSTANDING DATATYPES:

|| INT(size) or integer(size) : To handle normal digits.

|| Bigint(size):to store large value

And there are smallint(size),mediumint(size) respectively for respective


ranges of value, only difference is memory occupied.

|| UNSIGNED INT is a variant of the INT data type that only allows non-
negative numbers. UNSIGNED Key is used as constrain.

CREATE TABLE my_table ( id INT UNSIGNED, value INT UNSIGNED );

|| BOOL or BOOLEAN: It only excepts 0 (meaning false) or non


zero(meaning true).

|| FLOAT(size): SIZE:0 TO 24 FLOAT, SIZE:25 TO 54 DOUBLE.


There is FLOAT(A,B) where A is no of digits, B is no of digits after
decimal.

|| CHAR(size) : String of fixed size if size is 10 you have to write 10 digit


string.
|| VARCHAR(size):Variable char, You can enter any no of digits within
size.

There are text, tinytext, mediumtext and longtext for respective


purpose.

|| ENUM(val1,val2,val3,….): You can only enter values among va1,val2…


Respectively.
EG: CREATE TABLE my_table (
status ENUM('active', 'inactive', 'pending') NOT NULL
);
|| DATE : yyyy-mm-dd
|| DATE TIME: yyyy-mm-dd hh:mm:ss
|| YEAR: yyyy (4 digits)
CONSTRAINTS:

NOT NULL:
By default a column can hold null value, not null constrain enforces a
column to not accept null value. So adding null value is not possible
when not null constraint is applied.
It can be applied while creating and through alter command.
But while applying not null through you must check the column where
not null constrain is applied don't contain null value.
SYNTAX:
CREATE TABLE TABLE_NAME(
COL1_NAME DATATYPE CONSTRAINT CONSTRAINT_NAME NOT NULL,
COL2_NAME DATATYPE CONSTRAINT CONSTRAINT_NAME NOT NULL

)
EG:
CREATE TABLE STUDENTS(
STD_ID INT CONSTRAINT CNAME NOT NULL,
STD_NAME VARCHAR CONSTRAINT CON_NAME NOT NULL);

Giving Name to constrain is Optional.so


SYNTAX:
CREATE TABLE TABLE_NAME(
COL1_NAME DATATYPE CONSTRAINT,
COL2_NAME DATATYPE CONSTRAINT

);
EG:
CREATE TABLE STUDENTS(
STD_ID INT NOT NULL,
STD_NAME VARCHAR NOT NULL);

ALTER TABLE FOT NOT NULL:


ALTER TABLE TABLE_NAME
MODIFY COLUMN COL_NAME DATATYPE CONSTRAINT;
EG:
ALTER TABLE STUDENTS
MODIFY COLUMN STD_ID INT NOT NULL;
TO REMOVE NOT NULL CONSTRAINT:
ALTER TABLE TABLE_NAME
MODIFY COMLUMN COL_NAME DATATYPE;

UNIQUE CONSTRAINT: It ensures that the data entered in a field are


unique or not repeated.
It can be put while creating table same as not null difference is replace
not null by UNIQUE. But there is alternative way.
CREATE TABLE TABLE_NAME(
COL1_NAME DATATYPE,
COL2_NAME DATATYPE,
….……………………………….
CONSTRAINT CONTRAINT_NAME UNIQUE(COL1_NAME,COL2_NAME,
….));

OR UNIQUE(COL1_NAME,COL2_NAME,…));

CONSTRAINT NAMING Is optional.

ADDING UNIQUE CONSTRAINT IN PRE EXISTING TABLE:

ALTER TABLE TABLE_NAME


ADD UNIQUE(COL_NAMES);
OR
ALTER TABLE TABLE_NAME
ADD CONSTRAINT CONSTRAINT_NAME UNIQUE(COL_NAMES);

TO DELETE CONSTRAIN
ALTER TABLE TABLE_NAME
DROP INDEX CONTRAINT_NAME

NOTE:After applying unique constrain you can have multiple null value.
PRIMARY KEY:
It uniquely identifies each record in a table, field which is primary key
cannot contain null and must contain unique value. A table can have
only one primary key.But a primary key may be made up of combination
of more than one column.
Applying primary key on a table.
CREATE TABLE STUDENTS(
STD_ID VARCHAR(30) PRIMARY KEY,
NAME VARCHAR(30) NOT NULL,
CLASS INT,
ROLL_NO INT);

OR
CREATE TABLE STUDENTS(
STD_ID VARCHAR(30),
NAME VARCHAR(30) NOT NULL,
ROLL_NO INT,
PRIMARY KEY(STD_ID));

TO ADD PRIMARY KEY ON PRE EXISTING TABLE

ALTER TABLE TABLE_NAME


ADD CONSTRAINT CONS_NAME PRIMARY KEY(COL_NAME);
OR
ALTER TABLE TABLE_NAME
ADD PRIMARY KEY(COL_NAME);

TO REMOVE PRIMARY KEY


ALTER TABLE TABLE_NAME
DROP PRIMARY KEY;

FOREIGN KEY:(Already explained on 2nd page)


The table in which foreign key is primary key is called parent table, and
where it is foreign key is called child table.
SYNTAX:
CREATE TABLE TABLE_NAME(
COL1_NAME DTYPE CONSTRAIN,
….…………………………………………….
PRIMARY KEY (COL_NAME), [primary key for child table]
FOREIGN KEY (COL_NAME IN THIS TABLE)
REFRENCES PARENT_TABLE_NAME (COL_NAME IN PARENT TABLE )

);

Note: The foreign key must be primary key on parent table.

EG:STUDENTS TABLE
LETS HAVE A TABLE WITH :
+--------+---------+-------+---------+
| STD_ID | NAME | CLASS | ROLL_NO |
+--------+---------+-------+---------+
| ST1121 | David | 10 | NULL |
| ST1234 | Alice | 10 | 1|
| ST3141 | Eve | 11 | 4|
| ST5678 | Bob | 11 | 2|
| ST9101 | Charlie | 12 | 3|
+--------+---------+-------+---------+
Where STD_ID is primary key.
Now lets say a school did a programme those students also participated
and some data of programme is kept in table program.

create table program(


PROJECT_ID INT NOT NULL,
CONTRIBUTOR VARCHAR(30),
EXACT_TIME TIME,
PRIMARY KEY(PROJECT_ID),
FOREIGN KEY(CONTRIBUTOR) REFERENCES STUDENTS(STD_ID));

STD_ID is primary key of table students which acts as foreign key here.
ENTERING RANDOM VALUE:
INSERT INTO program (PROJECT_ID, CONTRIBUTOR, EXACT_TIME)
VALUES (1, 'ST1121', '14:30:00');

Foreign key can be applied as:


CONSTRAINT CONS_NAME FOREIGN KEY(CONTRIBUTOR) REFERENCES
STUDENTS(STD_ID));
Foreign key accepts null value.
You can delete a record from students[parent table] only if that row
doesn’t have foreign key on child table[program table].

ALTER TABLE Method to add FOREIGN KEY


ALTER TABLE CHILD_TABLE_NAME
ADD CONSTRAIN CONS_NAME FOREIGN KEY (COL_NAME)
REFRENCES PARENT_TABLE_NAME (COL_NAME IN PARENT TABLE )

To Remove FOREIGN KEY


ALTER TABLE CHILD_TABLE_NAME
DROP FOREIGN KEY CONS_NAME

CHECK CONSTRAINT:
It is use to limit values within certain range while entering data onto the
column.
SYNTAX:
CREATE TABLE TABLE_NAME(
COL1_NAME DTYPE,
….…………………………
CONSTRAINT C_NAME CHECK (condition) // check(condition)
);

Eg:
create table emp(
name varchar(30) not null,
age int,
roll_no int,
constraint cons check(age>20)); [But age can be Null]
ALTER TABLE TABLE_NAME
ADD CONSTRAINT CONS_NAME CHECK(CONDITION);

ALTER TABLE TABLE_NAME


DROP CHECK CONS_NAME;

DEFAULT:
It provides a default value for a column when no value is specified during
an insert operation.In absence of default value null value is obtained.

CREATE TABE TABLE_NAME(


COL_NAME DTYPE DEFAULT DEFAULT_VALUE
….……………………………………..
);

ALTER TABLE TABLE_NAME


ALTER COLUMN_NAME SET DEFALUT DEFAULT_VALUE;

ALTER TABLE TABLE_NAME


ALTER COLUMN_NAME DROP DEFAULT;

Note: If you have Deleted Your Custom made default value, then there is
no default value. By Default Null is a Default value if u delete Your
Custom made default value Now Null won’t be default value.

These were all major constraints used in sql.


ALTER TABLE COMMAND:
Used to add, delete, or modify columns and constraints.

TO add new column in table.

ALTER TABLE table_name


ADD column_name datatype;

To change dtype of column.

ALTER TABLE table_name


MODIFY column_name new_datatype;

To change Name of column


ALTER TABLE table_name
RENAME COLUMN OLD_NAME TO NEW_NAME;

To delete column

ALTER TABLE table_name


DROP column_name;

To change position of column
To place col1 after col2

ALTER TABLE table_name


Modify col1_name dtype after col2_name;

To put a col in first position


ALTER TABLE table_name
Modify col1_name dtype FIRST;

“ SQL Command under quotation means unnecessary to study.”


INSERT INTO COMMAND:
To add new row

INSERT INTO table_name (column1, column2, column3, ...)


VALUES
(value1a, value2a, value3a, ...),
(value1b, value2b, value3b, ...),
(value1c, value2c, value3c, ...);

SELECT COMMAND:

To select data according to requirement.


SELECT col2,col1,… FROM table_name;[First col2 then col1 will appear]

To select from all column


SELECT * FROM table_name;

ROW SELECTION ACCORDING TO CONDITION


SELECT * FROM table_name
WHERE condition;

We can use “and”,”or” in condition.

LIKE operator in SQL

1. Using % Wildcard
% means any no of any type of character so mysql will try infinite
combinations [4 letter word, 5 letter word ] and show results.

Example1: Find all employees whose names start with "A"[case


sensitive]
SELECT * FROM employees WHERE name LIKE 'A%';

Example2: Find all employees whose names ends with "er"


SELECT * FROM employees WHERE name LIKE '%er';[case sensitive]
Example3: Find all customers whose names contain "an":
SELECT * FROM customers WHERE name LIKE '%an%';[case sensitive]
Eg:Brian,Daniel.

2. Using _ Wildcard
_ means a single character

Example: Find all employees whose names have exactly 4 characters and
start with "J":
SELECT *FROM employees Where name LIKE 'J___'; [4 “_” ]

Example: Find all employees whose names have "a" as the second
character:
SELECT *FROM products WHERE product_name LIKE '_a%';
Example: Find all employees whose names have 5 letters
SELECT * FROM products WHERE product_name like “_____”;

USE OF IN OPERATOR

SELECT column1, column2, ... FROM table_name WHERE column_name


IN (value1, value2, ...);
Eg:
SELECT * FROM employee WHERE name IN (“rajesh”,”suman”,”raj”);
[case insensitive]
If any of 3 name is present in table it will show data.

Suppose a table people:


Name Age Email City
Rakesh Kumar 25 [email protected] New York

Rakesh Sharma 30 [email protected] Los Angeles

Rakesh Kumar 28 [email protected] Chicago

Rakesh Gupta 35 [email protected] Houston


Rakesh Mehta 22 [email protected] Phoenix

Rakesh Kumar 40 [email protected] Philadelphia

SELECT DISTINCT name from people [prints unique value]

It will remove a Rakesh Kumar don’t know which.

SELECT DISTINCT name,age from people

It will print all rakesh because it will look for combination of name,age
that are same since there is no same combination of name and age it will
print all rakesh.

UPDATE COMMAND:
It is used to update records in a table.

UPDATE TABLE_NAME
SET COL1=VAL1,COL2=VAL2,……….
WHERE CONDITION;
Update command without where will change all the records.
To compare NULL value don’t use
Where price=NULL [wrong]
Instead do
Where price is NULL [correct]

DELETE COMMAND:
We cannot delete a field but can delete a record.

DELETE FROM table_name


WHERE condition;

ORDER BY:
To sort data.
Null is the smallest value.

SELECT * FROM table_name ORDER BY col_name ASC;


If no key after col_name it will understand ascending order.

SELECT * FROM table_name ORDER BY col_name DESC;


Use DESC key to print in descending order.

SORTING MULTIPLE COLUMNS:


It is used if two or more records have same value in same column then
we can sort them according to another column.

Teacher_Name Class Student Subject


Bishnu 10 Kiran Math
Bishnu 10 Kiran Math
Raj 9 Sita Science
Priya 10 Ram Math
Ramesh 9 Gita Science
Laxmi 10 Shyam Math
Kiran 9 Deepa Science
Sunita 10 Anil Math

If we sort this table by class in descending order there are 5 records of


class 10 but also we can sort those 5 descending ordered in Alphbetical
order according to student column AS:
select * from teacher order by class desc,students asc;
[writing asc for ascending order is optional]
And result is
Sunita 10 Anil Math
Bishnu 10 Kiran Math
Bishnu 10 Kiran Math
Priya 10 Ram Math
Laxmi 10 Shyam Math
Kiran 9 Deepa Science
Ramesh 9 Gita Science
Raj 9 Sita Science

As we can see the class 9 students are also ordered in alphabetical


order,
Because class column has 3 records of class 9 and they are also sorted
according to alphbetical order.
ORDER BY WITH WHERE CLAUSE:

SELECT * FROM table_name WHERE condition ORDER BY col_name;

SELECT * FROM TEACHER WHERE


Teacher_name in ("Sunita","ram","bishnu","kiran","raj")
ORDER BY Teacher_name,class;

First select required records then sorts according to Teacher_name.


Bishnu 10 Kiran Math

Bishnu 10 Kiran Math

Kiran 9 Deepa Science

Raj 9 Sita Science

Sunita 10 Anil Math

AGREGATE FUNCTIONS:
To perfrom basic mathematical calculation of column we use agregate
functions.
MIN().MAX(),COUNT(),SUM(),AVG(),STDDEV(),VARIANCE() etc are
agregate functions.
All ignore null except,
count() it count null if we want to see of whole table but it ignores null
for a coulmn.

Note: No space between agregate function name and parenthesis


Count() [correct] count () [wrong]

STUDENTS TABLE

Name Balance Mother Father


Aarav 8765 Manju Hari
Anil 7890 Kumari Bikash
Arjun 5678 Laxmi Ram
Bibek 5674 Sunita Dilip
BIKRAM Null RUPA BHANU
BINOD Null ARUNA SUJAN
Dipesh 4563 Sarita Prakash
Kiran 2345 Shanti Dinesh
Niraj 6789 Gita Madan
Pratik 4321 Sita Shyam
Sujan 3456 Radha Gopal
Suman 1234 Mina Krishna

SELECT MIN(BALANCE) FROM STUDENTS;


>>1234

SELECT AVG(BALANCE) FROM STUDENTS;


>>5071.5000

To count total no of rows


select count(*) from students;
>>12

select count(balance) from students;


>>10 [ignores null values]
COUNT() WITH WHERE CLAUSE

SELECT COUNT(*) FROM students WHERE balance IS NULL;


>>2 [counts no of null field in balance]

select count(*) from students where balance>5000;


>>5

Select count(DISTINCT name) from students;


>> 12

To find sum of balance of name starting with “B”


select sum(balance) from students where name like"B%";
>> 5674
NESTED QUERY:
Nested queries are queries inside queries.
Consider two tables.

Teacher Table
Teacher_name Class Students Subject
Bishnu 10 Kiran Math
Bishnu 10 Kiran Math
Laxmi 10 Shyam Math
Kiran 9 Deepa Science
Sunita 10 Anil Math
Sunita 10 Niraj Math
Bishnu 10 Suman Math
Bishnu 10 Sujan Math

Student table
Name Balance Mother_Name Father_Name
Aarav 8765 Manju Hari
Anil 7890 Kumari Bikash
Arjun 5678 Laxmi Ram
Bibek 5674 Sunita Dilip
Dipesh 4563 Sarita Prakash
Kiran 2345 Shanti Dinesh
Niraj 6789 Gita Madan
Pratik 4321 Sita Shyam
Sujan 3456 Radha Gopal
Suman 1234 Mina Krishna

Some Names of students table appear in teacher table we can see it


using nested query

Select * from students where name in (select students from teacher);


Name Balance Mother_Name Father_Name

Anil 7890 Kumari Bikash


Kiran 2345 Shanti Dinesh
Niraj 6789 Gita Madan
Sujan 3456 Radha Gopal

Suman 1234 Mina Krishna

We can also do that from teacher table as:


Select * from teacher where students in (select name from students);

Teacher_name Class Students Subject


Bishnu 10 Kiran Math
Bishnu 10 Kiran Math
Sunita 10 Anil Math
Sunita 10 Niraj Math
Bishnu 10 Suman Math
Bishnu 10 Sujan Math

Where condition inside child query


select * from students where name in(select Students from teacher
where students like "%a__%");

Name Balance Mother_Name Father_Name

Anil 7890 Kumari Bikash

SQL ALIAS:
When we work with multiple table together it becomes confusing to add
different cols from different tables in a siingle query. So we use alias to
fix that.We give nickname to table.
For above student table:
select s.name,s.balance from students as s;

Note:Once the query is complete, the alias is no longer available for the
next query.

Teacher Table
Teacher Name Class Students Subject Salary
Laxmi 10 Shyam Math 1200
Kiran 9 Deepa Science 5500
Nabin 10 Kiran Math 9000
Rabin 10 Suman Math 9000
Sunita 10 Sujan Math 7000
Nirmal 10 Anil Math 7500
Apark 9 Pratik Science 2300

Students Table
Name Balance Mother's Name Father's Name
Aarav 8765 Manju Hari
Anil 7890 Kumari Bikash
Arjun 5678 Laxmi Ram
Bibek 5674 Sunita Dilip
Dipesh 4563 Sarita Prakash
Kiran 2345 Shanti Dinesh
Niraj 6789 Gita Madan
Pratik 4321 Sita Shyam
Sujan 3456 Radha Gopal
Suman 1234 Mina Krishna
select s.name from students as s where s.balance<(select t.salary from
teacher as t where s.name=t.students);
Name
Suman
Kiran
Sujan

SQL JOIN: It is used to join 2 or more than 2 tables through column.


Eg: above student and teacher table are connected by students.name
column.
Inner join returns only elements present in both tables.
select * from students as s inner join teacher as t on s.name=t.students;
[writing join and inner join is same]
Mother's
Name Balance Father's Name Teacher Name Class Students Subject Salary
Name
Kiran 2345 Shanti Dinesh Nabin 10 Kiran Math 9000
Suman 1234 Mina Krishna Rabin 10 Suman Math 9000
Sujan 3456 Radha Gopal Sunita 10 Sujan Math 7000
Anil 7890 Kumari Bikash Nirmal 10 Anil Math 7500
Pratik 4321 Sita Shyam Apark 9 Pratik Science 2300

Left join selects all from left table and only data that matches to left
table from right table.

select * from teacher as t left join students as s on t.students=s.name;

Teacher Name Class Students Subject Salary Name Balance Mother's Name Father's Name

Laxmi 10 Shyam Math 1200 NULL NULL NULL NULL


Kiran 9 Deepa Science 5500 NULL NULL NULL NULL
Nabin 10 Kiran Math 9000 Kiran 2345 Shanti Dinesh
Rabin 10 Suman Math 9000 Suman 1234 Mina Krishna
Sunita 10 Sujan Math 7000 Sujan 3456 Radha Gopal
Nirmal 10 Anil Math 7500 Anil 7890 Kumari Bikash
Apark 9 Pratik Science 2300 Pratik 4321 Sita Shyam
Above left table is joined with right in order.
There is self join also.

UNION:
It helps to merge two select statements are 2 or same tables but it will
be possible only when the order and type of data on 2 tables must be
same but name of columns can vary.
EG:
Table1: std_id,class,Course
Table2: teacher_id, class ,Course
These 2 table can apply union
But:
Table1: std_id,class,Course
Table2: teacher_id, Course,class
These 2 table cannot apply union as order of data is not same.

Syntax:
Select columbs from table1 union Select columbs from table2
This will show duplicate data only once

Select columbs from table1 UNION ALL Select columbs from table2
This will show duplicate data as much as apppear.

-- Create table t1stud


CREATE TABLE t1stud (
std_id INT,
class VARCHAR(50),
Course VARCHAR(100)
);

-- Create table t2teach


CREATE TABLE t2teach (
teacher_id INT,
class VARCHAR(50),
Course VARCHAR(100),
);

t1stud (students table):


std_id class Course
1 Class A Mathematics
2 Class B Physics
3 Class C Chemistry
4 Class D Biology
5 Class E History

t2teach (teachers table):


teacher_id class Course

101 Class A Mathematics

102 Class B Physics

103 Class C Chemistry

104 Class D Biology

5 Class E History

Select course from t1stud union select course from t2teach;


course
Mathematics
Physics

Chemisty

Biology
History

If I did union all it will repeat all subject twice.

GROUP BY:

You might also like