0% found this document useful (0 votes)
6 views25 pages

MYSQL Practical1 Students

The document provides a comprehensive overview of commonly used MySQL queries for database management, including creating databases, tables, and performing CRUD operations. It also explains MySQL constraints, detailing their types, creation, and examples such as NOT NULL, UNIQUE, CHECK, and FOREIGN KEY. Additionally, it includes practical examples of inserting records into tables and demonstrates how to enforce data integrity through constraints.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

MYSQL Practical1 Students

The document provides a comprehensive overview of commonly used MySQL queries for database management, including creating databases, tables, and performing CRUD operations. It also explains MySQL constraints, detailing their types, creation, and examples such as NOT NULL, UNIQUE, CHECK, and FOREIGN KEY. Additionally, it includes practical examples of inserting records into tables and demonstrates how to enforce data integrity through constraints.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

MySQL Queries

A list of commonly used MySQL queries to create database, use database, create table, insert
record, update record, delete record, select record, truncate table and drop table are given below.

1) MySQL Create Database


MySQL create database is used to create database. For example

1. create database db1;

2) MySQL Select/Use Database


MySQL use database is used to select database. For example

1. use db1;

3) MySQL Create Query


MySQL create query is used to create a table, view, procedure and function. For example:

1. CREATE TABLE customers


2. (id int(10),
3. name varchar(50),
4. city varchar(50),
5. PRIMARY KEY (id )
6. );

4) MySQL Alter Query


MySQL alter query is used to add, modify, delete or drop colums of a table. Let's see a query to
add column in customers table:

1. ALTER TABLE customers


2. ADD age varchar(50);

5) MySQL Insert Query


MySQL insert query is used to insert records into table. For example:

1. insert into customers values(101,'rahul','delhi');


6) MySQL Update Query
MySQL update query is used to update records of a table. For example:

1. update customers set name='bob', city='london' where id=101;

7) MySQL Delete Query


MySQL update query is used to delete records of a table from database. For example:

1. delete from customers where id=101;

8) MySQL Select Query


Oracle select query is used to fetch records from database. For example:

1. SELECT * from customers;

9) MySQL Truncate Table Query


MySQL update query is used to truncate or remove records of a table. It doesn't remove
structure. For example:

1. truncate table customers;

10) MySQL Drop Query


MySQL drop query is used to drop a table, view or database. It removes structure and data of a
table if you drop table. For example:

1. drop table customers;

MySQL Constraints
The constraint in MySQL is used to specify the rule that allows or restricts what values/data will
be stored in the table. They provide a suitable method to ensure data accuracy and integrity
inside the table. It also helps to limit the type of data that will be inserted inside the table. If any
interruption occurs between the constraint and data action, the action is failed.
Constraints in MySQL is classified into two types:

1. Column Level Constraints: These constraints are applied only to the single column that limits
the type of particular column data.
2. Table Level Constraints: These constraints are applied to the entire table that limits the type of
data for the whole table.

How to create constraints in MySQL


We can define the constraints during a table created by using the CREATE TABLE statement.
MySQL also uses the ALTER TABLE statement to specify the constraints in the case of the
existing table schema.

Syntax

The following are the syntax to create a constraints in table:

1. CREATE TABLE new_table_name (


2. col_name1 datatype constraint,
3. col_name2 datatype constraint,
4. col_name3 datatype constraint,
5. .........
6. );

Constraints used in MySQL

The following are the most common constraints used in the MySQL:

 NOT NULL
 CHECK
 DEFAULT
 PRIMARY KEY
 AUTO_INCREMENT
 UNIQUE
 INDEX
 ENUM
 FOREIGN KEY

Let us discuss each of these constraints in detail.

NOT NULL Constraint

This constraint specifies that the column cannot have NULL or empty values. The below
statement creates a table with NOT NULL constraint.
mysql> CREATE TABLE Student(Id INTEGER, LastName TEXT NOT NULL, FirstName TEXT NOT N
ULL, City VARCHAR(35));

