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

CS Module II MySQL Notes

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

CS Module II MySQL Notes

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

Introduction to MYSQL

Data- is a piece of information or collection of facts related to any entity


Database is a systematic collection of data it supports storage and manipulation of the
data that you have stored
What is a database management system :- It is a collection of programs which
enables users to access databases,manipulate data and represent data.

There are 4 basic DBMS


1. Hierarchical DBMS (HDBMS):- has a style of parent child relationship of storing
data. It has a structure like a tree with nodes representing records and branches
representing fields.

2. Network DBMS (NDBMS):- Supports many - to many relations, this may results
in complex structures.

3. Relational DBMS (RDBMS):- This type of DBMS defines database relationships


in the form of tables ,also known as relations.
4. Object-oriented DBMS:- This type supports storage of new data types. This data
to be stored in the form of objects.

SQL: It is a Structured Query Language


1)It is a standardized programming language which is used for managing relational
databases.
2)With SQL you can modify databases,add,update or delete rows of data ,retrieve
subjects of information from a database and many more.
3)Relational databases like MySQL,Oracle,Python Java use SQL

MySQL is basically a relational database management system, which works with tables
and then defines the relations between the tables. It is an open source software that
provides multiuser access so you can know that your many users can use this particular
DBMS and retrieve the data . It also supports a multi storage engine and works on
many platforms.
Common terminologies used is SQL
● Row(Record): Record is a collection of values or fields of a specific entity. Eg.
An employee, Salary account, etc.
● column(Field): A field refers to an area within a record which is reserved for a
specific piece of data. Eg. Employee ID.
● Table: Table is the collection of records of specific types. E.g. Employee table is
a collection of records related to all the employees.
● Query- It is a request for data or information from a database table or
combination of tables.

Relationships
A relational database contains tables that relate to another table by using a relationship.
The tables are connected by a common field. The relationships are defined as:
● One to Many: this is the most common type of a table relationship. For every
record in Table A, there are multiple records in Table B.
Example: There is a one to many relationship between the Customers table and Orders
table. A customer may have many orders in the Order table.
● Many to Many: For every record in Table A, there are multiple records in Table
B, and vice versa. In this case, a third table called a Join Table is created to
which will contain only unique values
Example: Many to Many relationship between Orders and Products with the table
ProductsOrders functioning as the Join Table. The table ProductsOrders holds all the
details about each order and what products it contains. Its primary key is a combination
of the primary key of the Orders and Products table.
● One to One – the rarest type of a table relationship. It is used for security and
organization to avoid empty fields that only apply to some records in a table.

SQL command categories


1) Data Definition Language (DDL) - Consists of commands that can be used to define
the database schema. (CREATE,DROP,ALTER,TRUNCATE,COMMENT,RENAME).
2)Data Manipulation Language - The SQL commands that deal with the manipulation of
data present in a database (SELECT,INSERT,UPDATE,DELETE etc.)
3)Data Control Language (DCL)- Includes commands which mainly deal with the
rights,permissions and other controls of the database system.(GRANT ,INVOKE).
4)Transaction Statements -Transaction statements are used to begin ,end and roll back
transaction.For example ROLLBACK,COMMIT statements.
Question based on Introduction to MYSQL
1)How many types of relationships are available? Name them
2)What is DML? Give an example of it.
3)What is a table?
4)Explain types of DBMS?
5) What is DBMS?
6) What is a Query?
7)Explain RDBMS

My SQL Basics
Rules for Database names ,table name and column name :-
1)It can be at most 64 characters long.
2)It should not be a keyword (SELECT,SHOW etc.)
3)It should be unique.
Data types:-
Character data
1) Character data:- Character data can be stored either as fixed length or variable
length .While defining a character column you have to specify the maximum size of any
string to be stored in the column.For example if you want to store strings upto 30
character then you should either use char(30) or varchar(30). The maximum length for
the char column is 255 bytes whereas for varchar it is 65,535.
If you assign a value to a CHAR or VARCHAR column that exceeds the column’s
maximum length ,then the value will not be accepted.
Values in CHAR and VARCHAR are sorted and compared in case-insensitive
fashion,unless the binary attribute was specified when the table was created.

Numeric data
2)Numeric data - Numeric means numbers and they can be positive, negative or zero
,with decimal points without decimal points . If the data is without decimal point then it is
integer and if it is with decimal point then it is real(float).

