MySQL SELECT Lauseke esimerkkeineen

⚡ Älykäs yhteenveto

MySQL SELECT statement retrieves rows from one or more tables, and every example below runs against the myflix sample database, moving from the plain star query to expressions, column aliases, and string functions.

  • 🔎 Ydintarkoitus: SELECT fetches stored rows that match a criteria, from the command prompt or from PHP, Python, ja muilla kielillä.
  • 🧩 Syntax Order: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY must appear in that fixed sequence.
  • Star Shortcut: SELECT * FROM `members`; returns every column, while naming columns explicitly keeps result sets smaller and faster.
  • 🔗 Ilmaisut: Concat() joins column values, and LEFT() trims characters, so computed fields appear directly in the result set.
  • 🏷️ Column Aliases: The optional AS keyword renames any expression, replacing unreadable headers such as Concat(`title`) with clear labels.
  • 🖱️ Workbench Comparison: MySQL Workbench generates queries visually, yet hand-written SELECT statements remain necessary for complex, precise retrieval.

What is SELECT Query in MySQL?

SELECT query is used to fetch data from the MySQL tietokanta. Tietokannat tallentavat tiedot myöhempää hakua varten. Tarkoitus MySQL SELECT is to return one or more rows from the database tables that match a given criteria. A SELECT query can be used in a scripting language like PHP or Ruby, or you can execute it from the command prompt.

VALITSE kysely sisään MySQL

Because SELECT is the command you will run most often, it pays to learn its syntax before touching the sample data.

SQL SELECT Statement Syntax

SELECT is the most frequently used SQL command, and it has the following general syntax:

SELECT [DISTINCT|ALL] { * | [fieldExpression [AS newName]} FROM tableName [alias] [WHERE condition] [GROUP BY fieldName(s)] [HAVING condition] [ORDER BY fieldName(s)];

TÄÄLTÄ

  • VALITSE on SQL-avainsana, jonka avulla tietokanta tietää, että haluat hakea tietoja.
  • [DISTINCT | KAIKKI] are optional keywords that fine-tune the results returned from the SQL SELECT statement. If nothing is specified, then ALL is assumed as the default.
  • {*| [fieldExpression [AS newName]} at least one part must be specified. “*” selects all the fields from the specified table name; fieldExpression performs computations on the specified fields, such as adding numbers or joining two string fields into one.
  • FROM tableName is mandatory and must contain at least one table. Multiple tables must be separated using commas or joined using the JOIN keyword.
  • MISTÄ condition is optional. It specifies criteria in the result set returned from the query.
  • GROUP BY käytetään koota tietueita, joilla on samat kenttäarvot.
  • oTTAA condition is used to specify criteria when working with the GROUP BY keyword.
  • TILAUS käytetään määrittämään tulosjoukon lajittelujärjestys.

*

The star symbol selects all the columns in a table. A simple SELECT statement looks like the one shown below.

SELECT * FROM `members`;

The statement above selects all the fields from the members table. The semicolon is a statement terminator. It is not mandatory, but ending your statements this way is considered good practice.

SELECT DISTINCT and LIMIT in MySQL

Two optional keywords in the syntax deserve a closer look, because beginners meet them as soon as a table grows.

DISTINCT removes duplicate rows from the result set. The movies table stores several films released in 2007, so a plain query repeats that year. DISTINCT returns each value once.

SELECT DISTINCT `year_released` FROM `movies`;

RAJOITA caps the number of rows returned, which protects the client from a query that would otherwise pull millions of records.

SELECT * FROM `movies` LIMIT 5;
avainsana Mitä se tekee Milloin sitä käytetään
ALL (default) Returns every matching row, duplicates included Counting or listing raw records
DISTINCT Collapses duplicate rows into one Building a list of unique values
RAJOITA Returns only the first N rows Previewing data or paging results

With the syntax settled, the sample database brings these clauses to life.

SELECT Statement Practical Examples

Lataa napsauttamalla tätä the myflix DB used for the practical examples.

You can learn how to import the .sql file into MySQL Työpöytä.

The examples are performed on the following two tables.

Taulukko 1: jäseniä taulukko

jäsennumero full_names sukupuoli syntymäaika fyysinen osoite postiosoite yhteystieto_ numero email
1 Janet Jones Nainen 21-07-1980 First Street -tontti nro 4 Yksityinen laukku 0759 253 542 janetjones@yagoo.cm
2 Janet Smith Jones Nainen 23-06-1980 Melrose 123 NULL NULL jj@fstreet.com
3 Robert Phil Mies 12-07-1989 3rd Street 34 NULL 12345 rm@tstreet.com
4 Gloria Williams Nainen 14-02-1984 2nd Street 23 NULL NULL NULL

Taulukko 2: Elokuvat taulukko

elokuvan_tunnus otsikko johtaja vuosi_vapautettu kategorian_tunnus
1 Pirates of the Caribbean 4 Rob Marshall 2011 1
2 Sarah Marshal unohdetaan Nicholas Stoller 2008 2
3 X-Men NULL 2008 NULL
4 Code Nimi Musta Edgar Jimz 2010 NULL
5 Isän pienet tytöt NULL 2007 8
6 enkelit ja demonit NULL 2007 6
7 DaVinci Code NULL 2007 6
9 Honey mooners John Schultz 2005 8
16 67% syyllinen NULL 2012 NULL

Getting Members Listing

Suppose we want a list of all the registered library members from our database. We would use the script shown below to do that.

SELECT * FROM `members`;

Executing the script in MySQL Workbench produces the following results.

jäsennumero full_names sukupuoli syntymäaika fyysinen osoite postiosoite yhteystieto_ numero email
1 Janet Jones Nainen 21-07-1980 First Street -tontti nro 4 Yksityinen laukku 0759 253 542 janetjones@yagoo.cm
2 Janet Smith Jones Nainen 23-06-1980 Melrose 123 NULL NULL jj@fstreet.com
3 Robert Phil Mies 12-07-1989 3rd Street 34 NULL 12345 rm@tstreet.com
4 Gloria Williams Nainen 14-02-1984 2nd Street 23 NULL NULL NULL

The query returned all the rows and columns from the members table.

Selecting Specific Columns

Say we are interested only in the full_names, gender, physical_address, and email fields. The following script achieves this.

SELECT `full_names`,`gender`,`physical_address`, `email` FROM `members`;

Executing the script in MySQL Workbench produces the following results.

full_names sukupuoli fyysinen osoite email
Janet Jones Nainen First Street -tontti nro 4 janetjones@yagoo.cm
Janet Smith Jones Nainen Melrose 123 jj@fstreet.com
Robert Phil Mies 3rd Street 34 rm@tstreet.com
Gloria Williams Nainen 2nd Street 23 NULL

Getting Movies Listing With Expressions

Expressions can also be used in SELECT statements. Say we want a list of movies with the title and the name of the director in one field, the director in brackets, plus the year the movie was released. The following script does that.

SELECT Concat(`title`, ' (', `director`, ')') , `year_released` FROM `movies`;

TÄÄLTÄ

  • The Concat() MySQL function joins column values together.
  • The line “Concat(`title`, ‘ (‘, `director`, ‘)’)” gets the title, adds an opening bracket followed by the name of the director, then adds the closing bracket.
  • String portions are separated using commas inside the Concat() function.

Executing the script in MySQL Workbench produces the following result set.

Concat(`title`, '(', `ohjaaja', ')') vuosi_vapautettu
Pirates of the Caribean 4 (Rob Marshall) 2011
Sarah Marshalin unohtaminen (Nicholas Stoller) 2008
NULL 2008
Code Nimi Black (Edgar Jimz) 2010
NULL 2007
NULL 2007
NULL 2007
Honey mooners (John Schultz) 2005
NULL 2012

Huomautus: Concat() returns NULL when any argument is NULL, which is why films without a director show NULL above.

Alias Field Names

The example above returned the concatenation code as the field name. To use a more descriptive field name in the result set, apply a column alias. The basic syntax follows.

SELECT `column_name|value|expression` [AS] `alias_name`;

TÄÄLTÄ

  • “SELECT `column_name|value|expression`” is the regular SELECT statement, which can be a column name, value, or expression.
  • "[KUTEN]" is the optional keyword before the alias name.
  • "alias_name" is the alias that is returned in the result set as the field name.

The same query with a more meaningful column name:

SELECT Concat(`title`, ' (', `director`, ')') AS `Concat`, `year_released` FROM `movies`;

We get the following result.

Concat vuosi_vapautettu
Pirates of the Caribean 4 (Rob Marshall) 2011
Sarah Marshalin unohtaminen (Nicholas Stoller) 2008
NULL 2008
Code Nimi Black (Edgar Jimz) 2010
NULL 2007
NULL 2007
NULL 2007
Honey mooners (John Schultz) 2005
NULL 2012

Getting Members Listing Showing the Year of Birth

Suppose we want a list of all members showing the membership number, full names, and year of birth. We can use the LEFT string function to extract the year of birth from the date of birth field.

SELECT `membership_number`,`full_names`,LEFT(`date_of_birth`,4) AS `year_of_birth` FROM members;

TÄÄLTÄ

  • "LEFT(`syntymäpäivä`,4)" Ishayoiden opettaman LEFT merkkijonofunktio accepts the date of birth as the parameter and returns only 4 characters from the left.
  • "AS `syntymävuosi" on sarakkeen aliaksen nimi returned in our results. The AS-avainsana on valinnainen; you can leave it out and the query still works.

Executing the query in MySQL Workbench against the myflixdb gives us the results shown below.

jäsennumero full_names syntymävuosi
1 Janet Jones 1980
2 Janet Smith Jones 1980
3 Robert Phil 1989
4 Gloria Williams 1984

Hand-written queries are only one route to a result set. Workbench can also build the statement for you.

SQL Using MySQL Työpöytä

Aiomme nyt käyttää MySQL Workbench to generate the script that displays all the field names from our categories table.

1. Right-click on the Categories table. Click on “Select Rows – Limit 1000”.

2. MySQL Workbench automatically creates a SQL query and pastes it in the editor.

3. Query results are shown in the grid below the editor.

SQL:n käyttö MySQL Työpöytä

As the screenshot shows, we did not write the SELECT statement ourselves. MySQL Workbench generated it for us.

Why Use the SELECT SQL Command When We Have MySQL Työpöytä?

You might be wondering why you should learn the SQL SELECT command when a tool such as MySQL Workbench returns the same results without any knowledge of the SQL language. That shortcut is possible, but learning the SELECT command antaa sinulle enemmän joustavuus ja ohjaus yli sinun SQL SELECT -lauseet.

MySQL Workbench falls into the category of “Kysely esimerkin mukaan” (QBE) tools. It is intended to generate SQL statements faster and increase user productivity.

Learning the SQL SELECT command lets you create monimutkaiset kyselyt that cannot easily be generated by Query by Example utilities such as MySQL Työpöytä.

To improve productivity, you can generate the code in MySQL Työpöytä, sitten räätälöidä se täyttää vaatimukset. That is only possible once you understand how the SQL statements work.

Ymmärtäminen MySQL SELECT-lause

UKK

Usually yes. SELECT * reads every column, including large text and blob fields you may not need, and it blocks covering indexes. Naming the columns keeps the result set smaller and the query faster.

Keywords such as SELECT and FROM are not case sensitive. String comparisons follow the collation of the column, so a case-insensitive collation such as utf8mb4_0900_ai_ci treats “Janet” and “janet” as equal.

A missing index is the usual cause. Run EXPLAIN before the query to see whether MySQL performs a full table scan, then index the filtered or joined columns and return only the rows you need.

Yes. Text-to-SQL assistants convert a plain request into a SELECT statement once they know your schema. Review the generated joins and filters, because an AI model can invent column names that do not exist.

No. AI drafts a query quickly, but you still verify the logic, the joins, and the performance in MySQL Työpöytä. Knowing SELECT is what lets you spot a wrong result before it reaches production.

Tiivistä tämä viesti seuraavasti: