In this tutorial you will learn about the MySQL Select Query and its application with practical example.
The SQL SELECT command is used to fetch data from MySQL database.
Table Of Contents−
MySql SELECT Syntax:
1 2 3 |
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 condition using a WHERE clause. But WHERE clause is an optional part of SELECT command.
- You can fetch one or more columns in a single SELECT query.
- You can specify star (*) in place of fields. In this case SELECT will return all the fields
- You can specify any condition using WHERE clause.
- You can specify an offset using OFFSET from where SELECT will start returning records. By default offset is zero
- You can limit the number of returned using LIMIT attribute.
Select all data
1 2 |
SELECT * FROM <table_name> |
MySql select specific columns
1 2 |
SELECT <column1,column2,...> FROM <table_name> |
MySql select specific rows
1 2 3 4 5 6 7 |
SELECT <column1,column2,...> FROM <table_name> WHERE <column1> operator <value> //For all columns SELECT * FROM <table_name> WHERE <expression> |
MySql select specific rows with AND operator
1 2 3 4 |
SELECT * FROM <table_name> WHERE <column1> operator <value> AND <column2> operator <value>; |
MySql select specific rows with OR operator
1 2 3 4 |
SELECT * FROM <table_name> WHERE <column1> operator <value> OR <column2> operator <value>; |
While fetching data you can write as complex SQL as you like. Procedure will remain same as mentioned above.
MySql select with LIMIT
The LIMIT clause can be used to limit the number of rows to be returned by the SELECT query. LIMIT takes one or two numeric arguments, which must both be non negative integer constants.With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
1 2 3 |
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15 SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows |