SQL stands for Structured Query Language. It allows the user to access and perform operations on databases.
SELECT
query in SQLSELECT
is one of the most used queries in SQL. The purpose of the SELECT
query is to select data from the database.
The syntax of the SELECT
query is given below.
SELECT column_name1, column_name2, ... FROM table_name
column_name1
and column_name2
are columns we want data from. table_name
is the name of the table in the database in which these columns exist.
Let’s take an example of a basic database table named PERSONAL_INFO
.
The table above contains a list of people with their personal information, such as Name, Age, Gender, and the City where they live.
We can use the SELECT
query to select data from the database above in various ways.
Let’s discuss some examples of the SELECT
query.
SELECT * FROM PERSONAL_INFO
The code above selects all the data from all the columns in the database and returns everything that is present there. The output of the code is given below.
We can also select specific columns from the database. Let’s discuss an example in which we want the name of the person and their gender.
The SELECT
query will be as follows.
SELECT Name, Gender FROM PERSONAL_INFO
The query above selects the Name
and Gender
columns from the database and drops all other columns (Age
and City
), then displays the table from the filtered data.
The columns mentioned in the query must be present in the database; otherwise, it will throw an error. The output of the code above will be as follows.
We can also get data from specific rows with SELECT
, FROM
, and WHERE
statements. WHERE
only displays the data from the rows that satisfy the condition after WHERE
in the SQL query.
The syntax is as follows.
SELECT column_name1, column_name2,... FROM table_name WHERE column_name='value'
WHERE
specifies the data that contains the rows with value
in column name
.
Let’s discuss some more examples.
SELECT * FROM PERSONAL_INFO WHERE Gender='Female'
The code above displays the data that contains all the columns (because we use *
after SELECT
) with rows in which the Gender
of the person is Female
.
The output of the code is as follows.
Here’s the last example, with data that contains specific rows and specific columns.
Suppose we want data with Name
, Age
, and City
, and the person’s age must be greater than or equal to 20.
The columns we want must be specified after the SELECT
statement, and the rows we want must be specified after the WHERE
statement.
The code is given below.
SELECT Name, Age, City FROM PERSONAL_INFO WHERE Age >= 20