Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Basic Operations With MySQL - Part 1

The document provides an introduction to Structured Query Language (SQL), covering basic database concepts, types of SQL statements, and MySQL data types. It explains the structure of databases, tables, records, and fields, along with operations for creating, modifying, and managing data. Additionally, it details the syntax for various SQL commands and data types used in MySQL.

Uploaded by

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

Basic Operations With MySQL - Part 1

The document provides an introduction to Structured Query Language (SQL), covering basic database concepts, types of SQL statements, and MySQL data types. It explains the structure of databases, tables, records, and fields, along with operations for creating, modifying, and managing data. Additionally, it details the syntax for various SQL commands and data types used in MySQL.

Uploaded by

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

Introduction to Structured Query Language

BASIC DATABASE CONCEPTS:

➢ All DBMS systems store user data in the form of tables.


➢ A is a 2-dimensional matrix that consists of rows and columns. Each
column consists of a cell which is created by data base administrator.
➢ A is also called as field. A number of such fields placed horizontal
plane is called a record or row or tuple.
➢ The characteristics of an entity are called or or .
➢ A number of rows, of equal length placed on bellow the other is called a
table.

Type of SQL Statements


Type of SQL statements are divided into four basic different categories:
⚫ Data definition language (DDL),
⚫ Data manipulation language (DML),
⚫ Data Control Language (DCL),
⚫ Transaction Control Language (TCL)

➢ The manages table and index structure.


The most basic items of DDL are the CREATE, ALTER, RENAME and DROP
statements:
◼ CREATE creates an object (a table, for example) in the database.
◼ DROP deletes an object in the database, usually irretrievably.
◼ ALTER modifies the structure an existing object in various ways—for
example, adding a column to an existing table.
◼ TRUNCATE removes all table records including allocated table spaces.
◼ RENAME renames the database/table.

➢ The is the subset of SQL used to add,


update and delete data.
➢ The acronym CRUD refers to all of the major functions that need to be
implemented in a relational database application to consider it complete.
➢ Each letter in the acronym can be mapped to a standard SQL statement:
Operation SQL Description

Create INSERT INTO inserts new data into a database

Read (Retrieve) SELECT extracts data from a database

Update UPDATE updates data in a database

Delete (Destroy) DELETE deletes data from a database

➢ The statements are use to give privileges to


access limited data.
◼ GRANT Gives privileges to user for accessing database data.
◼ REVOKE Take back for given privileges.

➢ statements are used to apply the changes


permanently save into database.
◼ COMMIT Permanent work save into database.
◼ ROLLBACK Restore database to original form since the last COMMIT.
◼ SAVEPOINT Create SAVEPOINT for later use ROLLBACK the new
changes.

➢ Field (Column): A single piece of information. Could be a name, or a


number. In some cases, it may even be a null or empty value.

➢ Record (Row): A collection of related fields. A number of pieces of


information that relate to the same object. For example: If we keep records
on an employee, we might have their name, address, social security
number, phone number, etc…Each piece of the information relates back to
one employee. This would be the employee’s record.

➢ Table (File): A collection of related records. If we put all the employee


records together, you have a table of employees.

➢ Database: A collection of tables. If you were keeping the company records,


you might have a table for employees, a table for customers, and another
for sales records. All these tables would be combined as a database.

➢ Relational Database: A collection of related tables.


Basic Operations with MySQL

⚫ Showing existing databases - Displays all the databases currently existing


in the system.

Syntax: SHOW DATABASES ;


Example:

⚫ Creating a new database - Creates a new empty database with the name
dbname.

Syntax : CREATE DATABASE dbname;


Example:

⚫ Connecting to a database : First, pick the database in which you want to


create the table with a CONNECT statement:

Syntax: CONNECT dbame;

Example: CONNECT pets;

Now you are inside the space provided for the db dbname. At this
moment the user can create tables.

⚫ Deleting a database: Drop command is used to delete any object present in


the database.
Syntax for deleting a database is ,

Syntax: DROP DATABASE dbname;

Example: DROP DATABASE pets;

