SQL Standard

30 SQL Query Examples

The full form of SQL is Structured Query language. It is a very useful tool to access or modify the structure and the data of the database. Many applications need the database to store the necessary data in a database in structured format permanently. MySQL, Oracle, SQL Server, etc. are popular databases to store the data of the application. They are essential to learn the basics of SQL to access or modify the content of the database. The basic uses of the SQL statements on a MariaDB database are shown in this tutorial using 30 SQL query examples.

Prerequisites

You have to install the database server with the client before practicing the examples in this tutorial. The MariaDB database server and client are used in this tutorial.

1. Run the following commands to update the system:

$ sudo apt-get update

2. Run the following command to install the MariaDB server and client:

$ sudo apt-get install mariadb-server mariadb-client

3. Run the following command to install the security script for the MariaDB database:

$ sudo mysql_secure_installation

4. Run the following command to restart the MariaDB server:

$ sudo /etc/init.d/mariadb restart

6. Run the following command to log in to the MariaDB server:

$ sudo mariadb -u root -p

List of SQL Query Examples

  1. Create the Database
  2. Create the Tables
  3. Rename the Table Name
  4. Add a New Column to the Table
  5. Remove the Column from the Table
  6. Insert a Single Row into the Table
  7. Insert Multiple Rows into the Table
  8. Read All of the Particular Fields from the Table
  9. Read the Table After Filtering the Data from the Table
  10. Read the Table After Filtering the Data Based on Boolean Logic
  11. Read the Table After Filtering the Rows Based on the Range of Data
  12. Read the Table After Sorting the Table Based on the Particular Columns.
  13. Read the Table by Setting the Alternative Name of the Column
  14. Count the Total Number of Rows in the Table
  15. Read the Data from Multiple Tables
  16. Read the Table by Grouping the Particular Fields
  17. Read the Table After Omitting the Duplicate Values
  18. Read the Table by Limiting the Row Number
  19. Read the Table Based on the Partial Match
  20. Count the Sum of the Particular Field of the Table
  21. Find the Maximum and Minimum Values of the Particular Field
  22. Read the Data on the Particular Part of a Field
  23. Read the Table Data After Concatenation
  24. Read the Table Data After Mathematical Calculation
  25. Create a View of the Table
  26. Update the Table Based on the Particular Condition
  27. Delete the Table Data Based on the Particular Condition
  28. Delete All Records from the Table
  29. Drop the Table
  30. Drop the Database

Create the Database

Suppose we have to design a simple database for Library Management System. To do this task, a database needs to create in the server that contians multiple relational tables. After logging in to the database server, run the following command to create a database named “library” in the MariaDB database server:

CREATE DATABASE library;

The output shows that the library database is created on the server:

Run the following command to select the database from the server to perform different types of database operations:

USE library;

The output shows that the library database is selected:

Create the Tables

The next step is to create the necessary tables for the database to store the data. Three tables are created in this part of the tutorial. These are books, members, and borrow_info tables.

  1. The books table stores all book-related data.
  2. The members table stores all information about the members who borrows the book from the library.
  3. The borrow_info table stores the information about which book is borrowed by which member.

1. Books Table

Run the following SQL statement to create a table named “books” in the “library” database that contains seven fields and one primary key. Here, the “id” field is the primary key and the data type is int. The auto_increment attribute is used for the “id” field. So, the value of this field is incremented automatically when a new row is inserted. The varchar data type is used to store the string data of the variable length. The title, author, publication, and isbn fields store the string data. The data type of the total_copy and price fields are int. So, these fields store the numeric data.

CREATE TABLE books (
id INT AUTO_INCREMENT,
title VARCHAR(50),
author VARCHAR(50),
publication VARCHAR(100),
isbn VARCHAR(30),
total_copy INT,
price INT,
PRIMARY KEY (id));

The output shows that the “books” table is created successfully:

2. Members Table

Run the following SQL statement to create a table named “members” in the “library” database that contains 5 fields and one primary key. The “id” field has the auto_increment attribute like the “books” table. The data type of the other fields is varchar. So, these fields store the string data.