Execute the queries listed below to understand how it works:

1. mysql> INSERT INTO Student VALUES(1, 'Hanks', 'Peter', 'New York');


2.
3. mysql> INSERT INTO Student VALUES(2, NULL, 'Amanda', 'Florida');

Output

In the above image, we can see that the first INSERT query executes correctly, but the second
statement fails and gives an error that says column LastName cannot be null.

UNIQUE Constraint

This constraint ensures that all values inserted into the column will be unique. It means a column
cannot stores duplicate values. MySQL allows us to use more than one column with UNIQUE
constraint in a table. The below statement creates a table with a UNIQUE constraint:

1. mysql> CREATE TABLE ShirtBrands(Id INTEGER, BrandName VARCHAR(40) UNIQUE, Size VARCHA
R(30));

Execute the queries listed below to understand how it works:

1. mysql> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Pantaloons', 38), (2, 'Cantabil',
40);
2.
3. mysql> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Raymond', 38), (2, 'Cantabil', 4
0);

Output

In the below output, we can see that the first INSERT query executes correctly, but the second
statement fails and gives an error that says: Duplicate entry 'Cantabil' for key BrandName.
CHECK Constraint

It controls the value in a particular column. It ensures that the inserted value in a column must be
satisfied with the given condition. In other words, it determines whether the value associated
with the column is valid or not with the given condition.

Before the version 8.0.16, MySQL uses the limited version of this constraint syntax, as given
below:

1. CHECK (expr)

After the version 8.0.16, MySQL uses the CHECK constraints for all storage engines i.e., table
constraint and column constraint, as given below:

1. [CONSTRAINT [symbol]] CHECK (expr) [[NOT] ENFORCED]

Let us understand how a CHECK constraint works in MySQL. For example, the following
statement creates a table "Persons" that contains CHECK constraint on the "Age"
column. The CHECK constraint ensures that the inserted value in a column must be
satisfied with the given condition means the Age of a person should be greater than or
equal to 18:

1. mysql> CREATE TABLE Persons (


2. ID int NOT NULL,
3. Name varchar(45) NOT NULL,
4. Age int CHECK (Age>=18)
5. );

Execute the listed queries to insert the values into the table:

1. mysql> INSERT INTO Persons(Id, Name, Age)


2. VALUES (1,'Robert', 28), (2, 'Joseph', 35), (3, 'Peter', 40);
3.
4. mysql> INSERT INTO Persons(Id, Name, Age) VALUES (1,'Robert', 15);

Output

In the below output, we can see that the first INSERT query executes successfully, but the
second statement fails and gives an error that says: CHECK constraint is violated for key Age.
DEFAULT Constraint

This constraint is used to set the default value for the particular column where we have not
specified any value. It means the column must contain a value, including NULL.

For example, the following statement creates a table "Persons" that contains DEFAULT
constraint on the "City" column. If we have not specified any value to the City column, it inserts
the default value:

1. mysql> CREATE TABLE Persons (


2. ID int NOT NULL,
3. Name varchar(45) NOT NULL,
4. Age int,
5. City varchar(25) DEFAULT 'New York'
6. );

Execute the listed queries to insert the values into the table:

1. mysql> INSERT INTO Persons(Id, Name, Age, City)


2. VALUES (1,'Robert', 15, 'Florida'),
3. (2, 'Joseph', 35, 'California'),
4. (3, 'Peter', 40, 'Alaska');
5.
6. mysql> INSERT INTO Persons(Id, Name, Age) VALUES (1,'Brayan', 15);

Output

In the below output, we can see that the first insert query that contains all fields executes
successfully, while the second insert statement does not contain the "City" column but also
executed successfully. It is because it has a default value.
Now, executes the following statement to validate the default value for the 4th column:

1. mysql> SELECT * FROM Persons;

We can see that it works perfectly. It means default value "New York" stored automatically in
the City column.

PRIMARY KEY Constraint

This constraint is used to identify each record in a table uniquely. If the column contains primary
key constraints, then it cannot be null or empty. A table may have duplicate columns, but it can
contain only one primary key. It always contains unique value into a column.

The following statement creates a table "Person" and explains the use of this primary key more
clearly:

1. CREATE TABLE Persons (


2. ID int NOT NULL PRIMARY KEY,
3. Name varchar(45) NOT NULL,
4. Age int,
5. City varchar(25));

Next, use the insert query to store data into a table:

1. INSERT INTO Persons(Id, Name, Age, City)


2. VALUES (1,'Robert', 15, 'Florida') ,
3. (2, 'Joseph', 35, 'California'),
4. (3, 'Peter', 40, 'Alaska');
5.
6. INSERT INTO Persons(Id, Name, Age, City)
7. VALUES (1,'Stephen', 15, 'Florida');

Output

In the below output, we can see that the first insert query executes successfully. While the second
insert statement fails and gives an error that says: Duplicate entry for the primary key column.

AUTO_INCREMENT Constraint

This constraint automatically generates a unique number whenever we insert a new record into
the table. Generally, we use this constraint for the primary key field in a table.

We can understand it with the following example where the id column going to be auto-
incremented in the Animal table:

1. mysql> CREATE TABLE Animals(


2. id int NOT NULL AUTO_INCREMENT,
3. name CHAR(30) NOT NULL,
4. PRIMARY KEY (id));

Next, we need to insert the values into the "Animals" table:

1. mysql> INSERT INTO Animals (name) VALUES


2. ('Tiger'),('Dog'),('Penguin'),
3. ('Camel'),('Cat'),('Ostrich');

Now, execute the below statement to get the table data:

1. mysql> SELECT * FROM Animals;

Output

In the output, we can see that I have not specified any value for the auto-increment column, so
MySQL automatically generates a unique number in the sequence order for this field.

ENUM Constraint

The ENUM data type in MySQL is a string object. It allows us to limit the value chosen from a
list of permitted values in the column specification at the time of table creation. It is short for
enumeration, which means that each column may have one of the specified possible values. It
uses numeric indexes (1, 2, 3…) to represent string values.

The following illustration creates a table named "shirts" that contains three columns: id, name,
and size. The column name "size" uses the ENUM data type that contains small, medium, large,
and x-large sizes.

1. mysql> CREATE TABLE Shirts (


2. id INT PRIMARY KEY AUTO_INCREMENT,
3. name VARCHAR(35),
4. size ENUM('small', 'medium', 'large', 'x-large')
5. );

Next, we need to insert the values into the "Shirts" table using the below statements:

1. mysql> INSERT INTO Shirts(id, name, size)


2. VALUES (1,'t-shirt', 'medium'),
3. (2, 'casual-shirt', 'small'),
4. (3, 'formal-shirt', 'large');

Now, execute the SELECT statement to see the inserted values into the table:

1. mysql> SELECT * FROM Shirts;

Output

We will get the following output:


INDEX Constraint

This constraint allows us to create and retrieve values from the table very quickly and easily. An
index can be created using one or more than one column. It assigns a ROWID for each row in
that way they were inserted into the table.

The following illustration creates a table named "shirts" that contains three columns: id, name,
and size.

1. mysql> CREATE TABLE Shirts (


2. id INT PRIMARY KEY AUTO_INCREMENT,
3. name VARCHAR(35),
4. size ENUM('small', 'medium', 'large', 'x-large')
5. );

Next, we need to insert the values into the "Shirts" table using the below statements:

1. mysql> INSERT INTO Shirts(id, name, size)


2. VALUES (1,'t-shirt', 'medium'),
3. (2, 'casual-shirt', 'small'),
4. (3, 'formal-shirt', 'large');

Now, execute this statement for creating index:


1. mysql> CREATE INDEX idx_name ON Shirts(name);

We can use the query below to retrieve the data using the index column:

1. mysql> SELECT * FROM Shirts USE INDEX(idx_name);

Output

The following output appears:

Foreign Key Constraint