MySQL Data Types


Each column in a database table is required to have a name and a data type.

An SQL developer must decide what type of data that will be stored inside each
column when creating a table. The data type is a guideline for SQL to
understand what type of data is expected inside of each column, and it also
identifies how SQL will interact with the stored data.
The data type in MySQL with the following characteristics:
o The type of values (fixed or variable) it represents.
o The storage space it takes is based on whether the values are a fixed-
length or variable length.
o Its values can be indexed or not.
o How MySQL performs a comparison of values of a particular data type.

In MySQL there are three main data types: string, numeric, and date and time.

1. String Data Types

Data type Description

CHAR(size) ₒ A FIXED length string (can contain letters,


numbers, and special characters).
ₒ The size can be from 0 to 255.
ₒ Default is 1

VARCHAR(size) ₒ A VARIABLE length string (can contain letters,


numbers, and special characters).
ₒ The size can be from 0 to 65535

BINARY(size) ₒ Equal to CHAR(), but stores binary byte strings.


ₒ The size parameter specifies the column length in
bytes.
ₒ Default is 1

VARBINARY(size) ₒ Equal to VARCHAR(), but stores binary byte strings.


ₒ The size parameter specifies the maximum column
length in bytes.

TINYBLOB ₒ For BLOBs (Binary Large OBjects).


ₒ Max length: 255 bytes

TINYTEXT ₒ Holds a string with a maximum length of 255


characters

TEXT(size) ₒ Holds a string with a maximum length of 65,535


bytes

BLOB(size) ₒ For BLOBs (Binary Large OBjects).


ₒ Holds up to 65,535 bytes of data

MEDIUMTEXT ₒ Holds a string with a maximum length of


16,777,215 characters

MEDIUMBLOB ₒ For BLOBs (Binary Large OBjects).


ₒ Holds up to 16,777,215 bytes of data
LONGTEXT ₒ Holds a string with a maximum length of
4,294,967,295 characters

LONGBLOB ₒ For BLOBs (Binary Large OBjects).


ₒ Holds up to 4,294,967,295 bytes of data

ENUM(val1, val2, ₒ A string object that can have only one value, chosen
val3, ...) from a list of possible values.
ₒ You can list up to 65535 values in an ENUM list.
ₒ If a value is inserted that is not in the list, a blank
value will be inserted.
ₒ The values are sorted in the order you enter them

SET(val1, val2, ₒ A string object that can have 0 or more values,


val3, ...) chosen from a list of possible values.
ₒ You can list up to 64 values in a SET list

2. Numeric Data Types

Data type Description

BIT(size) ₒ A bit-value type.


ₒ The number of bits per value is specified in size.
ₒ The size parameter can hold a value from 1 to 64.
ₒ The default value for size is 1.

TINYINT(size) ₒ A very small integer. Signed range is from -128 to 127.


ₒ Unsigned range is from 0 to 255.
ₒ The size parameter specifies the maximum display
width (which is 255)

BOOL ₒ Zero is considered as false, nonzero values are


considered as true.

BOOLEAN ₒ Equal to BOOL

SMALLINT(size) ₒ A small integer.


ₒ Signed range is from -32768 to 32767.
ₒ Unsigned range is from 0 to 65535.
ₒ The size parameter specifies the maximum display
width (which is 255)

MEDIUMINT(size) ₒ A medium integer. Signed range is from -8388608 to


8388607.
ₒ Unsigned range is from 0 to 16777215.
ₒ The size parameter specifies the maximum display
width (which is 255)

INT(size) ₒ A medium integer. Signed range is from -2147483648


to 2147483647.
ₒ Unsigned range is from 0 to 4294967295.
ₒ The size parameter specifies the maximum display
width (which is 255)

INTEGER(size) ₒ Equal to INT(size)

BIGINT(size) ₒ A large integer. Signed range is from -


9223372036854775808 to 9223372036854775807.
ₒ Unsigned range is from 0 to 18446744073709551615.
ₒ The size parameter specifies the maximum display
width (which is 255)

