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

database testing Syntaxes

The document provides an overview of database concepts, including definitions of databases, SQL, and DBMS, along with practical instructions for using MySQL for database management. It covers essential SQL commands for creating, retrieving, updating, and deleting data, as well as managing database structures. Additionally, it highlights the importance of using MySQL as a preferred open-source DBMS and includes links for downloading MySQL software.

Uploaded by

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

database testing Syntaxes

The document provides an overview of database concepts, including definitions of databases, SQL, and DBMS, along with practical instructions for using MySQL for database management. It covers essential SQL commands for creating, retrieving, updating, and deleting data, as well as managing database structures. Additionally, it highlights the importance of using MySQL as a preferred open-source DBMS and includes links for downloading MySQL software.

Uploaded by

Ahmed Mawrdy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

💽

Database testing ( Udemy +


guru99 )
what is database ?
it’s a collection of data : could be stored, managed and updated

the collection of data is organized in shape of tables consists of ( coloumns and


rows )

coloumns : the information category ( for example : Name of a student in a


student information table and so on )

rows : it’s the record ( the information for a specific student : for example Ahmed
is a student that is enrolled in course of database and paying 200 LE as a price
for this course )

how can we explain that in a shape of database :

Name Course Price Payment state

Ahmed Database 200 Paid


Mohamed Database 200 Not paid

so, Ahmed is a “ student “ enrolled in “ database “ course , whose price is “ 200 LE “


and he “ has already ” paid for the course
Mohamed is a “ student “ enrolled in “ database “ course, whose price is “ 200 LE “
and he “ hasn’t “ paid for the course

SQL ?
it stands for “ structure query language “ and it’s the way you can communicate with
database for managing the information within
— through SQL you can :

Database testing ( Udemy + guru99 ) 1


retrieve data from database

add data ( records or new records ) in database

update data in database

delete data in database

Create tables in database

Create database

Create stored procedures for retrieving, adding, updating or even deleting data
from database

Create views in database

Using Queries ( statements of the language itself )

DBMS ?
it stands for DataBase Management System, it’s the software you use to manage
database through using SQL queries

there are a lot of systems :

Microsoft SQL database

Oracle SQL database

SQLite database

SQL server

all you need to know is that there is no major difference between all the DBMSs in
Market

the differences are minor : mainly there are some queries supportive for some
DBMS but not for the others

Database testing ( Udemy + guru99 ) 2


MySQL database is the best practice cause it’s an open source, you don’t need to
pay for using the software and it has most of the common queries you need to know
about in managing database