CREATE TABLE members (
id INT AUTO_INCREMENT,
name VARCHAR(50),
address VARCHAR(200),
contact_no VARCHAR(15),
email VARCHAR(50),
PRIMARY KEY (id));

The output shows that the “members” table is created successfully:

3. Borrow_info Table

Run the following SQL statement to create a table named “borrow_info” in the “library” database that contains 6 fields. Here, the “id” field is the primary key but the auto_increment attribute is not used for this field. So, a unique value is inserted manually into this field when a new record is inserted into the table. The book_id and the member_id fields are foreign keys for this table; those are the primary key of the “books” table and “members” table. The data type of borrow_date and return_date fields are date. So, these two fields store the date value in the “YYYY-MM-DD” format.

CREATE TABLE borrow_info (
id INT,
borrow_date DATE,
book_id INT,
member_id INT,
return_date DATE,
STATUS VARCHAR(10),
PRIMARY KEY (id),
FOREIGN KEY (book_id) REFERENCES books(id),
FOREIGN KEY (member_id) REFERENCES members(id));

The output shows that the “borrow_info” table is created successfully:

Rename the Table Name

The ALTER TABLE statement can be used for multiple purposes in the SQL statements. Run the following ALTER TABLE statement to change the name of the “borrow_info” table to “book_borrow_info”. Next, the SHOW tables statement can be used to check if the name of the table has been changed or not.

ALTER TABLE borrow_info RENAME TO book_borrow_info;
SHOW TABLES;

The output shows that the table name has been changed successfully and the name of the borrow_info table has been changed to book_borrow_info:

Add a New Column to the Table

The ALTER TABLE statement can be used to add or delete one or more columns after creating the table. The following ALTER TABLE statement adds a new field named “status” to the table members. The DESCRIBE statement is used to show whether the table structure has been changed or not.

ALTER TABLE members ADD STATUS VARCHAR(10);
DESCRIBE members;

The output shows that a new column which is “status” is added to the “members” table and the data type of the table is varchar:

Remove the Column from the Table

The following ALTER TABLE statement deletes the field named “status” from the “members” table. The DESCRIBE statement is used to show whether the table structure has been changed or not.

ALTER TABLE members DROP COLUMN STATUS;
DESCRIBE members;

The output shows that the “status” column is removed from the “members” table:

Insert a Single Row into the Table

The INSERT INTO statement is used to insert one or more rows into the table. Run the following SQL statement to insert a single row into the “books” table. Here, the “id” field is omitted from this query because it is inserted automatically into the record when a new record is inserted for the auto-increment attribute. If this field is used in the INSERT statement, the value must be NULL.

INSERT  INTO books (title, author, publication, isbn, total_copy, price)
VALUES ('SQL in 10 Minutes', 'Ben Forta', 'Sams Publishing', '784534235', 5, 39);

The output shows that a record is added to the “books” table successfully:

The data can be inserted into the table using the SET clause where each field value is assigned separately. Run the following SQL statement to insert a single row into the “members” table using the INSERT INTO and SET clauses. The “id” field is also omitted in this query like the previous example for the same reason.

INSERT INTO members
SET name='John Sina', address='34, Dhanmondi 9/A, Dhaka', contact_no='+14844731336', email='[email protected]';

The output shows that a record is added to the members table successfully:

Run the following SQL statement to insert a single row into the “book_borrow_info” table:

INSERT  INTO book_borrow_info (id, borrow_date, book_id, member_id, return_date, STATUS)
VALUES (1, '2023-03-12', 1, 1, '2023-03-19' , 'Borrowed');

The output shows that a record is added to the “book_borrow_info” table:

Insert Multiple Rows into the Table

Sometimes, it requires adding many records at a time using a single INSERT INTO statement. Run the following SQL statement to insert three records into the “books” table using a single INSERT INTO statement. In this case, the VALUES clause is used for one time and the data of each record are separated by comma.

INSERT INTO books (title, author, publication, isbn, total_copy, price)
VALUES
("SQL Cookbook (O'Reilly)", "Anthony Molinaro", "O'Reilly", "2467777532", 10, 49),
("SQL Queries for Mere Mortals", "John Viescas", "Addison-Wesley", '673456234', 15, 35),
("Learning SQL", "Alan Beaulieu", "Penguin Books Ltd", "534433222", 12, 45);

