Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a single row in MySQL

Tags:

I am using MySQL, I have a table that has 9 columns. One of them is the primary key.

How can I select a single row, by the primary key or column 8 or 4?

like image 306
aggitan Avatar asked Sep 11 '09 18:09

aggitan


People also ask

How do I select a single row?

In SQLJ, a single-row query can be executed and its result set data can be retrieved with a single statement: SELECT ... INTO <select target list> . The INTO-clause contains a list of host variables or host expressions that receive the result set data.

How do I select a specific row in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

How do I select specific in MySQL?

If you want to select only specific columns, replace the * with the names of the columns, separated by commas. The following statement selects just the name_id, firstname and lastname fields from the master_name table.


3 Answers

If I understand your question correctly:

SELECT * FROM tbl WHERE id = 123 OR colname4 = 'x' OR colname8 = 'y' LIMIT 1

The 'LIMIT' keyword makes sure there is only one row returned.

like image 190
ChristopheD Avatar answered Oct 02 '22 04:10

ChristopheD


select *
from MyTable
where MyPrimaryKey = 123
like image 25
D'Arcy Rittich Avatar answered Oct 02 '22 04:10

D'Arcy Rittich


Columns in SQL don't have a defined 'order'. Database systems generally keep track of an order for display purposes, but it doesn't make sense to ask a database to select a column by number. You need to know the column's name in order to query its contents.

The same thing goes for the primary key (which, incidentally, may not be just a single column). You have to know which column it is, and what that column is named, in order to execute a query.

If you don't know these things, or need to figure them out dynamically, then

DESCRIBE tablename;

will tell you the names of each column, and whether it is part of the primary key or not. It will return a table that you can read, like any other result.

like image 30
Ian Clelland Avatar answered Oct 02 '22 02:10

Ian Clelland