This constraint is used to link two tables together. It is also known as the referencing key. A
foreign key column matches the primary key field of another table. It means a foreign key field
in one table refers to the primary key field of another table.

Let us consider the structure of these tables: Persons and Orders.

Table: Persons

1. CREATE TABLE Persons (


2. Person_ID int NOT NULL PRIMARY KEY,
3. Name varchar(45) NOT NULL,
4. Age int,
5. City varchar(25)
6. );

Table: Orders

1. CREATE TABLE Orders (


2. Order_ID int NOT NULL PRIMARY KEY,
3. Order_Num int NOT NULL,
4. Person_ID int,
5. FOREIGN KEY (Person_ID) REFERENCES Persons(Person_ID)
6. );

In the above table structures, we can see that the "Person_ID" field in the "Orders" table points to
the "Person_ID" field in the "Persons" table. The "Person_ID" is the PRIMARY KEY in the
"Persons" table, while the "Person_ID" column of the "Orders" table is a FOREIGN KEY.

Output

Our table contains the following data:

MySQL INSERT Example

Let us understand how INSERT statements work in MySQL with the help of multiple examples.
First, create a table "People" in the database using the following command:

1. CREATE TABLE People(


2. id int NOT NULL AUTO_INCREMENT,
3. name varchar(45) NOT NULL,
4. occupation varchar(35) NOT NULL,
5. age int,
6. PRIMARY KEY (id)
7. );
1. If we want to store single records for all fields, use the syntax as follows:

1. INSERT INTO People (id, name, occupation, age)


2. VALUES (101, 'Peter', 'Engineer', 32);

2. If we want to store multiple records, use the following statements where we can either specify
all field names or don't specify any field.

1. INSERT INTO People VALUES


2. (102, 'Joseph', 'Developer', 30),
3. (103, 'Mike', 'Leader', 28),
4. (104, 'Stephen', 'Scientist', 45);

3. If we want to store records without giving all fields, we use the following partial field
statements. In such case, it is mandatory to specify field names.

1. INSERT INTO People (name, occupation)


2. VALUES ('Stephen', 'Scientist'), ('Bob', 'Actor');

In the below output, we can see that all INSERT statements have successfully executed and
stored the value in a table correctly.

We can use the below syntax to show the records of the People table:
1. mysql> SELECT * FROM People;

We will get the output as follows:

Inserting Date in MySQL Table:

We can also use the INSERT STATEMENT to add the date in MySQL table. MySQL provides
several data types for storing dates such as DATE, TIMESTAMP, DATETIME, and YEAR. The
default format of the date in MySQL is YYYY-MM-DD.

This format has the below descriptions:

 YYYY: It represents the four-digit year, like 2020.


 MM: It represents the two-digit month, like 01, 02, 03, and 12.
 DD: It represents the two-digit day, like 01, 02, 03, and 31.

Following is the basic syntax to insert date in MySQL table:

