Your cart is currently empty!
Category: mysql
-
Khóa học miễn phí MySQL – Constraints nhận dự án làm có lương
MySQL − Constraints
Table of content
MySQL Constraints
The MySQL constraints can be used to set certain rules to the column(s) in a table. These constraints can restrict the type of data that can be inserted or updated in a particular column. This helps you to maintain the data accuracy and reliability in a table.
There are two types of MySQL constraints.
- Column level constraints: These type of constraints will only apply to a column in a table.
- Table level constraints: These constraints will apply to the complete table.
The commonly used constraints in MySQL are NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, CREATE INDEX, AUTO_INCREMENT, etc.
Syntax
Following is the basic syntax to add a constraint for the column(s) in a table −
CREATE TABLE table_name ( Column_name1 datatype constraint, Column_name2 datatype constraint, Column_name3 datatype constraint, ......... );
MySQL NOT NULL Constraint
By default, a column in a MySQL table can contain NULL values. In some scenarios, we may want a particular column to not accept or contain NULL values. To do so, we can use the MySQL NOT NULL constraint.
This constraint enforces a specific field to always contain a value, which means that we cannot insert or update a record without adding a value to this field.
Example
In the following query, we are adding the NOT NULL constraint on the ID and NAME columns of the CUSTOMERS table. As a result, the ID and NAME columns will not accept NULL values at the time of record insertion.
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int );
Let”s try inserting records into this table. The following statement will insert a record into the CUSTOMERS table −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Nikhil'', 18);
But, if we try to insert records with NULL values as ID as −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(Null, ''Varun'', 26);
An error will be generated saying “Column ”ID” cannot be null”.
ERROR 1048 (23000): Column ''ID'' cannot be null
In the same way if we try to pass NULLs as values to the NAME column, similar error will be generated.
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(3, Null, 19);
This will generate the following error −
ERROR 1048 (23000): Column ''NAME'' cannot be null
As we can see in the above queries, the first record is successfully inserted because it does not have null values in the ID and Name columns. Whereas, the second and third records are not inserted because we are trying to insert NULL values in the columns which shouldn”t be NULL.
MySQL UNIQUE Constraint
The UNIQUE constraint in MySQL ensures that every value in a column must be distinct. This means the column with the UNIQUE constraint cannot have the same value repeated; each value must be unique.
Note: We can have one or more UNIQUE constraints on a single table.
Example
The following query creates a UNIQUE constraint on the ID column of the CUSTOMERS table −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, UNIQUE (ID) );
Now, let us insert the following records into the above-created table −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Nikhil'', 18); INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Varun'', 26);
In the above code block, the second insert statement returned an error saying “Duplicate entry ”1” for key ”customers.ID” because the ID value we are inserting already exists in the table. Therefore, it is a duplicate and the query generates the following error −
ERROR 1062 (23000): Duplicate entry ''1'' for key ''customers.ID''
MySQL PRIMARY KEY Constraint
The PRIMARY KEY constraint in MySQL is used to uniquely identify each record in a table. This means that, if we define primary key on a particular column in a table, it must contain UNIQUE values, and cannot contain NULL values.
Note: We can have only a single primary key on a table.
Example
The following query creates a PRIMARY KEY on the ID column of the CUSTOMERS table −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, PRIMARY KEY (ID) );
Once the table is created, insert the following record into the above-created table −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES (1, ''Nikhil'', 18); Query OK, 1 row affected (0.01 sec)
Since we added the PRIMARY KEY constraint on the ID column, if you try to insert a record with duplicate ID value or NULL value, it will generate an error.
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES (1, ''Varun'', 26); ERROR 1062 (23000): Duplicate entry ''1'' for key ''customers.PRIMARY'' INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES (NULL, ''Datta'', 19); ERROR 1048 (23000): Column ''ID'' cannot be null
As we can see in the above queries, the first insert statement is successfully inserted into the table. Whereas the second and third statements returned an error because they contain a duplicate and a NULL value in the primary key column i.e. (ID).
MySQL FOREIGN KEY Constraint
The FOREIGN KEY constraint in MySQL is used to link a field or collection of fields in one table to the primary key of another table.
A table with the foreign key is called a child table and the table with the primary key is called the parent table or referenced table.
Example
The following query creates a FOREIGN KEY on the CUST_ID column when the ORDERS table is created −
Table: Customers
CREATE TABLE CUSTOMERS ( CUST_ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, PRIMARY KEY (CUST_ID) );
Table: Orders
CREATE TABLE ORDERS ( ORDER_ID int NOT NULL, ORDER_NUMBER int NOT NULL, CUST_ID int, FOREIGN KEY (CUST_ID) REFERENCES CUSTOMERS (CUST_ID) );
MySQL CHECK Constraint
The CHECK constraint in MySQL restricts the range of values that can be inserted into a column. This constraint ensures that the inserted value in a column must be satisfied with the provided condition.
Example
The following query creates a CHECK constraint on the AGE column of the CUSTOMERS table, where it ensures that the age of the student must be 18 or older −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, CHECK (AGE >= 18) );
Once the table is created, we can insert the records into the above created table as shown below −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Nikhil'', 18); INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(3, ''Datta'', 19);
Since we added the CHECK constraint on the AGE column such that the age of the student should be equal or greater than 18. If you try to insert a record with age value less than 18, an error will be generated.
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(2, ''Varun'', 16); ERROR 3819 (HY000): Check constraint ''customers_chk_1'' is violated. INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(4, ''Karthik'', 15); ERROR 3819 (HY000): Check constraint ''customers_chk_1'' is violated.
Example
Here, the following query creates a CHECK constraint on multiple columns (AGE and ADDRESS) −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, ADDRESS varchar(40), CONSTRAINT CHECK_AGE CHECK (AGE >= 18 AND ADDRESS = "Mumbai") );
Now, let us insert the following records into the above-created table −
INSERT INTO CUSTOMERS(ID, NAME, AGE, ADDRESS) VALUES(1, ''Nikhil'', 18, ''Mumbai''); Query OK, 1 row affected (0.01 sec) INSERT INTO CUSTOMERS(ID, NAME, AGE, ADDRESS) VALUES(3, ''Datta'', 19, ''Delhi''); ERROR 3819 (HY000): Check constraint ''CHECK_AGE_AND_ADDRESS'' is violated.
The second insert statement returned an error because it is violating the condition of the check constraint i.e. (AGE >= 18 AND ADDRESS = “Mumbai”).
MySQL DEFAULT Constraint
The DEFAULT constraint in MySQL is used to assign a default value to a specific column in a table. This default value gets applied to any new records in the DEFAULT specified column when no other value is provided during insertion.
Example
In the following query, we are defining the DEFAULT constraint on the ADDRESS column of the CUSTOMERS table. We assigned “Mumbai” as default value when no value is inserted. −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, ADDRESS varchar(40) DEFAULT "Mumbai" );
Here, we are inserting the first two records without any value in the ADDRESS column. In the third record, we are inserting the ADDRESS value as ”Delhi”.
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Nikhil'', 18); INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(2, ''Varun'', 16); INSERT INTO CUSTOMERS(ID, NAME, AGE, ADDRESS) VALUES(3, ''Datta'', 19, ''Delhi'');
Exeucte the following query to display the records inserted in the above-created table −
Select * from CUSTOMERS;
In the following output, we can see that the value in the ADDRESS column for the first two rows is by default “Mumbai”.
ID NAME AGE ADDRESS 1 Nikhil 18 Mumbai 2 Varun 16 Mumbai 3 Datta 19 Delhi MySQL CREATE INDEX Constraint
The CREATE INDEX constraint in MySQL is used to create indexes for one more columns in a table.
The indexes are used to fetch the data from the database much quicker. However, the users cannot see the indexes in action, instead, they are just used to speed up the searches and queries.
Example
Here, we are creating a table named CUSTOMERS using the query below −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, ADDRESS varchar(40), PRIMARY KEY (ID) );
The following query creates an index named “index_address” on the ADDRESS column of the CUSTOMERS table −
CREATE INDEX index_address ON CUSTOMERS (ADDRESS);
MySQL AUTO_INCREMENT Constraint
When a AUTO_INCREMENT constraint is defined on a particular column of a table, it will automatically generate a unique number when a new record is inserted into that column.
By default, the starting value is 1, and it will automatically increment its value by 1 for each new record.
Example
The following query adds an AUTO_INCREMENT constraint on the ID column of the CUSTOMERS table −
CREATE TABLE CUSTOMERS ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(20) NOT NULL, AGE int, PRIMARY KEY (ID) );
In the insert statements below, we are not inserting ID values.
INSERT INTO STUDENTS(NAME, AGE) VALUES(''Nikhil'', 18); INSERT INTO STUDENTS(NAME, AGE) VALUES(''Varun'', 16); INSERT INTO STUDENTS(NAME, AGE) VALUES(''Datta'', 19);
Now, execute the following query to display the records of the above-created table −
Select * from CUSTOMERS;
As we can see in the STUDENTS table below, the values in the ID column are automatically incremented because of the AUTO_INCREMENT constraint on the ID column.
ID NAME AGE 1 Nikhil 18 2 Varun 16 3 Datta 19
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc
Khóa học miễn phí MySQL – Select Query nhận dự án làm có lương
MySQL – Select Query
Now that we have learned how to create tables in MySQL and insert values into it in the previous tutorials, the next step is to check whether the values are recorded in this table or not. To do this, one must use the SELECT statement to retrieve and view the records in that specific table.”
MySQL Select Statement
The MySQL SELECT command is used to fetch data from the MySQL database in the form of a result table. These result tables are called result-sets.
Note − We can use this command at ”mysql>” prompt as well as in any script like PHP, Node.js, Java, python, etc.
Syntax
Here is generic SQL syntax of SELECT command to fetch data from the MySQL table −
SELECT field1, field2,...fieldN FROM table_name1, table_name2... [WHERE Clause] [OFFSET M ][LIMIT N]
-
You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command.
-
We can fetch one or more fields in a single SELECT command.
-
We can specify star (*) in place of fields. In this case, SELECT will return all the fields.
-
We can specify any condition using the WHERE clause.
-
We can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero.
-
We can limit the number of returns using the LIMIT attribute.
Fetching Data Using SELECT from Command Prompt
This will use SQL SELECT command to fetch data from an MySQL table.
Example
First of all, let us create a table named CUSTOMERS using the following query −
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
The following query inserts 7 records into the above created table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ), (2, ''Khilan'', 25, ''Delhi'', 1500.00 ), (3, ''Kaushik'', 23, ''Kota'', 2000.00 ), (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 ), (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ), (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ), (7, ''Muffy'', 24, ''Indore'', 10000.00 );
To Retrieve All Fields
Now, to retrieve all the data present in a CUSTOMERS table, we use the following SELECT statement −
SELECT * from CUSTOMERS;
Following are the records present in the CUSTOMERS table −
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Khilan | 25 | Delhi | 1500.00 |
3 | Kaushik | 23 | Kota | 2000.00 |
4 | Chaitali | 25 | Mumbai | 6500.00 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | Hyderabad | 4500.00 |
7 | Muffy | 24 | Indore | 10000.00 |
To Retrieve Selective Fields
Here, we are retrieving only three columns/fields, ID, NAME, and ADDRESS present in the CUSTOMERS table, using the following query −
SELECT ID, NAME, ADDRESS FROM CUSTOMERS;
On executing the given query, the output is displayed as follows −
ID | NAME | ADDRESS |
---|---|---|
1 | Ramesh | Ahmedabad |
2 | Khilan | Delhi |
3 | Kaushik | Kota |
4 | Chaitali | Mumbai |
5 | Hardik | Bhopal |
6 | Komal | Hyderabad |
7 | Muffy | Indore |
Computing using SELECT in Command Prompt
The SELECT statement is not only used to fetch data from tables but can also be used to get the results of mathematical computations in a tabular format. In these cases, you don”t have to mention a specific database table in the SELECT statement.
Following is the syntax to do so −
SELECT [math_computation];
Example
In the following example, let us solve a mathematical computation using the SELECT statement −
SELECT 46475*453;
Output
The output for the program query is produced as given below −
46475*453 |
---|
21053175 |
Aliasing a Column in SELECT Statement
MySQL database provides a method to alias column names into a more understandable and relative name when being displayed. This is done using the ”AS” keyword. This keyword is used in the SELECT statement as well.
Following is the syntax to do so −
SELECT column_name AS alias_name FROM table_name;
You can also use an alias to display select expressions with the same syntax; you should use a select expression instead of column_name in the syntax.
Example
In the example below, we are retrieving the ID column from the previously created CUSTOMERS table. We aliased the ID column as “Identity_Document” −
SELECT ID AS Identity_Document FROM CUSTOMERS;
As we can see the output, the alias name ”Identity_Document” has been used instead of ”ID”.
Identity_Document |
---|
1 |
2 |
3 |
4 |
5 |
6 |
7 |
Select Query into MySQL Database Using a Client Program
Besides getting data from a table using the SELECT query, you can also use a client program to perform the SELECT operation on a table.
Syntax
Following are the syntaxes of this operation in various programming languages −
To fetch data from a MySQL table through a PHP program, we need to execute the SELECT statement using the mysqli function query() as −
$sql="SELECT COLUMN_NAME1, COLUMN_NAME2,... FROM TABLE_NAME"; $mysqli->query($sql);
To fetch data from a MySQL table through a Node.js program, we need to execute the SELECT statement using the query() function of the mysql2 library as −
sql="SELECT field1, field2,...fieldN FROM table_name"; con.query(sql);
To fetch data from a MySQL table through a Java program, we need to execute the SELECT statement using the JDBC function executeUpdate() as −
String sql="SELECT COLUMN_NAME1, COLUMN_NAME2,... FROM TABLE_NAME"; statement.executeQuery(sql);
To fetch data from a MySQL table through a Python program, we need to execute the SELECT statement using the execute() function of the MySQL Connector/Python as −
select_query = "SELECT COLUMN1, COLUMN2,.. FROM TABLE_NAME"; cursorObj.execute(select_query);
Example
Following are the programs −
$dbhost = ''localhost $dbuser = ''root $dbpass = ''password $dbname = ''TUTORIALS $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli->connect_errno ) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
''); $sql = "SELECT * FROM tutorials_tbl"; if($result = $mysqli->query($sql)){ printf("Select statement executed successfully..! "); printf("Records are: "); while($row = mysqli_fetch_row($result)){ print_r ($row); } } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();
Output
The output obtained is as follows −
Select statement executed successfully..! Records are: Array ( [0] => 1 [1] => MySQL Tut [2] => unknown [3] => 2023-07-25 ) Array ( [0] => 2 [1] => PHP Tut [2] => unknown2 [3] => 2023-08-12 )
var mysql = require(''mysql2''); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123" }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); //Creating a Database sql = "CREATE DATABASE IF NOT EXISTS TUTORIALS" con.query(sql); //Selecting a Database sql = "USE TUTORIALS" con.query(sql); //Creating a Table sql = "CREATE TABLE IF NOT EXISTS tutorials_tbl(tutorial_id INT NOT NULL PRIMARY KEY, tutorial_title VARCHAR(100) NOT NULL, tutorial_author VARCHAR(40) NOT NULL, submission_date DATE)" con.query(sql); //Inserting records into table sql = "INSERT INTO tutorials_tbl(tutorial_id, tutorial_title, tutorial_author, submission_date) VALUES(1, ''Learn PHP'', ''John Paul'', NOW()), (2, ''Learn MySQL'', ''Abdul S'', NOW()), (3, ''JAVA Tutorial'', ''Sanjay'', ''2007-05-06''), (4, ''Python Tutorial'', ''Sasha Lee'', ''2016-09-04''), (5, ''Hadoop Tutorial'', ''Chris Welsh'', NOW())" con.query(sql); //Selecting all the records from table sql = "SELECT * FROM tutorials_tbl" con.query(sql, function (err, result) { if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
Connected! [ { tutorial_id: 1, tutorial_title: ''Learn PHP'', tutorial_author: ''John Paul'', submission_date: 2023-07-25T18:30:00.000Z }, { tutorial_id: 2, tutorial_title: ''Learn MySQL'', tutorial_author: ''Abdul S'', submission_date: 2023-07-25T18:30:00.000Z }, { tutorial_id: 3, tutorial_title: ''JAVA Tutorial'', tutorial_author: ''Sanjay'', submission_date: 2007-05-05T18:30:00.000Z }, { tutorial_id: 4, tutorial_title: ''Python Tutorial'', tutorial_author: ''Sasha Lee'', submission_date: 2016-09-03T18:30:00.000Z }, { tutorial_id: 5, tutorial_title: ''Hadoop Tutorial'', tutorial_author: ''Chris Welsh'', submission_date: 2023-07-25T18:30:00.000Z } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class SelectQuery { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String user = "root"; String password = "password"; ResultSet rs; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, password); Statement st = con.createStatement(); //System.out.println("Database connected successfully...!"); String sql = "SELECT * FROM tutorials_tbl"; rs = st.executeQuery(sql); System.out.println("Select query executed successfully..!"); System.out.println("Table records: "); while(rs.next()) { String tutorial_id = rs.getString("tutorial_id"); String tutorial_title = rs.getString("tutorial_title"); String tutorial_author = rs.getString("tutorial_author"); String submission_date = rs.getString("submission_date"); System.out.println("Id: " + tutorial_id + ", Title: " + tutorial_title + ", Author: " + tutorial_author + ", Submission_date: " + submission_date); } }catch(Exception e) { e.printStackTrace(); } } }
Output
The output obtained is as shown below −
Select query executed successfully..! Table records: Id: 1, Title: Learn PHP, Author: John Paul, Submission_date: 2023-08-08
import mysql.connector import datetime #establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) table_name = ''tutorials_tbl'' #Creating a cursor object cursorObj = connection.cursor() select_query = f"SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM {table_name}" cursorObj.execute(select_query) result = cursorObj.fetchall() print("Tutorial Table Data:") for row in result: print(row) cursorObj.close() connection.close()
Output
Following is the output of the above code −
Derived Table Result: Tutorial Table Data: (1, ''Learn PHP'', ''John Paul'', datetime.date(2023, 3, 28)) (2, ''Learn MySQL'', ''Abdul S'', datetime.date(2023, 3, 28)) (3, ''JAVA Tutorial'', ''Sanjay'', datetime.date(2007, 5, 6)) (4, ''Python Tutorial'', ''Sasha Lee'', datetime.date(2016, 9, 4)) (5, ''Hadoop Tutorial'', ''Chris Welsh'', datetime.date(2023, 3, 28)) (6, ''R Tutorial'', ''Vaishnav'', datetime.date(2011, 11, 4))
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc