Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views8 pages

MySQL Notes 1

Uploaded by

pearlkumbhat7
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)
5 views8 pages

MySQL Notes 1

Uploaded by

pearlkumbhat7
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/ 8

MySQL

IP - 12th
IMPORTANT DEFINITIONS
Database: Database is the collection of related data.

DBMS: Database Management System is used to manage the database. A Database Management System is a
collection of interrelated data. Its objective is to provide an environment to retrieve and store database
information.

Relational Database Management System (RDBMS): It facilitates the storage, access, security and integrity of
data and eliminates data redundancy. It stores the data in a set of tables. Example: MySql, SQL Server etc.

Data Integrity: It means that data contained in the database is both accurate and consistent.

Advantages of database management system:


1. Reduced data redundancy (duplication of data is removed).
2. Inconsistency is also maintained.
3. Sharing of data can be done.
4. Database enforced standards.
5. Secured data and Privacy of data.

Database Models: A database model describes the database scheme as per the stated requirements. These
models are called data models. These are three types of models:
a) Relational Model
b) Hierarchical Model
c) Network Model

Data Dictionary: A file containing facts or data about the data stored in the table. It is also called as “metadata”.

Relation: A relation is a table in Relational Model.


Table: It is a collection of rows and columns which describe the necessary structure to store data.
Attribute: Column of a table is called attribute.
Tuple: Row of a table is called a tuple.
Degree: The number of attributes in a relation is called the degree of the relation.
Cardinality: The number of tuples in a relation is called the cardinality of the relation.
Primary Key: The primary key of a relation uniquely identifies each record in the table. Primary keys may consist
of a single attribute or multiple attributes in combination.

Candidate Key: A candidate key is the one that is capable of becoming primary key i.e., a field or attribute that
has unique value for each row in a relation.

Alternate Key: A candidate key that is not primary key is called an alternate key.

Foreign Key: A non-key attribute, whose values are derived from the primary key of some other table. A foreign
key refers to a primary key or a unique key in another table.
Explain with example:-
*Employee

Empno regno ename sal deptno


1 1011 abc 7000 20
2 1021 xyz 10000 10
3 1031 mno 6800 5
4 1041 rst 15000 20

Dept
Deptno dept_name
5 accounts
10 sales
20 purchase
30 production
Empno & regno are candidate keys in Employee table
Empno is primary key & deptno is foreign key of employee table
Deptno is primary key of dept table

Integrity constraints: They are the rules that a database must comply at all times. It determines what all
changes are allowable to the database.
*it can be done by all constraints like not null, default, primary key etc

Classification of SQL Statements


1. Data Definition Language (DDL) commands: Allows you to perform tasks related to data definition such as
Creating, Altering and Dropping.

2. Data Manipulation Language (DML) commands: Allows you to perform the data manipulation such as
retrieval, insertion, deletion, and modification of data stored in a database.

3. Transaction Control Language: Allows you to manage and control the transactions such as commit, rollback,
creating save points.

Data Types: means to identify the type of data. Various MYSQL data type is:

 Numeric
Integer: Stores numeric values.
Float, Double and Decimal
 Date and time types
Date: Stores date in ’yyyy- mm- dd’ format.
Time: Stores time ‘hh: mm: ss’ in format.
Datetime: Stores date and time combination in ’yyyy- mm- dd’ ‘hh: mm: ss’ format.
 String types: char(size) and varchar(size)
Difference between char and varchar.
Char Varchar

1. It is of fixed length. It is of Variable length.

2. Occupy fixed number of bytes i.e., n bytes. No blanks are added if the length is
If a value is shorter than this length n then shorter than the maximum length n.
blanks are added, but the size of values
remains n byte.
Relational operators: These operators are used to compare two values. Various relational operators are:
= equal to, >greater than, < less then, >= greater than or equal to,
<= smaller than or equal to, <>not equal to
Logical operators: OR (||), AND (&&) and Not (!)

COMMANDS IN MYSQL
1. For creating a database syntax is:
Create database <database name>;
For e.g., create database employee;
2. To open databases syntax is:
Use <database name>;
For e.g., use employee;
3. To see all the databases use syntax is:
Show databases;
4. To remove a database syntax is:
Drop database <database name>;
For e.g., drop database employee;
5. For Creating tables in a database syntax is:
Create table <table name>
(<Column name> <data type> [(size)]),
<Column name><data type> [(size)…]);
For e.g., Create table emp
( ecode integer,
ename varchar(20),
grade char(2),
gender char(1),
salary decimal );
6. To view the number of tables in a database:
Show tables;
7. To view the structure of table:
Desc <tablename>;
For e.g., desc employee;
8. Insert into command:
Insert into <tablename> values (<value>, <value1>…);
For e.g., Insert into emp values (101, ’smith’, ’e1’, 5000.00);
9. Select Command:
Select <column name …> from <table name>;
For e.g.,
a) To show all the columns from emp table.
Select * from emp;
b) To view only two columns i.e., code and name grade from emp table.
Select ecode, ename, grade from emp;
c) To eliminate redundant data (with distinct keyword).
Select distinct ename from emp;
10. Where Clause:
Select <column name …> from <table name> where <condition>;
For e.g.,
1. Select all information of employee whose empid =101
Select * from emp where empid =101;
2. Select all employee that were born on or after jan 1,1998.
Select * from emp where dob>=’1998-01-01’;
3. Select all manger of deptno 20.
Select * from emp where job=’manager’ and deptno=20;
4. Select all salesman or manager.
Select * from emp where job=’salesman’ or job=’manager’;