The output shows that three records are added to the “books” table:

Read All of the Particular Fields from the Table

The SELECT statement is used to read the data from the “database” table. The “*” symbol is used to denote all fields of the table in the SELECT statement. Run the following SQL command to read all records of the books table:

SELECT * FROM books;

The output shows all records of the books table that contains 4 records:

Run the following SQL command to read all records of three fields of the “members” table:

SELECT name, email, contact_no FROM members;

The output shows all records of three fields of the “members” table:

Read the Table After Filtering the Data from the Table

The WHERE clause is used to read the data from a table based on one or more conditions. Run the following SELECT statement to read all records of all fields of the “books” table where the author name is “John Viescas”.

SELECT * FROM books WHERE author='John Viescas';

The “books” table contains one record that matches the condition of the WHERE clause which is shown in the output:

Read the Table After Filtering the Data Based on Boolean Logic

The Boolean AND logic is used to define multiple conditions in the WHERE clause that returns true if all conditions return true. Run the following SELECT statement to read all records of all fields of the “books” table where the value of the total_copy field is more than 10 and the value of the price field is less than 45 using the logical AND.

SELECT * FROM books WHERE total_copy > 10 AND price < 45;

The books table contains one record that matches the condition of the WHERE clause which is shown in the output:

The Boolean OR logic is used to define multiple conditions in the WHERE clause that returns true if any of the conditions returns true. Run the following SELECT statement to read all records of all fields of the “books” table where the value of the total_copy field is more than 10 or the value of the price field is more than 40.

SELECT * FROM books WHERE total_copy > 10 OR price > 40;

The books table contains three records that match the condition of the WHERE clause which is shown in the output:

The Boolean NOT logic is used to return false when the condition is true and returns true when the condition is false. Run the following SELECT statement to read all records of all fields of the “books” table where the value of the author field is not “Addison-Wesley”.

SELECT * FROM books WHERE NOT author ='Addison-Wesley';

The “books” table contains three records that match the condition of the WHERE clause which is shown in the output:

Read the Table After Filtering the Rows Based on the Range of Data

The BETWEEN clause is used to read the range of data from the database table. Run the following SELECT statement to read all records of all fields of the “books” table where the value of the price field is between 40 to 50.

SELECT * FROM books WHERE price BETWEEN 40 AND 50;

The books table contains two records that match the condition of the WHERE clause which is shown in the output. The books of the price values, 39 and 35, are omitted from the result set because those are out of range.

Read the Table After Sorting the Table

The ORDER BY clause is used to sort the result set of the SELECT statement in ascending or descending order. The result set is sorted in ascending order by default if the ORDER BY clause is used without ASC or DESC. The following SELECT statement reads the sorted records from the books table based on the title field:

SELECT * FROM books ORDER BY title;

The data of the title field of the “books” table is sorted in ascending order in the output. The “Learning SQL” book comes first alphabetically if the title field of the “books” table is sorted in ascending order.

Read the Table by Setting the Alternative Name of the Column

The alternative name of the column is used in the query to make the result set more readable. The alternative name is set using the “AS” keyword. The following SQL statement returns the values of the title and author fields by setting the alternative names.

SELECT title AS `Book Name`, author AS `Author Name`
FROM books;

The title field is displayed with the alternative name which is “Book Name” and the author field is displayed with the alternative name which is “Author Name” in the output.

Count the Total Number of Rows in the Table

The COUNT() is an aggregate function of SQL that is used to count the total number of rows based on the particular field or all fields. The “*” symbol is used to denote all fields and the COUNT(*) is used to count all records of the table.

The following query counts the total records of the books table:

SELECT COUNT(*) AS `Total Books` FROM books;

Four records in the “books” table are shown in the output:

The following query counts the total rows of the “members” table based on the “id” field:

SELECT COUNT(id) AS `Total Members` FROM members;

The “members” table has two id values that are printed in the output:

Read the Data from Multiple Tables

The previous SELECT statements retrieved the data from a single table. But the SELECT statement can be used to retrieve the data from two or more tables. The following SELECT query reads the values of the title and author fields from the “books” table and the borrow_date from the “book_borrow_info” table.