FLOAT(size, d) ₒ A floating point number.


ₒ The total number of digits is specified in size.
ₒ The number of digits after the decimal point is
specified in the d parameter.
ₒ This syntax is deprecated in MySQL 8.0.17, and it will
be removed in future MySQL versions

FLOAT(p) ₒ A floating point number.


ₒ MySQL uses the p value to determine whether to use
FLOAT or DOUBLE for the resulting data type.
ₒ If p is from 0 to 24, the data type becomes FLOAT().
ₒ If p is from 25 to 53, the data type becomes
DOUBLE()

DOUBLE(size, d) ₒ A normal-size floating point number. The total number


of digits is specified in size. The number of digits after
the decimal point is specified in the d parameter

DOUBLE
PRECISION(size, d)

DECIMAL(size, d) ₒ An exact fixed-point number.


ₒ The total number of digits is specified in size.
ₒ The number of digits after the decimal point is
specified in the d parameter.
ₒ The maximum number for size is 65.
ₒ The maximum number for d is 30.
ₒ The default value for size is 10. The default value
for d is 0.

DEC(size, d) ₒ Equal to DECIMAL(size,d)

Note: All the numeric data types may have an extra option: UNSIGNED or
ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values
for the column. If you add the ZEROFILL option, MySQL automatically also
adds the UNSIGNED attribute to the column.
3. Date and Time Data Types

Data type Description

DATE ₒ A date. Format: YYYY-MM-DD.


ₒ The supported range is from '1000-01-01' to '9999-12-
31'

DATETIME(fsp) ₒ A date and time combination.


ₒ Format: YYYY-MM-DD hh:mm:ss.
ₒ The supported range is from '1000-01-01 00:00:00' to
'9999-12-31 23:59:59'.
ₒ Adding DEFAULT and ON UPDATE in the column
definition to get automatic initialization and updating to
the current date and time

TIMESTAMP(fsp) ₒ A timestamp.
ₒ TIMESTAMP values are stored as the number of seconds
since the Unix epoch ('1970-01-01 00:00:00' UTC).
ₒ Format: YYYY-MM-DD hh:mm:ss.
ₒ The supported range is from '1970-01-01 00:00:01' UTC
to '2038-01-09 03:14:07' UTC.
ₒ Automatic initialization and updating to the current date
and time can be specified using DEFAULT
CURRENT_TIMESTAMP and ON UPDATE
CURRENT_TIMESTAMP in the column definition

TIME(fsp) ₒ A time.
ₒ Format: hh:mm:ss.
ₒ The supported range is from '-838:59:59' to '838:59:59'

YEAR ₒ A year in four-digit format.


ₒ Values allowed in four-digit format: 1901 to 2155, and
0000.
ₒ MySQL 8.0 does not support year in two-digit format.

CREATE TABLE Statement

⚫ The CREATE TABLE statement is used to create a new table in a database.

Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
.… );
Where,

ₒ The column parameters specify the names of the columns of the table.

ₒ The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).

Example: Create a table called "Persons" that contains five columns:


PersonID, LastName, FirstName, Address, and City

CREATE TABLE Persons (


PersonID int,
LastName varchar(25),
FirstName varchar(25),
Address varchar(55),
City varchar(20)
);

⚫ CREATE TABLE Using Another Table

A copy of an existing table can also be created using CREATE TABLE.


The new table gets the same column definitions. All columns or specific
columns can be selected.

Where Clause:

ₒ If you create a new table using an existing table, the new table will be filled
with the existing values from the old table, if the where clause is skipped.

ₒ If where clause is included, then the records satisfying the where clause
condition will be inserted into the new table.

ₒ If the where clause condition is not satisfied then none of the records will
be inserted into the new table. Thus an empty table will be created.

Syntax:
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE <condition>;

The following SQL creates a new table called "TestTables" (which is a


copy of the "Customers" table):

CREATE TABLE TestTable AS


SELECT customername, contactname
FROM customers;
⚫ Show Tables

SHOW TABLES allows you to get all the tables at your fingertips.