The table displays the allowable storage in bytes, the maximum and minimum values of
SIGNED and UNSIGNED integer data types.
Type Stora Minimum Minim Maximum Maximum
ge Value SIGNED um Value Signed Value
(byte Value Unsigned
s) Unsign
ed

TINYINT 1 -128 0 127 255

SMALLINT 2 -32768 0 32767 65535

MEDIUMINT 3 -8388608 0 8388607 16777215

INT 4 -2147483648 0 2147483647 4294967295

BIGINT 8 -263 0 263-1 264-1

TINYINT-
CREATE TABLE StudentGroup(id tinyint AUTO_INCREMENT,Name varchar(255) NOT
NULL,Surname varchar(255) NOT NULL,Grade tinyint(4) UNSIGNED,PRIMARY KEY
(id));
INSERT INTO StudentGroup (id, Name, Surname, Grade)VALUES (1, 'John', 'Smith',5);

SMALLINT-
CREATE TABLE SmallintTable(ID smallint AUTO_INCREMENT,value_1 smallint
SIGNED,value_2 smallint(6) UNSIGNED,PRIMARY KEY (id));
INSERT INTO SmallintTable (ID, value_1, value_2)VALUES (1, -768, 0);

MEDIUMINT-
CREATE TABLE MediumIntTable(ID mediumint AUTO_INCREMENT,value_1
mediumint,value_2 mediumint(6) UNSIGNED,PRIMARY KEY (ID));

INSERT INTO MediumIntTable (ID, value_1, value_2) VALUES (5, -1234567, 1234567);

BIGINT-
create a table
CREATE TABLE BigIntTable(ID bigint AUTO_INCREMENT,value_1 bigint,value_2
bigint(20) UNSIGNED,PRIMARY KEY (ID));

-- insert data
INSERT INTO BigIntTable (ID, value_1, value_2)VALUES (2, -72036854775808,
9223372036854775808);

UNSIGNED-INTEGER data types can be UNSIGNED and SIGNED. UNSIGNED can


store only zero and positive numbers in a column. If the values in the column never use
negative numbers or when there is a need in using a larger upper numeric range for the
column, you can set UNSIGNED
SIGNED-It can allow zero, positive, and negative numbers.

ZEROFILL-If you need to replace spaces with zeros, you can use the ZEROFILL
attribute for the MySQL INT UNSIGNED column. For example, for the INT(3) ZEROFILL
column with the value 1, the result you retrieve will be 001.
3)TEMPORAL DATA (Date and time)-

Type Default format Storage


required

DATE YYYY-MM-DD 3 bytes

DATETIME YYYY-MM-DD HH:MM:SS 8 bytes

TIMESTAMP YYYY-MM-DD HH:MM:SS 4 bytes

YEAR YYYY 1 bytes

Time HH:MM:SS or HHH:MM:SS 3 bytes

Datetime-Allowable values from year 1000 to year 9999.


Timestamp- Allowable values from year 1970 to year 2037.

Column Specification attributes.


a)Null:-The SQL NULL is the term used to represent a missing value. A NULL value in
a table is a value in a field that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that
a NULL value is different from a zero value or a field that contains spaces.
b)Not null:-By default, a column can hold NULL values. If you do not want a column to
have a NULL value, then you need to define such a constraint on this column specifying
that NULL is now not allowed for that column.
A NULL is not the same as no data, rather, it represents unknown data.
c)Default value:-The DEFAULT constraint provides a default value to a column when
the INSERT INTO statement does not provide a specific value.
Example:-For example, the following SQL creates a new table called CUSTOMERS and
adds five columns. Here, the SALARY column is set to 5000.00 by default, so in case
the INSERT INTO statement does not provide a value for this column, then by default
this column would be set to 5000.00.
d)Auto_increment:-Auto-increment is a concept in SQL which automatically generates
the unique number in the field when the new row is entered into the table. This feature
is generally used for the Primary Key field, where we need to create a unique value for
every record.
e)Primary key:-A primary key is a field in a table which uniquely identifies each
row/record in a database table. Primary keys must contain unique values. A primary key
column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields.
When multiple fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records
having the same value of that field(s).
f)Foriegn key:-A foreign key is a key used to link two tables together. This is sometimes
also called a referencing key.
A Foreign Key is a column or a combination of columns whose values match a Primary
Key in a different table.The relationship between 2 tables matches the Primary Key in
one of the tables with a Foreign Key in the second table.
If a table has a primary key defined on any field(s), then you cannot have two records
having the same value of that field(s).
g)Unique:-The UNIQUE Constraint prevents two records from having identical values in
a column. In the CUSTOMERS table, for example, you might want to prevent two or
more people from having an identical age.