11. Condition based on a range: The Between operator defines a range of values.
For e.g.,
1. Display the records of an employee whose salary is between 30000 and 70000.
Select * from emp where salary between 30000 and 70000;
2. Display the records of an employee whose salary is not between 30000 and 70000.
Select * from emp where salary not between 30000 and 70000;

12. Condition based on Pattern matching: For comparing the character strings using Patterns.
Patterns are described using 2 special wildcard characters:
 Percentage (%): It matches any substring.
 Underscore (_): It matches any character.
The like keyword is used to that match a wildcard pattern.
For e.g.,
1. List the name of employee whose name starts with ‘A’.
Select ename from employee where name like’A%’;

2. List the name of employee whose name ends with ‘A’.


Select ename from employee where name like ’%A’;

3. List the name of employee whose name contains ‘A’ as fourth alphabet.
Select ename from employee where name like’_ _ _A%’;

13. Use of NULL: Null value can be searched in a table.


For e.g.,
1. List the name, job and department of employees whose department contain Null.
Select ename, job, dept from employee where deptno Is Null;
2. List the name and department of employees whose department contain Not Null.
Select ename, dept from employee where deptno Is Not Null;

14. Order by: Sorting can be done either in ascending or descending order, the default order is ascending.
For e.g., List the details of employees in descending order of employee code.
Select * from employees Order by ecode desc;
15. Column Alias: Columns that you select in a query can be given different
Select <column name> AS [column alias] from <table name>;
For e.g., select sal as “salary” from employee;

MYSQL FUNCTIONS
Function: A function is a special type of predefined command set, that performs some operation and return a
single value.

Various MYSQL functions are:


1. String function
2. Numeric function
3. Date/time function
STRING FUNCTIONS:
Function name Description Example

Char() Returns the character for each Select char (70,65,67.3,’69.9’);


