What is MySQL SELECT Statement?

The MySQL SELECT statement in the SQL is used to select data from a database. The data returned is stored in a result table, called the result set.

Before proceeding further let’s create a Students table that has 5 columns as follows.

We can use MySQL workbench or toolkit to create the table.

Query to create a table:

CREATE TABLE `test_schema1`.`students` (
  `roll_num` INT NOT NULL,
  `name` VARCHAR(45) NULL,
  `marks` INT NULL,
  `class` INT NULL,
  `gender` VARCHAR(1) NULL,
  PRIMARY KEY (`RollNum`));

 Once the table is created we will add some dummy data to the table as follows.

roll_numnamemarksclassgender
1KMS4654M
2MYG4892F
3BBH3901F
4DKS4924M
5PCY3541M
6KJN3433F
7ZYX4503M
8LPQ2305F
9KMS3402M
10OSH2505M
11KNJ3803F
12KTV4004F
13JJK3724M
14JJH2303F
15KJM3422M
16PJM2833F

Now we will See how we can use the select statement 

Syntax:

SELECT column_name1, column_name2, ..., column_name_n FROM schema_name.table_name;

Note: if we have the schema selected then we can exclude the schema name.

  1. Select all columns:
select * from test_schema1.students;

This will return all the data present in the table with all the columns selected.

  1. Select some columns:
select roll_num, name, marks from students;

This will return only selected columns only with all the data returned as shown below

  1. SELECT DISTINCT Statement:

To get the distinct values from the lists we can use the select distinct statement as follows.

select distinct class from students;

This will select the distinct values for the particular column or group of columns from the table as shown below.

  1. Count the number of values.
SELECT COUNT(roll_num) FROM students;

This will return the count of students in the table. 

If we want to count distinct classes from the table we can use the following query:

SELECT COUNT(distinct class) FROM students;

-A blog by Shwetali Khambe

Related Posts