(1)CREATE:- This statement is used to create a database ,table etc .with a given name
. Remember, the1 database name should be unique. CREATE statements with
constraints like KEY,CHECK,DEFAULT,ALTER and DROP statements.

A)Creating Table -CREATE TABLE command

It defines a each column of the table uniquely. Each column has minimum three
attributes: name, datatype and size( column width).Each column definition is
separated by comma and at last ends with semicolon.

Rules for creating table:- 1)Name should be maximum 30 characters long and can
have alphabets from A-Z and a-z and digits from 0-9.

2)Name should begin with an alphabet and should be a keyword

3)The only special character used in name is underscore(_).

Example:- Create Database Office;

Create table Manager (column data types);


(2) DESCRIBING STRUCTURE OF A TABLE
DESCRIBE command is used to describe the structure of a table along with the
table name, all columns and their data types, whether a primary key is assigned
or not. The general syntax is
DESCRIBE <table
name>; e.g. DESCRIBE
EMP;
(3) MODIFYING STRUCTURE OF A TABLE
The structure of a table can be modified by using ALTER TABLE command. It allows
• To change the structure of an existing table
• To add or delete columns,
• To create or destroy indexes,
• To change the data type of existing columns using
ALTER TABLE <table name> ADD (<new col name1> <data type 1>(size1), <new
col name2> <data type 2>(size2));
ALTER TABLE <table name> DROP COLUMN (<col name>);
ALTER TABLE <table name> MODIFY(<col name> <new data type>(new size));

(4) Adding data with INSERT statement,

(A) INSERTING VALUES INTO THE TABLE:- Once a table is created, to insert the
values row by row, we use a command INSERT INTO using the syntax

INSERT INTO <table name> (<col name1>,<col name2>..)


VALUES(<expression/value1>, <expression/value2>

For example:INSERT INTO STUDENT(SNAME, ROLL_NO) VALUES(‘ADESH’,


101); INSERT INTO STUDENT(SNAME, ROLL_NO) VALUES(‘VANITA’, 102);

INSERT INTO EMP(EMP_NAME,TEL_NO,ADDRESS,


JDATE,DESIGNATION) VALUES(MIHIR
JOSHI’,9822234561’MUMBAI’,’01-JUL-05’,’SOFTWARE
DEVELOPER’);

(B) INSERTING DATA INTO A TABLE FROM ANOTHER TABLE:- In addition to


inserting the data one row at a time into a table, it is possible to populate a table with
the data that already exists in another table using the syntaxINSERT INTO <table
name2> SELECT <col name>,>col name2>..> FROM <table name1>;

Which allows inserting the data of selected columns from table 1 to table 2. For
example to create a table emp_new with only two columns from emp with columns
(EMP_NAME,TEL_NO,ADDRESS, JDATE,DESIGNATION) and having 10 records we
write a command as

INSERT INTO EMP_NEW SELECT EMP_NAME,TEL_NO FROM EMP:

Which will create a table EMP_ NEW with two columns EMP_NAME and TEL_NO and
will insert the name and tel nos of 10 persons from table EMP.

(5) SHOW:- This statement is used to see what we are looking for. Example SHOW
DATABASES: , SHOW TABLES;
(6) USE:- This statement is used to open an existing database from SQL server.

Command Syntax Description

ALTER TABLE table_name ADD It is used to add columns


ALTER table column_name datatype; to a table in a database

AND SELECT column_name(s)FROM It is an operator that is


table_nameWHERE column_1 = used to combine two
value_1 AND column_2 = value_2; conditions

AS SELECT column_name AS It is a keyword in SQL that


‘Alias’FROM table_name; is used to rename a
column or table using an
alias name

AVG SELECT It is used to aggregate a


AVG(column_name)FROM numeric column and
table_name; return its average

BETWEEN SELECT column_name(s)FROM It is an operation used to


table_nameWHERE column_name filter the result within a
BETWEEN value_1 AND value_2; certain range

CASE SELECT It is a statement used to


column_name,CASEWHEN create different outputs
condition THEN ‘Result_1’WHEN inside a SELECT
condition THEN ‘Result_2’ELSE statement
‘Result_3’ENDFROM table_name;

COUNT SELECT It is a function that takes


COUNT(column_name)FROM the name of a column as
table_name; an argument and counts
the number of rows when
the column is not NULL

Create TABLE CREATE TABLE table_name ( It is used to create a new


column_1 datatype, column_2 table in a database and
datatype, column_3 datatype); specify the name of the
table and columns inside it

DELETE DELETE FROM It is used to remove the


table_nameWHERE some_column rows from a table
= some_value;
GROUP BY SELECT column_name, It is a clause in SQL used
COUNT(*)FROM for aggregate functions in
table_nameGROUP BY collaboration with the
column_name; SELECT statement

HAVING SELECT column_name, It is used in SQL because


COUNT(*)FROM the WHERE keyword
table_nameGROUP BY cannot be used in
column_nameHAVING COUNT(*) > aggregating functions
value;

INNER JOIN SELECT column_name(s)FROM It is used to combine rows


table_1JOIN table_2 ON from different tables if the
table_1.column_name = Join condition goes TRUE
table_2.column_name;

INSERT INSERT INTO table_name It is used to add new rows


(column_1, column_2, column_3) to a table
VALUES (value_1, ‘value_2’,
value_3);

IS NULL/ IS NOT SELECT column_name(s)FROM It is an operator used with


NULL table_nameWHERE column_name the WHERE clause to
IS NULL; check for the empty
values

LIKE SELECT column_name(s)FROM It is a special operator


table_nameWHERE column_name used with the WHERE
LIKE pattern; clause to search for a
specific pattern in a
column

LIMIT SELECT column_name(s)FROM It is a clause to specify the


table_nameLIMIT number; maximum number of rows
the result set must have

MAX SELECT It is a function that takes a


MAX(column_name)FROM number of columns as an
table_name; argument and returns the
largest value among them

MIN SELECT MIN(column_name)FROM It is a function that takes a


table_name; number of columns as an
argument and returns the
smallest value among
them
OR SELECT column_nameFROM It is an operator that is
table_nameWHERE column_name used to filter the result set
= value_1 OR column_name = to contain only the rows
value_2; where either condition is
TRUE

ORDER BY SELECT column_nameFROM It is a clause used to sort


table_nameORDER BY the result set by a
column_name ASC | DESC; particular column either
numerically or
alphabetically

OUTER JOIN SELECT column_name(s)FROM It issued to combine rows


table_1LEFT JOIN table_2 ON from different tables even
table_1.column_name = if the condition is NOT
table_2.column_name; TRUE

ROUND SELECT ROUND(column_name, It is a function that takes


integer)FROM table_name; the column name and an
integer as an argument
and rounds the values in a
column to the number of
decimal places specified
by an integer

SELECT SELECT column_name FROM It is a statement that is


table_name; used to fetch data from a
database

SELECT SELECT DISTINCT It is used to specify that


DISTINCT column_nameFROM table_name; the statement is a query
that returns unique values
in specified columns

SUM SELECT It is a function used to


SUM(column_name)FROM return the sum of values
table_name; from a particular column

UPDATE UPDATE table_nameSET It is used to edit rows in a


some_column = table
some_valueWHERE some_column
= some_value;

WHERE SELECT column_name(s)FROM It is a clause used to filter


table_nameWHERE column_name the result set to include
operator value; the rows where the
condition is TRUE
WITH WITH temporary_name AS It is used to store the
(SELECT *FROM result of a particular query
table_name)SELECT *FROM in a temporary table using
temporary_nameWHERE an alias
column_name operator value;

Pattern matching

Pattern Meaning

‘A%’ Starting with A or a

‘%B’ Ending with B

‘%A%’ Contains h or H anywhere (can be first ,can be at the middle


somewhere or can be at last)

‘-----’ Contain 5 letters only

‘--N--’ Total 5 characters only, out of which 3rd character is N or n

‘-a%’ Second character should be A or a

‘--a%’ Third character should be A or a

‘%a-’ Second last character should be A or a

‘%a--’ Third last character should be A or a

‘-a%e’ Second character should be A or a and last character e or E


SQL is case insensitive by default. If you want to make it case sensitive then you
should use the BINARY key word in your command.

Questions based on SQL Basics.

1)What are the different data types available in SQL?

2)What is the difference between CHAR and VARCHAR?

3)What is the primary key?

4) What is foreign key?

5) What do you understand about AUTO_INCREMENT?

6)What do you mean by ‘%S’?

7)What is the command to display all the records ending with the alphabet E?

8)What do you understand about NULL?

9)Explain Numeric datatype.

10)What is the difference between DELETE and DROP Command?

11)What is the use of the DESCRIBE command?

12)When to use the ALTER command?

13) What is the difference between the Update and Modify command?

14) What is the difference between SELECT* and SELECT?

15) What do you understand by UNSIGNED?

My SQL BUILT IN FUNCTIONS


STRING FUNCTION-The built-in functions which take an input string and return an
output string are called string functions.Some of the important string functions are as
follows:

Sr.No. Function & Description

1 CHAR_LENGTH()- Returns number of characters in argument

2 CHAR()= Returns the character for each integer passed

3 CHARACTER_LENGTH()= A synonym for CHAR_LENGTH()

4 CONCAT_WS()= Returns concatenate with separator

5 CONCAT() =Returns concatenated string

6 CONV()= Converts numbers between different number bases

FORMAT()
7
Returns a number formatted to specified number of decimal places
INSERT()

8
Inserts a substring at the specified position up to the specified number of
characters

INSTR()
9
Returns the index of the first occurrence of substring

LCASE()
10
Synonym for LOWER()

11 LEFT():- Returns the leftmost number of characters as specified

12 LENGTH():- Returns the length of a string in bytes

13 LOWER():-Returns the argument in lowercase

14 LTRIM():- Removes leading spaces

15 MID():- Returns a substring starting from the specified position

16 REPEAT():-Repeats a string the specified number of times


17 REPLACE():-Replaces occurrences of a specified string

18 REVERSE():-Reverses the characters in a string

19 RIGHT():-Returns the specified rightmost number of characters

20 RTRIM():- Removes trailing spaces

21 TRIM() :- removes leading and trailing spaces.

22 UCASE():- Synonym for UPPER()

23 UPPER():- Converts to uppercase

DATE AND TIME FUNCTION-

DAY(date)
The DAY() is a synonym for the DAYOFMONTH() function

SELECT DAYNAME('1998-02-05');

Output :-| Thursday

MONTH(date)-Returns the month for date, in the range 0 to 12.


SELECT MONTH('1998-02-03');

Output- 2
MONTHNAME(date) :-Returns the full name of the month for a date.
mysql> SELECT MONTHNAME('1998-02-05');

Output:- | February

YEAR(date)-Returns the year for date, in the range 1000 to 9999, or 0 for the .zero.
date.
SELECT YEAR('98-02-03');

Output- 1998

TIME(expr):-Extracts the time part of the time or datetime expression expr and returns it
as a string.
SELECT TIME('2003-12-31 01:02:03');

Output -| 01:02:03 |

CURDATE() :-Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD


format, depending on whether the function is used in a string or in a numeric context.

SELECT CURDATE();

Output-| 1997-12-15

NUMERIC FUNCTION-

ABS(X)- It returns the absolute value of x. If x is negative then it is multiplied by -1


otherwise x remains as it is.

SELECT ABS(-2);

Output :- 2

MOD(N ,M):- It returns the remainder of N divided by M.

SELECT MOD(34,10);

Output :- 4

POWER(X,Y):-These two functions return the value of X raised to the power of Y.


SELECT POWER(3,3);

Output:-

POWER(3,3) | 27

ROUND(X,D):-This function returns X rounded to the nearest integer. If a second


argument, D, is supplied, then the function returns X rounded to D decimal places. D
must be positive or all digits to the right of the decimal point will be removed. Consider
the following example −
SELECT ROUND(5.693893);
Output
ROUND(5.693893) |
|6

SQRT(X) :-This function returns the non-negative square root of X. Consider the
following example −
SQL>SELECT SQRT(49);
Output:
| SQRT(49) |
|7 |

Questions based on MY SQL BUILT IN FUNCTIONS

1)Which function is used to find the size of the string ?

2)Which function is used to convert upper alphabets into lowercase?

3)Which function is used to find the remainder of a division?

4)What is the output of Select Round (4.678)?

5)Give examples of LTRIM and RTRIM.

You might also like