SELECT title, author, borrow_date
FROM books, book_borrow_info
WHERE books.id = book_borrow_info.book_id;

The following output shows that the “SQL in 10 Minutes” book is borrowed two times and the “SQL Cookbook (O’Reilly)” book is borrowed one time:

The data can be retrieved from the multiple tables using different types of JOINS such as INNER JOIN, OUTER JOIN, etc. which are not explained in this tutorial.

Read the Table by Grouping the Particular Fields 

The GROUP BY clause is used to read the records from the table by grouping the rows based on one or more fields. This type of query is called a summary query. You have to insert multiple rows in the tables to check the use of the GROUP BY clause. Run the following INSERT statements to insert one record into the “members” table and two records into the “book_borrow_info” table.

INSERT  INTO members
SET name='Ella Hasan', address='11/A, Jigatola, Dhaka', contact_no='+8801734563423', email='[email protected]';
INSERT  INTO book_borrow_info (id, borrow_date, book_id, member_id, return_date, STATUS)
VALUES (2, '2023-04-10', 1, 1, '2023-04-15' , 'Returned');
INSERT  INTO book_borrow_info (id, borrow_date, book_id, member_id, return_date, STATUS)
VALUES (3, '2023-05-20', 2, 1, '2023-05-30', 'Borrowed');

After inserting the data by executing the previous queries, run the following SELECT statement that counts the total number of borrowed books and member’s name based on each member using the GROUP BY clause. Here, the COUNT() function works on the field that is used to regroup the records using the GROUP BY clause. The book_id field of the “members” table is used for grouping here.

SELECT COUNT(book_id) AS `Total book borrowed`, name AS `Member Name` FROM books,members, book_borrow_info  WHERE books.id = book_borrow_info.book_id AND members.id = book_borrow_info.member_id GROUP BY book_borrow_info.member_id;

According to the data of the books, “members” and “book_borrow_info” tables, “John Sina” borrowed 2 books and “Ella Hasan” borrowed 1 book.

Read the Table After Omitting the Duplicate Values

Sometimes, duplicate data are generated in the result set of the SELECT statement based on the table data that is unnecessary. For example, the following SELECT statement returns the duplicate records for the data of the “book_borrow_info” table.

SELECT name, email
FROM members, book_borrow_info
WHERE book_borrow_info.member_id = members.id;

In the output, the same record appears twice because the “John Sina” member borrowed two books. This problem can be solved using the DISTINCT keyword. It removes the duplicate records from the query result.

The following SELECT statement generates unique records of the result set from the “members” and “book_borrow_info” tables after omitting the duplicate values using the DISTINCT keyword in the query.

SELECT DISTINCT name, email
FROM members, book_borrow_info
WHERE book_borrow_info.member_id = members.id;

The output shows that the duplicate value is removed from the result set:

Read the Table by Limiting the Row Number

Sometimes, it requires reading the particular number of records from the beginning of the result set, the end of the result set, or the middle of the result set from the database table by limiting the row number. It can be done in many ways. Before limiting the rows, run the following SQL statement to check how many records exist in the books table:

SELECT * FROM books;

The output shows that the books table has four records:

The following SELECT statement reads the first two records from the “books” table using the LIMIT clause with the value of 2:

SELECT * FROM books LIMIT 2;

The first two records of the “books” table are retrieved which is shown in the output:

The FETCH clause is the alternative of the LIMIT clause and its use is shown in the following SELECT statement. The first 3 records of the “books” table are retrieved using the FETCH FIRST 3 ROWS ONLY clause in the SELECT statement:

SELECT * FROM books FETCH FIRST 3 ROWS ONLY;

The output shows the first 3 records of the “books” table:

Two records from the 3rd row of the books table are retrieved by executing the following SELECT statement. The LIMIT clause is used with the 2, 2 value here where the first 2 defines the starting position of the row of the table that starts counting from 0 and the second 2 defines the number of rows that starts counting from the starting position.

SELECT * FROM books LIMIT 2,2;

The following output appears after executing the previous query:

The records from the end of the table can be read by sorting the table in descending order based on the auto-incremented primary key value and using the LIMIT clause. Run the following SELECT statement that reads the last 2 records from the “books” table. Here, the result set is sorted in descending order based on the “id” field.

SELECT * FROM books ORDER BY id DESC LIMIT 2;

The last two records of the books table are shown in the following output:

Read the Table Based on the Partial Match

The LIKE clause is used with the “%” symbol to retrieve the records from the table by partial matching. The following SELECT statement searches the records from the “books” table where the author field contains “John” at the beginning of the value using the LIKE clause. Here, the “%” symbol is used at the end of the search string.

SELECT * FROM books WHERE author LIKE 'John%';

Only one record exists in the “books” table that contains the “John” string at the start of the value of the author field.

The following SELECT statement searches the records from the “books” table where the publication field contains the “Ltd” at the end of the value using the LIKE clause. Here, the “%” symbol is used at the beginning of the search string:

SELECT * FROM books WHERE publication LIKE '%Ltd';

Only one record exists in the “books” table that contains the “Ltd” string at the end of the publication field.

The following SELECT statement searches the records from the “books” table where the title field contains the “Queries” anywhere of the value using the LIKE clause. Here, the “%” symbol is used on both sides of the search string:

SELECT * FROM books WHERE title LIKE '%Queries%';

Only one record exists in the “books” table that contains the “Queries” string at the title field.

Count the Sum of the Particular Field of the Table

The SUM() is another useful aggregate function of SQL that calculates the sum of the values of any numeric field of the table. This function takes one argument that must be numeric. The following SQL statement calculates the sum of all values of the price field of the “books” table that contains integer values.

SELECT SUM(price) AS `Total Book Price`
FROM books;

The output shows the summation value of all values of the price field of the “books” table. Four values of the price field are 39, 49, 35, and 45. The sum of these values is 168.

Find the Maximum and Minimum Values of the Particular Field

The MIN() and MAX() aggregate functions are used to find out the minimum and maximum values of the particular field of the table. Both functions take one argument that must be numeric. The following SQL statement finds out the minimum price value from the “books” table which is an integer.

SELECT MIN(price) AS `Book of minimum cost` FROM books;

Thirty-five (35) is the minimum value of the price field that is printed in the output.

The following SQL statement finds out the maximum price value from the “books” table:

SELECT MAX(price) AS `Book of maximum cost` FROM books;

Forty-nine (49) is the maximum value of the price field that is printed in the output.

Read the Particular Part of the Data or a Field

The SUBSTR() function is used in the SQL statement to retrieve the particular portion of the string data or the value of the particular field of a table. This function contains three arguments. The first argument contains the string value or a field value of a table which is a string. The second argument contains the starting position of the sub-string that is retrieved from the first argument and the counting of this value starts from 1. The third argument contains the length of the sub-string that starts counting from the starting position.

The following SELECT statement cuts and prints the first five characters from the “Learn SQL Basics” string where the starting position is 1 and the length is 5:

SELECT SUBSTR("Learn SQL Basics", 1, 5) AS `Substring Value`;

The first five characters of the “Learn SQL Basics” string is “Learn” which is printed in the output.

The following SELECT statement cuts and prints the SQL from the “Learn SQL Basics” string where the starting position is 7 and the length is 3:

SELECT SUBSTR("Learn SQL Basics", 7, 3) AS `Substring Value`;

The following output appears after executing the previous query:

The following SELECT statement cuts and prints the first five characters from the name field of the “members” table:

SELECT SUBSTR(name, 1, 5) AS `Member Name` FROM members;

The output shows the first five characters of each value of the name field of the “members” table.

Read the Table Data After Concatenation

The CONCAT() function is used to generate the output by combining one or more fields of a table or adding the string data or the particular field value of the table. The following SQL statement reads the values of the title, author, and price fields of the “books” table, and the “$”string value is added with each value of the price field using the CONCAT() function.

SELECT title AS Title, author AS Author, CONCAT('$', price) AS Price
FROM books;

The values of the price field are printed in the output by concatenating with the “$” string.

Run the following SQL statement to combine the values of the title and author fields of the “books” table with the “by” string value using the CONCAT() function:

SELECT CONCAT(title,' by ', author) AS `Book name with author`
FROM books;

The following output appears after executing the previous SELECT query:

Read the Table Data After a Mathematical Calculation

Any mathematical calculation can be performed at the time of retrieving the values of the table using a SELECT statement. Run the following SQL statement to read the id, title, price, and discounted price value after calculating the 5% discount.

SELECT id, title, price AS `Regular Price`, price-(price*5/100) AS `Discount Price`
FROM books;

The following output shows the regular price and discount price of each book:

Create a View of the Table

The VIEW is used to make the query simple and provides extra security to the database. It works like a virtual table that is generated from one or more tables. The method of creating and executing a simple VIEW based on the “members” table is shown in the following example. The VIEW is executed using the SELECT statement. The following SQL statement creates a VIEW of the “members” table with the id, name, address, and contact_no fields. The SELECT statement executes the member_view.

CREATE VIEW member_view AS
SELECT id, name, address, contact_no
FROM members;

SELECT * FROM member_view;

The following output appears after creating and executing the view:

Update the Table Based on the Particular Condition

The UPDATE statement is used to update the content of the table. If any UPDATE query is executed without the WHERE clause, all fields that are used in the UPDATE query are updated. So, it is necessary to use an UPDATE statement with the proper WHERE clause. Run the following UPDATE statement to update the name and contact_no fields where the value of the id field is 1. Next, execute the SELECT statement to check whether the data is updated properly or not.

UPDATE members
SET name='Janifer', contact_no='+880175621223'
WHERE id=1;

SELECT * FROM members;

The following output shows that the UPDATE statement is executed successfully. The value of the name field is changed to “Janifer” and the contact_no field is changed to “+880175621223” of the record which contains the id value of 1 using the UPDATE query:

Delete the Table Data Based on the Particular Condition

The DELETE statement is used to delete the specific content or all content of the table. If any DELETE query is executed without the WHERE clause, all fields are deleted. So, it is necessary to use the UPDATE statement with the proper WHERE clause. Run the following DELETE statement to delete all data from the books table where the id value is 4. Next, execute the SELECT statement to check whether the data is deleted properly or not.

DELETE FROM books WHERE id=4;
SELECT * FROM books;

The following output shows that the DELETE statement is executed successfully. The 4th record of the books table is removed using the DELETE query:

Delete All Records from the Table

Run the following DELETE statement to delete all records from the “books” table where the WHERE clause is omitted. Next, execute the SELECT query to check the table content.

DELETE FROM book_borrow_info;
SELECT * FROM book_borrow_info;

The following output shows that the “books” table is empty after executing the DELETE query:

If any table contains an auto-increment attribute and all records are deleted from the table, the auto-increment field starts counting from the last increment when a new record is inserted after making the table empty. This problem can be solved using the TRUNCATE statement. It is also used to delete all records from the table but the auto-increment field starts counting from 1 after deleting all records from the table. The SQL of the TRUNCATE statement is shown in the following:

TRUNCATE book_borrow_info;

Drop the Table

One or more tables can be dropped by checking or without checking whether the table exists or not. The following DROP statements delete the “book_borrow_info” table and the “SHOW tables” statement checks whether the table exists or not on the server.

DROP TABLE book_borrow_info;
SHOW TABLES;

The output shows that the “book_borrow_info” table is dropped.

The table can be dropped after checking whether it exists on the server or not. Run the following DROP statement to delete the books and members table if these tables exist in the server. Next, the “SHOW tables” statement checks whether the tables exist or not on the server.

DROP TABLE IF EXISTS books, members;
SHOW TABLES;

The following output shows that the tables are deleted from the server:

Drop the Database

Run the following SQL statement to delete the “library” database from the server:

DROP DATABASE library;

The output shows that the database is dropped.

Conclusion

The mostly used SQL query examples to create, access, modify, and delete the database of the MariaDB server are shown in this tutorial by creating a database and three tables. The uses of different SQL statements are explained with very simple examples to help the new database user to learn the SQL basics properly. The uses of complex queries are omitted here. The new database users will be able to start working with any database after reading this tutorial properly.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.