Syntax: SHOW TABLES ;

MySQL returns the results in a table with one column. The tables are
ordered in alphabetical order.

⚫ Show tables with the LIKE pattern

The statement to return only the names of those databases that satisfies
the pattern.

Syntax : SHOW TABLES [ LIKE ‘pattern’ ];

The query will look as follows:


Example: SHOW TABLES LIKE ‘a%’ ;
This query will display the tables starting with letter ‘a’.

⚫ See the table structure:


We can use the following command to see the information or structure of
the newly created table:

SYNTAX: DESCRIBE Tablename; OR DESC Tablename;

Example:

ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns
in an existing table. The ALTER TABLE statement is also used to add and drop
various constraints on an existing table.

⚫ ALTER TABLE - ADD Column

1. To add a column in a table, use the following syntax:

Syntax: ALTER TABLE table_name


ADD column_name datatype;
Example: The following SQL adds an "Email" column to the
"Customers" table:

ALTER TABLE Customers


ADD Email varchar(255);

2. To change the data type of a column in a table, use the following


syntax:
Syntax: ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ];

Example: Add a new column “SSN” at the beginning of the Employee


table.

ALTER TABLE Employee


ADD SSN int (10)
FIRST;

Example: Add a new column “Delivery_date” after the column Order_id if


the Orders table.
ALTER TABLE Orders
ADD Delivery_date Date

AFTER Order_id;

⚫ ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):
Syntax: ALTER TABLE table_name
DROP COLUMN column_name;
The following SQL deletes the "Email" column from the "Customers"
table:
ALTER TABLE Customers
DROP COLUMN Email;

⚫ ALTER TABLE - MODIFY COLUMN

The MODIFY command is used to change the column definition of the


table.
Syntax: ALTER TABLE table_name
MODIFY column_name column_definition
[ FIRST | AFTER column_name ];
Example: To change the data type of the column named "DateOfBirth"
in the "Persons" table.
ALTER TABLE Persons
MODIFY DateOfBirth year;

RENAME TABLE Statement


RENAME TABLE renames one or more tables. You must have ALTER
and DROP privileges for the original table, and CREATE and INSERT privileges
for the new table.

Syntax: RENAME TABLE old_table TO new_table;

Example: Rename the relation Employee to Emp_Master.

RENAME TABLE Employee TO Emp_Master;

RENAME TABLE, unlike ALTER TABLE, can rename multiple tables


within a single statement:
Syntax: RENAME TABLE old_table1 TO new_table1,
old_table2 TO new_table2, old_table3 TO new_table3;

MySQL Rename Column


MySQL provides a useful syntax that can rename one or more columns in the
table. Few privileges are essential before renaming the column, such as ALTER
and DROP statement privileges.

MySQL can rename the column name in two ways:

• Using the CHANGE statement


• Using the RENAME statement

Using the CHANGE Statement:

The following are the syntax that illustrates the column rename using the
CHANGE statement:

ALTER TABLE table_name

CHANGE COLUMN old_column_name new_column_name Data Type;

This syntax can also allow us to change the column's data types.

Example: Change the column ‘acct char(5) ‘ of customer table to


‘account varchar(10)’.

ALTER TABLE customer


CHANGE COLUMN acct account varchar(10);

Using the RENAME Statement:


To remove the drawback of a CHANGE statement, MySQL proposed the
following syntax that illustrates the changing of the column name using
a RENAME statement:

ALTER TABLE table_name


RENAME COLUMN old_column_name TO new_column_name;

Example: Rename the column account to account_no of customer table.

ALTER TABLE customer


RENAME COLUMN account to account_no;

DROP TABLE Statement


⚫ The DROP TABLE statement is used to drop an existing table in a database.
Syntax: DROP TABLE Tblname;

Example: Delete the table Employee along with the data.

DROP TABLE Employee;

⚫ TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data inside a
table, but not the table itself. It works in the same way as a DELETE command
without using a WHERE clause that deletes complete rows from a table.

However, the TRUNCATE command is more efficient as compared to the


