Mysql Notes October 03 2023
Mysql Notes October 03 2023
Mysql Notes October 03 2023
Relatton GUARDIAN
utth 4 attrnbute/
columns
Attribute: The columns of a relation are the attributes which are also referred as
fields. For example, GUID, GName, GPhone and GAddress are attributes of relation
GUARDIAN.
Tuple: Each row of data in a relation (table) is called a tuple. In a table with n
columns, a tuple is a relationship between the n related values.
2
Domain: It is a set of values from which an ttribute can take avalue in each row.
Usually,a data type is used to specify domain for an attribute.
Degree: The number of attributes in a relation is calledthe Degree of the relation. for
example, relation GUARDIAN with four attributes is a relation of degree 4,
Cardinality: The number of tuples in arelation is called the Cardinality of the relation.
For example, the cardinality of relation GUARDIAN 0s 5as there are 5 tuples in the
table.
Type help;' or '\h' for help. Type '\c' to clear the current ínput statement
nysql> create table temp(id int);
1046 (3De00): No database selected
Constraints
Constraints are the certain types of restrictions on the data values that an
attribute can have.
They are used to ensure correctness of data.
However, it is not mandatory to define constraints for each attribute of a table.
Commonly used SQL Constraints are,
Constralnt Deseription
Ensures that a column cannot have NULL values where NULL means missing/
unknown/not applcable value
Fnsurcs that all the values in a column arr distinct/unique
Adefault value spec1fed for the column if no value is pronded
The column which can unqucly dentufv cach row /record in atable
The column which refers to value of an attrnbute de fined as prmary key in another
table
SQL allows us to write statements for defining, modifying and deleting relation
schemas. These are part of Data Definition Language (DDL).
The Create statement is used tocreate adatabase and its tables (relations).
Before creating a database, we should be clear about the number of tables the
database will have, the columns (attributes) in each table along with the data
type of each column, and its constraint, if any.
CREATE Database
The number of columns in a table defines the degree of that relation, which is
denoted by N.
Attribute name specifies the name of the column in the table.
Datatype specifies the type of datathat an attribute can hold.
Constraint indicates the restrictions imposed on the values of an attribute.
Example:
Create table e1(eid integer, empname varchar(20), dob date, dpmt_id char(10) );
(or)
Create table el(eid integer primary key, empname varchar(20), dob date, dpmt_id
char(10));
Note: "" is used to separate two attributes and each statement terminates with a
semi-colon (;).
Describe Table
" We can view the structure of an already created table using the DESCRIBE
statement or DESC statement.
Syntax:
DESCRIBE tablename;
Ex: mysql> DESCRIBE el;
Field Type Null Key Default Extra
eid int 11) NO PRI NULL
ename varchari 20) YES NULL
dob date YES NULL
8
Alter Table
ALTER TABLE statement is used to make changes in the structureof a table like
adding, removing or changing datatype of column(s).
Add an attribute to an existing table
Sometimes, we may need to add an additional attribute in a table. It can be
done using the ADD attribute statement as shown in the following Syntax:
ALTER TABLE table_name ADD attributename DATATYPE,
Ex: mysql> ALTER TABLE e1 ADD salary integer;
Remove an attribute
Using ALTER,we can remove attributes from a table,as shown in the following
syntax: ALTER TABLE table_name DROP attribute;
To remove the attribute dept id from table el, write the following MysQL
statement:
The following insert statement adds the first record in the table:
mysql> INSERT INTOe1 VALUES (1,"Siva" "1998/07/03","A11",25000 );
We can use the SQL statement SELECT * from table name to view the inserted
records.
If we want to insert values only for some of the attributes in a table (supposing
other attributes having NULL or any other default value), then we shall specify
the attribute names in which the values are to be inserted using the following
syntax of INSERT INTO statement.
Syntax: INSERT INTO tablename (column1, column2, ..) VALUES (valuel, value2, ...J.
Ex., insert into el (eid, empname, dob, salary) values (1, "Siva", "1998/07/03",
25000);
SQL for Data Query
SQL provides efficient mechanisms to retrieve data stored in multiple tables in
MysQL database (or any other RDBMS).
The SQL statement SELECT is used to retrieve data from the tables in a
database and is also calledaquery statement.
SELECT Statement
The SQL statement SELECT is used to retrieve data from the tables in a
database and the output is also displayed in tabular form.
Syntax: SELECT attribute1, attribute2, ...FROM table_name WHERE condition;
10
Note:
Here, attribute1, attribute2, ...are the column names of the table table_name
from which we want to retrieve data.
The FROM clause is always written with SELECT clause as it specifies the name
of the table from which data is to be retrieved.
specified
The WHERE clause is optional and is used to retrieve data that meet
condition(s).
statement:
Toselect allthe data available in a table, we use the following select
SELECT * FROM table_name;
Ex., Select * from el;
eid empname dob dept_id salary
1 Siva 1998-07-03 A11 25000
The following query selects the employee number and employee name of all the
employees, we write:
mysql> SELECT eid, empname FROM e1;
eid empname
1 Siva
(b)Renaming of columns -In case we want to rename any column while displaying
the output, it can be done by using the alias 'As'. The following query selects
empname as ename in the output for allthe employees:
mysql> SELECT empname as ename FROM el;
ename
Siva
11
(c) Distinct Clause
" By default, SQL shows all the data retrieved through query as output.
" However, there can be duplicate values.
" The SELECT statement when combined with DISTINCT clause, returns records
without repetition (distinct records).
For example, while retrieving a dept id from employee relation, there can be
duplicate values as many employees are assigned to the same department.
To select unique department number for all the employees, we use DISTINCT as
shown below:
14
Aggregate Functions
Aggregate functions are also called Multiple Rowfunctions.
These functions work on aset of records asSa whole and return asingle value
Tor each column of the records on which the function is
applied.
Function Description Example with output
Max(column) Keturns the largest value mysal> SELECT MAX(salary) FROM el;
from the specified Output: 45000
column
e1;
Min(column) Keturns the largest valuemysgl> SELECT MIN(salary) FROM
from the specified Output: 22000
column
Sum(column) Returns the average of mysql> SELECT SUM(salary) FROM e1;
the values in the Output: 100000
specified column.
AVG(salary) FROM e1;
Avg(column) Returns the average of mysql> SELECT
the values in the
specified column.
Count(column) Returns the number of mysql> SELECT COUNT(salary) FROM
values in the specified e1;
column ignoring the
NULL values.
Count(*) Returns the number of mysql> SELECT COUNT(*)FROM el;
records in a table.
GROUP BY Clause in SQL
GROUP BY function is used to group rows of a table that contain the same
values in aspecified column.
. Wecan use the aggregate functions (COUNT, MAX, MIN, AVG and SUM) to
work on the groupedvalues.
HAVING Clause in SQL isused to specify conditions on the rows with Group By
clause.
15
Cartesian product on two tables
Cartesian product operation combines tuples from two relations.
It results in all pairsof rows from the two input relations, regardless of whether
or not they have the same values oncommon attributes.
" It isdenoted as "X'.
" The degree of the resulting relation is calculated as the sum of the degrees of
both the relations under consideration.
The cardinality of the resulting relation is calculatedas the product of the
cardinality of relations on which cartesian product is applied.
Let us use the relations p1 and p2 toshowthe output of cartesian product.
Note that both relations are of degree 3. The cardinality of relations p1and p2
is 2 and 3 respectively.
Applyingcartesian product on these two relations willresult in a relation of
degree 6 and cardinality 6, as shown in Table.
Example,
p1
no
p2
name dept no
1 arun admin
name dept
1 ajay admin
2 siva sales
2 siva sales
3 bala hr
p1 X p2
no name dept no name dept
arun admin 1 ajay admin
2 siva sales 1 ajay admin
1 arun admin 2 siva sales
2 siva sales 2 siva sales
arun admin 3 bala hr
2 siva sales 3 bala hr
17
a) Using condition in where clause
mysql> SELECT * FROM UNIFORM U, coST CWHERE U.UCode = C.UCode;
b) Explicit use of JOIN clause
mysql> SELECT * FROM UNIFORMUJOIN CoST C ONU.Ucode=C.Ucode;
c) Explicit use of NATURAL JOIN clause
The output of queries (a) and (b) shown in Table, has a repetitive column Ucode
having exactly the same values.
Thisredundant column provides no additional information.
There isan extension of JOINoperation called NATURAL JOIN which works similar
to JOIN clause in SQL but removes the redundant
attribute.
This operator can be used to join the contents of two tables if there is one
common attribute in both the tables.
Theabove SQL query using NATURAL JOIN is shown below:
mysql> SELECT * FROM UNIFORM NATURAL JOIN COST;
Following are some of the points to be considered while applying JOIN operations on
two or more relations:
18