integer passed. Ans: FACE
Concat() Concatenates (join) two strings. 1. Select concat (name, age) from emp;
Ans: pooja 30
2. select concat(concat (ename, “is a”, job);
Ans: pooja is a clerk
Lower/Lcase() Converts a string into lowercase. Select lower(‘HELLO’) ;
Ans: hello
Upper/Ucase() Converts a string into uppercase. Select upper(‘hello’) ;
Ans: HELLO
Substr() Extracts a substring from a given 1. Select substr(‘webtech’ ,2,5);
string. Ans: ebtec

2. Select substr(‘webtech’ ,-4,3);


Ans: tec
Ltrim() Removes leading spaces i.e., from Select ltrim(‘ pooja goel’ );
the left of the given string. Ans: pooja goel
Rtrim() Removes trailing spaces i.e., from Select rtrim(‘ pooja goel’ );
the right of the given string. Ans: pooja goel
Trim() Remove leading and trailing spaces 1. Select trim(‘ star one ‘);
from a given string. Ans: star one
2. Select trim (leading ‘x’ from ‘xxxstar one
xxx ‘);
Ans: star one xxx
3. Select trim (both ‘x’ from ‘xxxstar
onexxx’);
Ans: star one
Instr() Searches for given second string Select instr (‘pooja goel’,’oo’);
into given first string. Ans: 2
Length() Return the length of a given string Select length (‘hello’) as len;
in bytes. Ans: 5
Left() Return the leftmost number of Select left (‘user/23/67’ ,3);
characters as specified. Ans: use
Right() Return the rightmost number of Select right (‘user/23/hello’ ,4);
characters as specified. Ans: ello
Mid() Returns a substring staring from a Select mid (‘quarter’ 3,4)
specified position. Ans: ater

NUMERIC FUNCTIONS
Function Description Example
name

Mod() Returns modulus i.e., remainder of two Select mod(11,4) as “modulus”;


numbers. Ans: 3
Power/ Returns mn i.e., a number m raised to the Select power (2,3) as “raised”;
pow() power n. Ans: 8
Round() Returns a number rounded off. 1. Select round(20.3464,2) as “round”;
Ans: 20.35
2. Select round(20.3464,-1) as “round”;
Ans: 120
3. Select round(20.3464,-2) as “round”;
Ans:100
4. Select round(20.3464,-3) as “round”;
Ans: 0
Sign() Returns sign of a given number. Select sign(20) as ‘sign”;
Ans: 1
Select sign(-20) as ‘sign”;
Ans: -1
Sqrt() Returns the square root of given number. Select sqrt (144) as “square root”;
Ans: 12
Truncate() Returns a number with some digits Select truncate (20.19399, 4) as “trunc”;
truncated. Ans: 20.1939

DATE/ TIME FUNCTIONS


Function name Description Example

Curdate/ Returns the current date in yyyy-mm-dd Select curdate();


current_date() format. Ans: 2011-02-16
Date() Extracts the date part of a date or Select date(‘2011-02-16 01:02:03’);
datetime expression. Ans: 2011-02-16
Month() Returns the month from the date Select month (‘2011-02-16’);
passed. Ans: 2
Year() Returns the year part of a date, in the Select year(‘2011-02-16’);
range 1000 to 9999. Ans: 2011
Dayname() Returns the name of weekday for date Select dayname (‘2011-02-16’);
Ans: Wednesday
Dayofmonth() Returns the day of month. Select dayofmonth(‘2011-02-16’);
Ans: 16
Dayofweek() Returns the day of week. Select dayofweek(‘2011-02-16’);
Ans: 4
Dayofyear() Return the day of year for the date. Select dayofyear(‘2011-02-16’);
Ans: 47
Now() Returns the current date and time. Select now();
Ans: 2011-02-16 01:02:03
Sysdate() Returns the time at which the function Select sysdate();
executes Ans: 2011-02-16 01:02:03

*Define questions:-
B)Consider the EXAM given below. Write commands in MySql for (i) to (iv)
and output for (v) to (vii).
Table: EXAM
No Name Stipend Subjet Average Division
1 Karan 400 English 68 FIRST
2 Aman 680 Mathematics 72 FIRST
3 Javed 500 Accounts 67 FIRST
4 Bishakh 200 Informatics 55 SECOND
5 Sugandha 400 History 35 THIRD
6 Suparna 550 Geography 45 THIRD

(i) To list the names of those students. who have obtained Division as FIRST in the ascending order of NAME.
Ans. SELECT Name FROM Exam
WHERE Division = 'FIRST'
ORDER BY Name;

(ii) To display a report listing NAME, SUBJECT and Annual stipend received assuming that the stipend column
has monthly stipend.
Ans. SELECT NAME, SUBJECT, STIPEND * 12
FROM EXAM;

(iii) To insert a new row in the table EXAM:


6 “Mohan”, 500, “English”, 73, “SECOND”;
Ans. INSERT INTO EXAM VALUES (6, “Mohan”, 500, “English”, 73, “SECOND”);
OR
INSERT INTO EXAM (NO, NAME, STIPEND, SUBJECT, AVERAGE, DIVISION)
VALUES (6, "Mohan", 500, "English", 73, "SECOND");

ALTER COMMAND
Sometimes we need to make changes in the definitions of existing table. This command is used to:
1. Adding column to a table
Alter table <table name> Add <column name> <data type> <size> [<constraint name>];
For e.g., To add a new column E-mail of datatype varchar and size 20 to the table employee.
Alter table employee Add Email varchar(20);

2. To redefine a column (data type, size, default value) using Modify command
Alter table <table name> Modify (column name newdata type (newsize));
For e.g., To modify column salary with new width of 30 characters in employee table.
Alter table employee modify salary varchar (30);

3. To change a column name


Alter table <table name> Change [column] old_col name new_col_name column_definition;
For e.g., To change the name of existing column Department to Dept.
Alter table employee Change Department Dept varchar (20);

4. To delete columns of a table.


Alter table <table name> Drop [<column name>];
For e.g., Alter table emp drop dname ;

Drop table command: To drop a table from a database.


Drop table <table name>
For e.g., drop table employee;

MODIFYING DATA WITH UPDATE COMMAND:


Update command specifies the rows to be changed using the Where clause, and the new data using the SET
keyword.
For e.g., 1) Change the salary to 5000 of all those employees whose salary is 3000.
Update employee SET Salary =5000 Where salary =3000;
2) Increase the salary of all employees by Rs.100
Update employee SET salary = salary +100;

DELETE COMMAND: Removes rows from a table.


Delete from <table name> [Where <predicate>];
For e.g., 1) To delete the records of employees whose salary is greater than 2000.
Delete from employee Where salary > 2000;
2) To remove all the contents of employee table, the command is:
Delete from employee;

You might also like