you need to know the difference between SQL and MySQL ( SQL is the
structure query language, But MySQL is the DBMS you use to manage the
Database through using SQL queries

Downloading MySQL Server on workbench ?

you will need to download :

MySQL Server

MySQL Editor

links for version 8.0


: https://dev.mysql.com/doc/refman/8.0/en/macos-installation-pkg.html

https://dev.mysql.com/downloads/mysql/
for MySQL workbench : https://dev.mysql.com/downloads/workbench/
.
links for version 5.6

: https://dev.mysql.com/doc/refman/5.6/en/macos-installation-pkg.html

Overview with MySQL Editor and some of its features

Workbench is the place where you will write your queries and manage the
Database

Database testing ( Udemy + guru99 ) 3


Open MySQL Workbench to start working

steps :

1- we need to fast connect to the server to access the databases

2- server containing databases, in databases there is tables, in tables we have


records

so we need to connect to the server first of all,

press on this :

Database testing ( Udemy + guru99 ) 4


this password is the password you created through the download for MySQL
Community while installation ( keep that in mind and remember it always )

the interface :

SCHEMAS :

Database testing ( Udemy + guru99 ) 5


where the databases saved to the server are shown there.

QUERIES Playground :

Database testing ( Udemy + guru99 ) 6


where you will write queries and hit the button to run and execute on database
to deal and communicate with

DATABASES, TABLES, COLOUMNS :

as defined before, you can navigate them through the interface as shown

Database testing ( Udemy + guru99 ) 7


1. Database

2. Tables

3. Columns

Creating Database and pointing to it

Database testing ( Udemy + guru99 ) 8


by moving around, you need first of all to create database, so in the workbench,
write query :

create database NameOfDataBase;

then hit the execute button ( Note : when you select a specific query like
shading it, and hit the execute button, it will execute the selected query only, but
if you hit the execute button without selecting a specific query, it will execute all
queries in the workbench )

to make sure that the result is successful, look at the action result and its details

Database testing ( Udemy + guru99 ) 9


then, you can easily move to your schema, refresh it and see the results :

Database testing ( Udemy + guru99 ) 10


Creating tables

first of all, to start working with a specific database, you must mention that with
command :
use NameOfDatabase;

steps to create a table :

1. Sketch the table

2. define its name

3. define data headers ( row headers )

Database testing ( Udemy + guru99 ) 11


then, in SQL, we will use the upcomming command to create table with all of its
details :

create table NameOfTable(FirstHeaderName


Datatype(limit),SecondHeaderName Datatype(limit),.... );

Data type :

String ( varchar : it stands for variable characters )

Integer ( int : it stands for integer )

in all tables , for any type of information, you need to have an ID for the table
records and it must be an integer data

Database testing ( Udemy + guru99 ) 12


note on specifying int values with width int(#): ( advanced )

Database testing ( Udemy + guru99 ) 13


MySQL supports an extension for optionally specifying the display width of
integer data types in parentheses following the base keyword for the type.
For example, INT(4) specifies an INT with a display width of four digits. This
optional display width may be used by applications to display integer values
having a width less than the width specified for the column by left-padding
them with spaces. (That is, this width is present in the metadata returned
with result sets. Whether it is used is up to the application.)
The display width does not constrain the range of values that can be stored
in the column. Nor does it prevent values wider than the column display
width from being displayed correctly. For example, a column specified as
SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and
values outside the range permitted by three digits are displayed in full using
more than three digits.

Check : https://dev.mysql.com/doc/refman/8.0/en/numeric-type-
attributes.html

So it shall be safe to ignore these kind of warning up to current version of


MySQL (8.0.17 as of writing).
If you'd like to avoid these warnings and play safe, update all your affected
tables having column type definitions of something like INT(##) to INT (i.e.
without explicitly specifying the display width).

insert records in table :

first of all, if anyone asked you to know about the structure of a table you have
created, the schema : ( which is the fields of the table, each field constraints :
the data type expected for each field, if the field accept null value or not and if
the field takes a default value if doesn’t specified while adding a new record to
the table ), and all those data are important for database testing, right now, we
will use ( describe command to reach the schema of the table )

using describe command

Database testing ( Udemy + guru99 ) 14


to create records to table, we will use the command ( insert into TableName
values(FirstValue,SecondValue,.... )

as shown :

Database testing ( Udemy + guru99 ) 15


so what is the error ?

the error is when we adding a string data, it should be rounded by a single


quotation sign like this : ‘ahmed’

so the correct one is :

Database testing ( Udemy + guru99 ) 16


let’s add all of the other data ( insert into TableName
values(FirstValue,SecondValue,....)

Database testing ( Udemy + guru99 ) 17


like this :

Retrieving data from database :

Using ( select ) keyword, and it’s commonly used by 99%, it’s also majorly used
in database testing ( the goal is retrieving data from a specific database )

using ( select ) keyword and ( from ) keyword :


select : is to determine which data you want to get from the table or the
database

from : is to determine which table you will retrieve data from

Database testing ( Udemy + guru99 ) 18


it gives the first error because we didn’t executed the query of ( use ) that points
to the database we will work on,

then the results are :

Database testing ( Udemy + guru99 ) 19


we can also export results in an external file from this button :

Database testing ( Udemy + guru99 ) 20


note :
in case we have a lot of columns and we need to get all their data from
database specific table, we use ( * )

select * from TableName;

like this :

Database testing ( Udemy + guru99 ) 21


we need to know the difference between ( describe and select )

describe : is used to get the schema ( as we said it’s the description of our
table, the value type for each column, the data constraint for each column for
our table in database )

select : is used to retrieve data from database ( for a specific column or for the
whole table using * )

editing on a table in a specific database :

we can edit on any table of a specific database by using the query ( command )
( alter table )

Database testing ( Udemy + guru99 ) 22


Very important note :

alter table command is used only of editing on the table structure ( the schema ),
not editing the data inside the table itself

type of edits :
adding a new column
modifying the column specs ( constraints )
deleting a specific column

how to add a new column through using alter table command :

:: alter table TableName add NewColumnName DataType(width or limit);

Database testing ( Udemy + guru99 ) 23


to modify a column by using alter command :

:: alter table TableName modify ColumnName DataType(width or limit);

to delete a specific column from a table using alter table command with drop
column :

:: alter table TableName drop ColumnName;

Database testing ( Udemy + guru99 ) 24


So ,, edit on a table structure and NOT data ( alter table TableName
add(adding a column) ColumnName DataType(limit in case of varchar) )- (
alter table TableName modify(editing specs or constraints or datatype for
a specific column) ColumnName DataType(limit) )- ( alter table TableName
drop(deleting a specific column) ColumnName )

update the table info ( editing the data itself ) :

1. adding a specific record or updating an existing record in database specific


table :

we use the syntax with command UPDATE :

:: update TableName set col=value;

Database testing ( Udemy + guru99 ) 25


if we want to give the same value for all the data inside the table

:: update TableName set col1=value1 where col2=value2;

if we want to give value 1 to the column named co1 for the row which col2 is
value2 ( the condition syntax for SQL )

So, applying this :

that error means we are using SQL in mode where we can’t update on any data
inside any table, so to edit this, we go to edit window from preferences ,,
uncheck the box of safe updates from SQL Editor, then you must reconnect to
the server from the tab ( Query > reconnect to server ):

Database testing ( Udemy + guru99 ) 26


Database testing ( Udemy + guru99 ) 27
and here we go with our syntax again and updating the data in the table using
the update syntax :

Database testing ( Udemy + guru99 ) 28


then , through using update TableName set col=value where col2=value2; can
add or update a specific row in the table,,

2. deleting a specific record from a specific table in database :

we can use the command ( delete ) with syntax :


:: delete from TableName where col=value;
it will delete any data for the specific condition we give after the keyword “
where “

Database testing ( Udemy + guru99 ) 29


to delete an entire database : we use the command : DROP :
:: drop database DatabaseName;

Note : you must use the command ( use ) to point to the specific database you
want to delete before deleting it ( IMPORTANT )

Database testing ( Udemy + guru99 ) 30


so in a nutshell before we go further in course :

1. to create a database : create database DatabaseName;

2. to point to a specific database( and this is so important before we have any


edits on it ) : use DatabaseName;

3. to create a table in database we pointed to : create table


TableName(ColumnName1 DataType(limit if varchar), ColumnName2
DataType(limit if varchar and no need if int));

4. to get the schema ( constraints for each row, datatype, and so on - the
structure of the table ) : describe TableName;

5. to add a value to the table ( adding a new record to the database


specific table ) : insert into TableName values(FirstColumnValue,
SecondColumnValue,...);

Database testing ( Udemy + guru99 ) 31


6. to retrieve data from a specific table in database : select ColumnName
from TableName;

7. to retrieve all data from a specific table in database : select * from


TableName;

8. to edit on the schema of the table ( adding a new column ) : alter table
TableName add ColumnName DataType(limit);

9. to edit on the schema of the table ( editing a column existing ) : alter


table TableName modify ColumnName DataType(limit);

10. to edit on the schema of the table ( deleting a column existing ) : alter
table TableName drop ColumnName;

11. to update data in table ( adding a new data to a specific column for a
record or updating this data - edit on this specific column for this
specific record ) : update TableName set col1=value1 where col2=value2;

12. to update data in table ( delete record from the table ) : delete from
TableName where col1=value1;

13. to delete an entire database : drop database DatabaseName;

getting data effectively from database :

1. distinct keyword :

we use distinct keyword in case we have a lot of values for a specific column in
database ,, for example : we have two persons named ahmed and two persons
named hossam and two persons named kareem,, now we want to get all names
from the table but for each two hossams we want to get one hossam as it’s a
distinct name

using syntax : select distinct ColumnName from TableName;

Database testing ( Udemy + guru99 ) 32


applying this :

selecting all name values from table :

selecting distinct name values from table :

Database testing ( Udemy + guru99 ) 33


2. where command usage :

we use where as a condition on the data we want to retrieve, update or delete


on table in database,,

as we see :

:: select ColumnName from TableName where (Col=Val or Col>Val or Col<Val);

Database testing ( Udemy + guru99 ) 34


we can use the keyword AND to give one more condition as a more specific
filterization for the data we want to retrieve :

:: select ColumnName from TableName where Col=Value and Col2=Value2;

Database testing ( Udemy + guru99 ) 35


we get no data in this case because there is no one located in giza whose age
is greater than 30 ,,

so, in case we have more than one condition we use and, but in case we have
some groups of conditions that we want to retrieve data based on it

for example :
we want to get all the names in table in the database we using that :

living in giza and their age is not exceeding 30

living in cairo and their gender is female

how we could write it in a syntax :


BY USING WHERE, AND ,OR

Database testing ( Udemy + guru99 ) 36


Syntax will be : select name from TableName where ( location=’giza’ and
age<30 ) or ( location=’cairo’ and gender=’female’);

WOHOO :

why getting only one ahmed , because the other is male,

Database testing ( Udemy + guru99 ) 37


make sure of understanding these points :

when using AND operator and OR operator, make sure of using brackets
like this :

select —- from —— where ( —— and —— ) or ———- ;

AND operator is used to get data based on satisfying the condition before
and after AND

OR operator is used to get data based on satisfying the condition before


OR , or the condition after OR.

the operator IN :

we use in operator in case we want to get a specifc data for a group of


conditions belong to the same column ( but multiple ) ,, for example :

Database testing ( Udemy + guru99 ) 38


we want to get all persons that there age is equal to 27, 29 or 30

we have two ways to write it in syntax :

select name from TableName where age = 27 or age = 29 or age = 30;


like this :

but in a less syntax we can use :

select name from TableName where age in (27,29,30);


like this :

Database testing ( Udemy + guru99 ) 39


the operator BETWEEN :

we use it if our condition gonna be a range of numbers


as example :

we want to get all names for persons whose age is in range from 22 to 30 .

we have only one way to express the range to SQL, using BETWEEN ——
AND ——— :

:: select name from TableName where age between 22 and 30;

Database testing ( Udemy + guru99 ) 40


like this :

NOT operator :

NOT operator is only used with BETWEEN ( NOT BETWEEN ) in case we have
a 1000 records in database specific table, and we want to get data for all
records ( EXCLUDING ) a range of records from them ,, so how we do that :

:: select ColumnName from TableName where Col2 not between Value1 and
Value2;

like this :

Database testing ( Udemy + guru99 ) 41


and this also may help in understanding :

Database testing ( Udemy + guru99 ) 42


Database testing ( Udemy + guru99 ) 43
Regular Expressions :

when we need to retrieve some data for a specific condition for example, a
value we know to filter with for a specific column ( name as ex )

we are using where syntax like this

select **** from **** where col=value

but if that value is varchar , and we don’t know the full spelling for it , we are
using % and _ :

% is used for expressing an infinite number of characters


_ is used for expressing a single character

so how we can use it :

for example we need to get all data for a person whose name is beginning with
“ a “ character :

:: select * from TableName where name like ‘a%’; #that means we want to get
all data from table for persons that their names start with “ a “ whatever the
number of the rest characters

Database testing ( Udemy + guru99 ) 44


or we need to get all data from table for persons whose names contains “ a “ as
the second letter whatever number of the characters for the rest of name :

:: select * from TableName where name like ‘_a%’;

and so on

note that :

when using a regular expression as a condition we don’t use “=” , instead


we use the keyword LIKE

don’t forget to give a concentration on where the letter located in the word

for example :
hossam > ____a%
ahmed > a%

Database testing ( Udemy + guru99 ) 45


kareem, Ebrahim, Naeem > %m

we could use it for varchar values or int values as example :

we want to get all data for persons in 20th


:: select * from TableName where age like ‘2%’;
:: select * from TableName where age like ‘2_’;
as shown :

ordering and sorting results :

we can order the result of retrieved data from table by using the keyword ( ORDER
BY )

Database testing ( Udemy + guru99 ) 46


example :

we want to get all data from table ordering the results by name :

:: select * from TableName order by name;

( Note : it will re-arrange them in ascending order by default as you will see down
there ) :

note that : if we used it by ordering the results as for a value that is string ( varchar )
, it will re-arrange them in an alphabetical way

Database testing ( Udemy + guru99 ) 47


but in case we are dealing with integer ( int ) values in re-arranging ( sorting or
ordering ), it will deal with them as ftom 1 to #######

Note : we may need to order them in descending order ( from larger to smaller
or from last to first in strings )

we use keyword DESC after ORDER BY :


:: select * from TableName order by name desc;

Database testing ( Udemy + guru99 ) 48


Group by, Aggregate functions :

we use GROUP BY key word and Aggregate functions in case we have a lot of data
( records ) in database specific table, and we need to know a specific value that
present some records with a common factor between them ,, in more details , lets
see the example :

Database testing ( Udemy + guru99 ) 49


in the previous example, we see that we have a table of transactions for a specific
company that have a lot of branches, and each branch get some profit for various
days through months

Database testing ( Udemy + guru99 ) 50


so , we need to get the total amount of profit for each month ( separately )

first of all : we will use the keyword GROUP BY , to group the records based on
months and let’s see what happens.
using syntax :

:: select * from Transactions group by month;

Note : ( from stack overflow ) in case of group by query execution error

Expression #1 of SELECT list is not in GROUP BY clause


and contains nonaggregated column
'returntr_prod.tbl_customer_pod_uploads.id' which is not
functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by

will be simply solved by changing the sql mode in MySQL by this command,

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

This too works for me.. I used this, because in my project there are many
Queries like this so I just changed this sql mode to only_full_group_by
OR simply include all columns in the GROUP BY clause that was specified by
the SELECT statement. The sql_mode can be left enabled.
Thank You... :-)

Database testing ( Udemy + guru99 ) 51


we see here , SQL gives you the fastest result for each month it finds in its way :

but, we need to get the sum of amount for the whole month, not the fastest result of
the amount of a specific day , so we use Aggregate function with group by called
SUM(), we can use it in form of syntax like this :

Database testing ( Udemy + guru99 ) 52


:: select sum(Amount) from Transactions group by Month;

in this case it will give us the sum of amount but will not specify which value belongs
to which month like this :

so we can give more specification for the retrieved data by adding more values to
get to the sum of amount ( the specific month for each ) like this :

:: select sum(Amount),month from Transactions group by Month;

Database testing ( Udemy + guru99 ) 53


on the same rythm , we can get the Maximum value for a specific column based on
another column value ( filtering ) by using the function Max(ColumnName) :

:: select Max(Amount),Month from Transactions group by Month;

we can get the Minimum value for a specific column based on another column value
( filtering ) by using the function Min(ColumnName) :

:: select Min(Amount), Month from Transactions group by Month;

also we can get the Average value for a specific column based on another column
value ( filtering ) by using the function Avg(ColumnName) :

:: select Avg(Amount),Month from Transactions group by Month;

Database testing ( Udemy + guru99 ) 54


also we can get the number of records added for each specific value for each
column in database specific table using the count(*),ColumnName group by
ColumnName;

:: select count(*),Month from Transactions group by Month;

Database testing ( Udemy + guru99 ) 55


we can notice that april has Mx=Mn=Sum cause it has only one value

Database testing ( Udemy + guru99 ) 56


Very important to distinguish :

in case we want to add a condition to a group by syntax, we use the Keyword


HAVING

for example : we need to count all records filtered by month in case the records for
a month is less than 3 records

:: select count(*),Month from Transactions group by Month having count(*)<3;

Database testing ( Udemy + guru99 ) 57


So let’s try to get some practice :
in our case , we need to get total sum of amount generated for each month only
in bangal or chicago branches for each one of them separately

how we can do it

we will use group by , having and where with its keywords

:: select sum(Amount),Month from Transactions where Branch=’bangal’ or


Branch=’chicago’ group by Month,Branch;

or

:: select sum(Amount),Month,Branch from Transactions where Branch


in(’bangal’,’chicago’) group by Month,Branch;

Database testing ( Udemy + guru99 ) 58


Very Important Note (VIN)
Note that :

when we said that we use the keyword (having) with group by, we used it as a
condition that will be applied on the results column, not a column for the table
we are retrieving data from

so when we said :

:: select count(*),Month from Transactions group by Month having count(*)<3;

we meant to have all the records number for each month where the records
doesn’t exceed a specific number

but by using where, we are butting a condition on the results for retrieving the
data based on the column data contained itself , not the results

How can we handle subqueries

Database testing ( Udemy + guru99 ) 59


In case we have two tables, and we are asked to provide data from the two tables
together:

1. we must have a common column between the two tables that makes us able to
get the data we need for the same common ones

simply we can use SubQueries :

SubQueries :

using a query to provide a value for a condition to retrieve data using a parent query
from a specific table in terms of the other table

in our example :
we have those :

Database testing ( Udemy + guru99 ) 60


we need to get the age of citizens that located in texas,

So we will use subqueries :

:: select name,age from citizens where name=(select name from citizenloc where
location=’texas’)

Database testing ( Udemy + guru99 ) 61


Note that :

in case you have more than one person located in texas, you must take in
consideration that your subquery will give you more than one record, so it couldn’t
be ( name=(subquery)), instead you will use ( name in(subquery));

:: select name,age from citizens where name in(select name from citizenloc where
location=’california’)

Database testing ( Udemy + guru99 ) 62


Join Usage and its advantages :

in the previous case, we have two tables, and a common column between them,
and we used subqueries to get data from a table in terms of the others using that
common column values,

easily we can use JOIN concept to generate a table which is containing the data of
two tables :

Note : the same as subqueries , to join two or more tables, you need to have
one common column between them at least, or one common column between
two of them ( if you have more than two tables ) and another common one
between the other two ( no need for the common column to be common
among the three tables, it’s just needed to have a common column between
the first pairs and it could be different from the other common one between
the other pair )

in our example, here is a clarification for the concept of JOIN :

Database testing ( Udemy + guru99 ) 63


so based on that :

1. use the select syntax and refer to the tables you want to get data from to insert
into the join table for each column from each one as this :

we give citizens refer as c


we give citizenloc refer as cl

:: select c.name,cl.location,c.age from citizens as c join citizenloc as cl

2. you must refer to the basement of join so SQL will not be confused by matching
the data based on columns in case they are different in arrangement ( give each
name its value in each table of them )

based on the common column ( in our case Name ) :

:: select c.name,cl.location,c.age from citizens as c join citizenloc as cl on


c.name=cl.name;

WOHOO :

Database testing ( Udemy + guru99 ) 64


you got exactly what you need ,

so, if you want to but a condition, so you will use the refer concept with the new
letters ( as refered to each table of the two tables ) :

ex : we want to get the name, location and age of people who are living in california

:: select c.name,cl.location, c.age from citizens as c join citizenloc as cl on


c.name=cl.name where cl.location = ‘california’;

Database testing ( Udemy + guru99 ) 65


Note : for performance of database , it’s better to use JOIN rather than using
SubQueries ( because it gives you two operations in one query if you are
using subqueries, while it seems to be one operation running while using
JOIN concept )

practical example :

for the two tables given :

we want to get the total number of employees for a company which established in
1990

Database testing ( Udemy + guru99 ) 66


solution :

:: select sum(c.employees),c.Name,e.year from company as c join established as e


on c.name=e.name where e.year=1990 group by c.name;

another solution using having :

Database testing ( Udemy + guru99 ) 67


Note that : for each value in the first table , it takes the opposite value for it in
the second table based on the common column ( even the rows are less ) (
based on the name as a common column )

inner join, left join , right join :

in the upcoming example :

Database testing ( Udemy + guru99 ) 68


two tables of two different entities, an academy and certification center,
the first required is to get all the students from the first entity who passed in the
exam ( their grades appear in the certification center table - grades table ) :

here is the solution, we are using inner join easily and get what we want :

1. inner join :

the same requirement, we need all data for first entity students who passed the
exam,
using inner join :
inner join is the way we used as before but to be more specific in types of join we
use INNER JOIN
and as a result , we don’t need to use the keyword AS

Database testing ( Udemy + guru99 ) 69


:: select s.name,s.id,s.age,s.gender,g.grade from studentdetails s inner join grades
g on s.id=g.id

2. left join :

we want to get the student details for all from the first entity who appeared in the
exam ( attended but not passed ) > it means we want to get a join table that
contains all the students from the first entity student details table :

we are going to use left join, in the same syntax with inner but using LEFT instead
of INNER

:: select s.name,s.age,s.id,s.gender,g.grade from studentdetails s left join grades g


on s.id=g.id;

Database testing ( Udemy + guru99 ) 70


3. right join :

we want to get the student details for all from the second entity who passed in the
exam ( no matter they are belonging to the first entity or not ) > it means we want to
get a join table that contains data for all students passed in the second entity no
matter they are belonging or not to the first entity :

we are going to use right join, same syntax as inner and left but using RIGHT
instead :

:: select s.name,s.age,s.id,s.gender,g.grade from studentdetails s right join grades g


on s.id=g.id;

Database testing ( Udemy + guru99 ) 71


very important screenshot to clarify the concept :

views

views are child tables created from a parent table to have a new table grapping all
data for a specific condition :

for example :

we have a table in database that gives you information about a lot of companies,
and you want a new table generated from it to get the data from, only for one or two
companies, then you need to use views :

Database testing ( Udemy + guru99 ) 72


here you need a table that created from the company table to get all the data
specified for only Google like this :

how can you do that using views in sql :

simply using views, we run query :

:: create view google_company as select * from company where name=’google’;

like this :

Database testing ( Udemy + guru99 ) 73


1. selecting all from company table

Database testing ( Udemy + guru99 ) 74


2. create a new child table for only google company information :

and it will not be added to the tables of database, instead it will be added to views
as like :

Database testing ( Udemy + guru99 ) 75


very important practice on views

we have a case on the previous example :


we need to have a new table for information about companies whom employees
number is more than the avg of the whole companies in the parent table (
company table ) :
Trials :
if you tried to get it using group by and having keywords L

1. create view most_employees as select sum(employees),name,branch from


company group by name having sum(employees)>avg(employees);

Database testing ( Udemy + guru99 ) 76


it will give you as shown the companies that their total number of employees
are greater than the their average number of employees and that means it gives
you only the companies that have more than one branch ( cause in this case
the avg < sum )

so we need to think in another way :


hint ( using subqueries ) :

using subqueries will allow you to get a comparison between the sum of
employees for a specific company and the average number of employees of the
whole companies in the parent table
so :

2. using subqueries in that syntax to create our desired view :

:: create view most_employees as select sum(employees),name from company


group by name having sum(employees)>(select avg(employees) from
company);

Database testing ( Udemy + guru99 ) 77


that’s exactly what we need.

string functions :

1. if we need to concatenate two strings into single column we use the string
function called CONCAT:

simply as :: concat(FirstCol,SecCol) as NewNameForNewCol

in our example we need to concatenate the name and branch in this table in a new
column :

Database testing ( Udemy + guru99 ) 78


:: select concat(name,branch) as branch_name from company;

Database testing ( Udemy + guru99 ) 79


it gives us the desired result.

2. substring :

we use it when we need to have a column that contain string info from another
column from the table but not the full string contained in that column from the table

for example , we want a column that contain abbreviation for the company name (
let’s say the first and second letter only )

two cases here for using substring :

Database testing ( Udemy + guru99 ) 80


in case we need to take part of the string starting from a letter index to the end
of name we specify only the index of beginning character like this :
substr(name, 3)

in case we need to take part from letter to the other, we specify the starting
index as well as the ending index like this : substr(name,3,5)

in our example we need only the first two letters from all of the companies names :

:: select substr(name,1,2) as appname from company;

Database testing ( Udemy + guru99 ) 81


3. replace :

when we are asked to replace a name or part of the name of a data inside a specific
column, we use the string function REPLACE :

how can we use it :

select replace( ColName, ‘the part of the name we want to replace’,’the desired
replacement of that part) from TableName where ColName=’the name we want to
replace part of it’;

for example :

Database testing ( Udemy + guru99 ) 82


note that :

it didn’t changed because you didn’t give concern for the capital letter in the
QAClickAcademy ( Aca instead of aca ) . very important

4. length

Database testing ( Udemy + guru99 ) 83


when we want to get the length of a string value inside a specific column, we use
the string function LENGTH:

how can we use it :

:: select length(ColName) from TableName;


or
:: select length(ColName) from TableName where ColName in(’value1’,’value2’)
in case we want the results for specific values

for example :

as you see, it gives you the count of letters contained on each company name in the
name column in company table

5. trim ( not useful )


we use it in case we want to reduce the spaces around a string value inside a
column in a table

Database testing ( Udemy + guru99 ) 84


how can we use it :
:: select trim(’ TheRoundedValueOrNameWithSpace ‘) from TableName where
ColumnName=’ the whole string value ‘;

6. limit :

we use it when we are asked to get only the first (##) of records in a table in
database

how can we use it :

:: select ColName from TableName limit NumberOfRecordsWeDesireToGet;

for example :

we want to get the first 3 records from the company table :

:: select * from company limit 3;

Database testing ( Udemy + guru99 ) 85


or we want to get the name value for the first 3 records :

:: select name from company limit 3;

Union, Union all, Intersect, Exists and Case :

1. Union, Union all :

Database testing ( Udemy + guru99 ) 86


we use union in case we have two tables with the same columns ( differentiate in
data or records inside each of them ), and we want to have a merged table between
them, BUT we need the merged table to contain unique records ( in case there are
duplicated records between them, give on record for all duplicated records )

how can we apply that in a real time scenario :

we have two tables : the first table contains the names and IDs of the 1st and 2nd
year students
the second table contains the names and IDs of the 2nd year and 3rd year students

and we want to get a merged table contains the names and IDs for the 1st,2nd and
3rd year students.

Database testing ( Udemy + guru99 ) 87


the table we need with unique records ( no need for duplicated records )
we apply UNION keyword usage :

how can we do that :

:: select * from 1stTableName union ( select * from 2ndTableName);

applying that :

Database testing ( Udemy + guru99 ) 88


applying union :

Union all :

in case we want a merged table ( with all records : containing duplicated records )
we use union all

Database testing ( Udemy + guru99 ) 89


how can we use it :

:: select * from 1stTableName union all ( select * from 2nd TableName);

applying that in our case :

the result we want :

applying in SQL :

Database testing ( Udemy + guru99 ) 90


2. intersect :

Unfortunately, we don’t have intersect keyword in MySQL, it belongs to OracleSQL


only,

we use it to get the intersection between two tables, that means it gives you a table
that contains the records only found in both tables :

real time example :

Database testing ( Udemy + guru99 ) 91


we have a table for the students in the college ( with their name and id ) , and a
table for the results in the exam, we are asked to provide a table that contains all
the students names and ids for whom that are students in the college and passed in
the exam :

as we said , we can’t use intersect keyword , for info only , in oracle we use it the
same syntax as union and union all like this :

Database testing ( Udemy + guru99 ) 92


:: select * from 1stTable intersect ( select * from 2ndTable )

in MySQL , we can solve that by two ways :

first way: subquery :

:: select * from 1stTable where id in ( select id from 2ndTable );

second way : join or inner join :

:: select T.name, B.id from 1stTable as T join 2ndTable as B on T.id = B.id;

:: select T.name,B.id from 1stTable T inner join 2ndTable B on T.id = B.id;

applying that :

Database testing ( Udemy + guru99 ) 93


3. Exist :

we use it when we need to retrieve all data from a specific table in case specific
record belongs to that table

real time scenario :

Database testing ( Udemy + guru99 ) 94


we have a college table with names and IDs for students, and there is a student
who made a crime, the police station have the ID for that student and want to know
if the student is belonging to a specific table, to get all data for the whole students in
that college to investigate with them.

so , the policeman want to know if the student belongs to the college or not (
condition )

then, if so, he want to get all the students’ data from that college :

:: select * from TableName where exists ( select * from TableName where id = ## );

applying that in our case :

we want to know if id = 574 exists in table or not, if so , get all data for the college :

:: select * from college where exists ( select * from college where id = ‘574’ );

Database testing ( Udemy + guru99 ) 95


we want to know if id = 333 exists in table or not, if so , get all data for the college :

:: select * from college where exists ( select * from college where id= 333 );

4. Case :

if we got a table, and we want to modify on some records of the table for specific
records only , we use case statement :

in real time scenario :

Database testing ( Udemy + guru99 ) 96


we have a table for the scores of some students, and for some students we want to
edit on their scores and have a new column showing the new scores based on the
edits on some records we mentioned,

how to use case statement :

:: select Col1, case Col2


when Val1ForCol2 then Col1Edit
when Val2ForCol2 then Col1Edit
else Col1
end
‘NewCol1ValuesName’,Col2 from TableName

in our previous example :

Database testing ( Udemy + guru99 ) 97


we can also create view for the new resulted table :

SQL constraints :

table constraints :
it’s the way how we can limit the data type which may be added in the future to the table
different columns.

it’s too important concept in database testing to validate on the constraints for the
columns of a specific table or group of tables in database.

1. NOT NULL :

it’s a constraint which can be added to the table schema for a specific column while
creating the table, which doesn’t allow any record to be added to the table while not
giving a value for that column ( Note : any column by default, when adding a record to
the table while the value for that column is missing, it takes NULL value )

Database testing ( Udemy + guru99 ) 98


in real time scenarios, that constraint prevent users from miss adding a mandatory
value
like a flight website, it doesn’t matter to add the date of the flight or the specific time for
it but it’s a mandatory to add the destination and departure, also as the flight number for
example, then for those three fields ( three columns in database, we add a constraint
that NOT NULL, not to allow users to add the flight details without providing data for
those three fields )

( Note : after adding this constraint, when you try to add a record to a table in database
without providing value for that specific column, the query will not be executed and it will
give you an error )

how to apply that while creating a table :

simply while creating the table :

:: create table TableName( Col1Name DataType, Col2Name DataType not null );

then Col2 will not accept null values, and you can’t add records without giving a value
for that column, like that :

creating the table :

Database testing ( Udemy + guru99 ) 99


testing the constraint :

1. trying to add a new record to the table without giving a value to flight id :

2. trying to add record with null value for the column flight id :

Database testing ( Udemy + guru99 ) 100


2. DEFAULT :

it’s added to a column as a constraint, if we want to make that column take a default
value in case there is no value provided to it while adding a new record to the table

:: create table TableName( Col1Name DataType(Limit) default DefaultValue);

real time scenario:

for a company that have too many branches and one main branch, if we are creating a
table for employees details, and we want to add records for each employee, with option
that if we are not providing information about for which branch he(she) belongs, then it’s
by default belonging to the main branch,

how can we apply that and test it :

Database testing ( Udemy + guru99 ) 101


1. creating the table with constraint:

2. trying to add a new record ( without adding info about branch ) :

Note that ( in MySQL 8.0 version and above, in insert statement, you must specify the
columns you provide data for with the same arrangement of columns, without
mentioning the default value constrained column ), like this :
:: insert into TableName(ColName) values(ValueforTheColumnMentioned);

3. Unique constraint :

Database testing ( Udemy + guru99 ) 102


we use unique constraint when we want to give a rule to a column in table in database
that it doesn’t accept duplicated values as a new record, it means each record added to
the table must have a unique value for that column,

how can we use it :

create table TableName( Col1Name DataType(LimitIfString) unique );

applying that for an example :

trying to insert duplicated values for two records ( values for the unique constrained
column ):

Database testing ( Udemy + guru99 ) 103


4. Check constraint ( isn’t supported in MySQL ) :

for overview :

when we want to put a customized constraint on a column value, it’s called CHECK,
for example, while we create the table, we want the ID column not to accept any values
that is less than 10, so we can simply do it by check constraint,

how can we use it in query :

:: create table TableName( Col1Name DataType(LimitIfString) check Col1Name > 10 );

5. Primary Key :

it’s the unique identifier for a record in database, let’s say :


we have a company with database including table for the employees info, and we want
to have a column that make it easy for us to uniquely identify each employee separately,
using name will make it confusing because there is a high probability that we have two
employees with the same name, and so as for the branch, but for the ID, it’s a unique

Database testing ( Udemy + guru99 ) 104


value that could be given for each employee, so that whenever I try to get the employee
info, I will identify him ( refer to him ) using the ID. so the ID column is the primary key.

Note : one table can contain more than one primary key, in this case it’s named as
composite key
Note2: the UNIQUE constraint + NOT NULL constraint = PRIMARY KEY constraint

how can we use it :

:: create table TableName( Col1 DataType(Limit), Col2 DataType(Limit), primary


key(Col1));

that means Col1 is the primary key for that table, it means it couldn’t accept null value (
not null ), and it must be unique as well.

applying that :

Database testing ( Udemy + guru99 ) 105


trying to insert a duplicated value for the primary key column :

trying to insert a null value :

Database testing ( Udemy + guru99 ) 106


Foreign key :

it’s all about mapping among tables in database,

the foreign key is the way we have to integrate between two tables in database,

the foreign key is the first table’s primary key and it should be contained in the second
table which we want to integrate the first table to :

1. the primary key for the first table must be unique and not null for the first table

2. the foreign key ( which is the primary for the first table ) may have one value for
more than one record ( may not be unique ) but it doesn’t accept null values for the
second table

3. to insert a record into the second table ( including value for the foreign key ), this
value must be contained in the first table to create that record in the second table

4. to delete a record in the first table, it must be checked first for all the records related
to the record need to be deleted in the second table, that they must be deleted
FIRST from the second table before deleting the record from the first table

Database testing ( Udemy + guru99 ) 107


5. the second table must have a primary key ( best practice )

how can we explain that in real time scenario :

assuming that we have an online shopping website , in this website, you must be
registered as customer before placing any order, so :

the business logic tells you that :

1. we must have a table for the registered customer data ( info ) including a primary
key ( ID for example and the best practice ) that will be the foreign key for any other
integrated table

2. we must have a table for the placed orders that contain ( the customer ID as a
foreign key , the order ID as the primary key )

that means :

A- the customer must be registered before placing any order


B- Any customer account couldn’t be deleted in case they have placed any order

Database testing ( Udemy + guru99 ) 108


that means ahmed is an already registered customer who placed two orders, so,

ahmed’s account can’t be deleted before they two records for the two orders he placed
are deleted first.

how we can apply that for two tables in database ( 1 parent table and 1 child table ) :

:: create table TableNameParent( Col1 DataType(limit), Col2 DataType(limit),... primary


key(Col1));

:: create table TableNameChild(Col3 DataType(limit), Col1 DataType(limit),..... primary


key(Col3), foreign key(Col1) references TableNameParent(Col1));

Trying to have this on our real time scenario example ( customer details and order
details tables ) :

1- creating the parent table ( customer details ) :

Database testing ( Udemy + guru99 ) 109


2- creating the child table ( order details ) :

3- adding records to customer details table :

4- adding records to order details ( trying to add using id that doesn’t found in the parent
table ) :

5- adding records to order details ( using existing id in the parent table ) :

Database testing ( Udemy + guru99 ) 110


6- trying to delete record from the parent table without deleting its related records in the
child table :

7- deleting records from the parent table after deleting its related records from the child
table :

how to provide delete option directly from parent table ( even there are records in the
child one related to that record ) :

simply we are using the concept of “ ON DELETE CASCADE “ , here when we directly
try to delete a record from the parent table, it will be deleted and all the records related
to it in the child table will also be deleted.

Database testing ( Udemy + guru99 ) 111


how can we use it :

:: create table TableNameChild(Col1 DataType(Limit),.... foreign key(Col1 )


REFERENCES TableNameParent(Col1) ON DELETE CASCADE );

while creating the child table

applying that :

when trying to delete a record from the parent table :

1- adding records to the parent and child first :

2- deleting records from the parent table directly :

Database testing ( Udemy + guru99 ) 112


here we find that the record added to the child table ( related to the deleted record from
the parent ) is also deleted :

Note : if you tried to drop the parent table, you must drop all child
tables first ( the same as records )

Database testing ( Udemy + guru99 ) 113

You might also like