SQL SELECT

SQL SELECT statement is used to select or get data from a database, as a result set.

Syntax

The syntax of a SQL SELECT statement is

SELECT select_list [ INTO new_table ]
[ FROM table_source ] [ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]
ADVERTISEMENT

Select All Columns from Table

SQL SELECT Query to select all columns from table table_source is

SELECT *
FROM table_source;

Examples

SELECT * FROM students;
SELECT * FROM employees;

Select Single Column from Table

SQL SELECT Query to select a specific column column1 from table table_source is

SELECT column1
FROM table_source;

Examples

SELECT name FROM students;
SELECT salary FROM employees;

Select Multiple Columns from Table

SQL SELECT Query to select multiple columns column1, column2, and column3 from table table_source is

SELECT column1, column2, column3
FROM table_source;

Examples

SELECT name, rollno FROM students;
SELECT name, id, role FROM employees;

Select from Table based on a Condition

SQL SELECT Query to select rows from table table_source based on a condition is

SELECT *
FROM table_source
WHERE condition;

Examples

SELECT * FROM students WHERE name='Arjun';
SELECT * FROM students WHERE rollno > 12;
SELECT * FROM employees WHERE id=25;
SELECT * FROM employees WHERE name LIKE '%John%';

Select from Table and Group By Column(s)

SQL SELECT Query to select rows from table table_source and group them by column column1 is

SELECT *
FROM table_source
GROUP BY column1;

Examples

SELECT * FROM students GROUP BY locality;
SELECT * FROM employees GROUP BY role;

Select from Table and Group By Column(s), Having Search Condition

SQL SELECT Query to select rows from table table_source, group them by column column1 and then having to pass the search condition SUM(column2) > 1000.

SELECT column1, SUM(column2) AS column2_sum   
FROM table_source  
GROUP BY column1   
HAVING SUM(column2) > 1000;

HAVING clause can be only used with GROUP BY clause.

Examples

SELECT role, SUM(salary) FROM employees GROUP BY role HAVING SUM(salary) > 2000.0;

Select from Table and Order By Column(s)

SQL SELECT Query to select rows from table table_source and order them by column column1 is

SELECT *
FROM table_source
ORDER BY column1;

Ascending is the default order. To order the rows in descending order of specific column, say column1, then the SQL SELECT Query is

SELECT *
FROM table_source
ORDER BY column1 DESC;

Examples

SELECT * FROM students ORDER BY name;
SELECT * FROM students ORDER BY name ASC;
SELECT * FROM students ORDER BY name DESC;
SELECT * FROM students ORDER BY name, locality;