1. INSERT INTO table_name (column_name, column_date) VALUES ('DATE: Manual Date', '2008-7-
04');

If we want to insert a date in the mm/dd/yyyy format, it is required to use the below statement:

1. INSERT INTO table_name VALUES (STR_TO_DATE(date_value, format_specifier));

UPDATE statement is given below:

1. UPDATE [LOW_PRIORITY] [IGNORE] table_name


2. SET column_assignment_list
3. [WHERE condition]
Update Single Column

This query will update the email id of Java course with the new id as follows:

1. UPDATE trainer
2. SET email = '[email protected]'
3. WHERE course_name = 'Java';

After successful execution, we will verify the table using the below statement:

1. SELECT * FROM trainer;

In the output, we can see that our table is updated as per our conditions.

Update Multiple Columns

The UPDATE statement can also be used to update multiple columns by specifying a comma-
separated list of columns. Suppose we have a table as below:
This statement explains will update the name and occupation whose id = 105 in the People
table as follows:

1. UPDATE People
2. SET name = 'Mary', occupation = 'Content Writer'
3. WHERE id = 105;

We can verify the output below:

UPDATE Statement to Replace String

We can also use the UPDATE statement in MySQL to change the string name in the particular
column. The following example updates the domain parts of emails of Android course:

1. UPDATE Trainer_table
2. SET email = REPLACE(email,'@javatpoint.com','@tutorialandexample.com')
3. WHERE course_name = 'Testing';

It will give the following output:

MySQL DELETE Statement Examples

Here, we are going to use the "Employees" and "Payment" tables for the demonstration of the
DELETE statement. Suppose the Employees and Payment tables contain the following data:
If we want to delete an employee whose emp_id is 107, we should use the DELETE statement
with the WHERE clause. See the below query:

1. mysql> DELETE FROM Employees WHERE emp_id=107;

After the execution of the query, it will return the output as below image. Once the record is
deleted, verify the table using the SELECT statement:
If we want to delete all records from the table, there is no need to use the WHERE clause with
the DELETE statement. See the below code and output:

In the above output, we can see that after removing all rows, the Employees table will be empty.
It means no records available in the selected table.

MySQL DELETE and LIMIT Clause

MySQL Limit clause is used to restrict the count of rows returns from the result set, rather than
fetching the whole records in the table. Sometimes we want to limit the number of rows to be
deleted from the table; in that case, we will use the LIMIT clause as follows:

1. DELETE FROM table_name


2. WHERE condition
3. ORDER BY colm1, colm2, ...
4. LIMIT row_count;

It is to note that the order of rows in a MySQL table is unspecified. Therefore, we should always
use the ORDER BY clause while using the LIMIT clause.

For example, the following query first sorts the employees according to their names
alphabetically and deletes the first three employees from the table:
1. mysql> DELETE FROM Employees ORDER BY name LIMIT 3;

It will give the below output:

MySQL DELETE and JOIN Clause

The JOIN clause is used to add the two or more tables in MySQL. We will add the JOIN clause
with the DELETE statement whenever we want to delete records from multiple tables within a
single query. See the below query:

1. mysql> DELETE Employees, Payment FROM Employees


2. INNER JOIN Payment
3. ON Employees.emp_id = Payment.emp_id
4. WHERE Employees.emp_id = 102;

Output:

After execution, we will see the output as below image:

MySQL SELECT Statement


MySQL SELECT Statement Example:

Let us understand how SELECT command works in MySQL with the help of various examples.
Suppose we have a table named employee_detail that contains the following data:

1. If we want to retrieve a single column from the table, we need to execute the below query:

1. mysql> SELECT Name FROM employee_detail;

We will get the below output where we can see only one column records.

2. If we want to query multiple columns from the table, we need to execute the below query:

1. mysql> SELECT Name, Email, City FROM employee_detail;

We will get the below output where we can see the name, email, and city of employees.
3. If we want to fetch data from all columns of the table, we need to use all column's names
with the select statement. Specifying all column names is not convenient to the user, so MySQL
uses an asterisk (*) to retrieve all column data as follows:

1. mysql> SELECT * FROM employee_detail;

We will get the below output where we can see all columns of the table.

4. Here, we use the SUM function with the HAVING clause in the SELECT command to get
the employee name, city, and total working hours. Also, it uses the GROUP BY clause to group
them by the Name column.

1. SELECT Name, City, SUM(working_hours) AS "Total working hours"


2. FROM employee_detail
3. GROUP BY Name
4. HAVING SUM(working_hours) > 5;

It will give the below output:


5. MySQL SELECT statement can also be used to retrieve records from multiple tables by using
a JOIN statement. Suppose we have a table named "customer" and "orders" that contains the
following data:

Table: customer

Table: orders

Execute the following SQL statement that returns the matching records from both tables using
the INNER JOIN query:

1. SELECT cust_name, city, order_num, order_date


2. FROM customer INNER JOIN orders
3. ON customer.cust_id = orders.order_id
4. WHERE order_date < '2020-04-30'
5. ORDER BY cust_name;

After successful execution of the query, we will get the output as follows:

You might also like