DELETE command because it removes and recreates the table instead of
deleting single records one at a time. Since this command internally drops the
table and recreates it, the number of rows affected by the truncate statement is
zero, unlike the delete statement that returns the number of deleted rows.

Syntax: TRUNCATE TABLE table_name;

The following points must be considered while using the TRUNCATE command:
✓ We cannot use the WHERE clause with this command so that filtering of
records is not possible.
✓ We cannot rollback the deleted data after executing this command because
the log is not maintained while performing this operation.
✓ We cannot use the truncate statement when a table is referenced by a
foreign key or participates in an indexed view.
✓ The TRUNCATE command doesn't fire DELETE triggers associated with the
table that is being truncated because it does not operate on individual rows.

Example: Delete all the data from the Product_Details table.


TRUNCATE TABLE Product_Details;

INSERT Statement
MySQL INSERT statement is used to store or add data in MySQL table within
the database. We can perform insertion of records in two ways using a single
query in MySQL:
• Insert record in a single row
• Insert record in multiple rows
Syntax: To insert a single record.

INSERT INTO table_name ( field1, field2,...fieldN )


VALUES ( value1, value2,...valueN );

Syntax: To insert multiple records within a single command.


INSERT INTO table_name VALUES
( value1, value2,...valueN ),
( value1, value2,...valueN ),
...........
( value1, value2,...valueN );

NOTE:

• Field name is optional if the values are to be inserted to all the


columns in the order as per table creation.

• If we want to specify partial values, the field name is mandatory.

• It also ensures that the column name and values should be the
same. Also, the position of columns and corresponding values must
be the same.

• Numeric valued data types do not need to be enclosed within single


quotes, whereas String and Date datatypes values, must be enclosed
with single quotes.
UPDATE Statement
There may be a requirement where the existing data in a MySQL table needs to
be modified. You can do so by using the SQL UPDATE command. This will
modify any field value of any MySQL table.

Syntax: UPDATE table_name

SET field1 = new-value1, field2 = new-value2

[WHERE Clause];

◆ You can update one or more field altogether.


◆ You can specify any condition using the WHERE clause.
◆ You can update the values in a single table at a time.

Example: Dirk Smith’s birthday is today, add 1 to his age.

UPDATE employees
SET age = age+1
WHERE firstname = 'Dirk' and lastname='Smith';

DELETE Statement

If you want to delete a record from any MySQL table, then you can use the SQL
command DELETE FROM.

Syntax: DELETE FROM table_name [WHERE Clause];

⚫ If the WHERE clause is not specified, then all the records will be deleted
from the given MySQL table.
⚫ You can specify any condition using the WHERE clause.
⚫ You can delete records in a single table at a time.

Example:

A. Delete all the records from the Client table.

DELETE FROM Client;

B. Delete the records from the Client table whose last names are ‘Kumar’.

DELETE FROM Client

WHERE lastname = 'Kumar';


EXERCISE # 1:

1. Create a Employees table that will contain the following information about
your new employees: firstname, lastname, title, age, and salary(5,2)

2. Add the following columns to the Employees table: Department, Designation,


Branch.

3. Add the column EmpID as first column.

4. Add the column MGRID after Department column.

5. Drop the column Branch.

6. Increase the size of the column salary from (5,2) to (10,2).

7. Insert 10 records into the table.

8. Create a table EmpSal (EmpID, basic) from Employees (EmpID, Salary) table.

9. Alter the table by adding the columns DA, HRA, Gross, PF, IT and Net.

10. Create a table named EmpLoc with columns EmpID, Department with same
structure as Employees table but without any records.

11. Update the table EmpSal as per the following instructions:

a) DA is 20% of basic salary.

b) HRA is 15% basic salary.

c) Gross is sum of basic, DA and HRA.

d) PF is 10% if basic is greater than 20000 else 200.

e) IT is 500 for all employees.

f) Net is computed as Gross - (PF+IT).

12. Delete the record with employee named ‘Rajath Kumar’.

13. Rename Employees table as MyEmp.



You might also like