A query is a command used to interact with a database. When you interact with a MySQL database, queries are written in the SQL language.
Below are all of the common MySQL query commands as well as examples of common queries.
Common query functions
SELECT
— used to retrieve objects from a database tableINSERT
— used to insert new objects into a database tableUPDATE
— used to update existing objects in a database tableDELETE
— used to delete objects from a database tableFROM
— used to specify the database table you wish to interact withWHERE
— used to filter the objects retrieved based on specified criteriaLIMIT
— used to restrict the number of objects retrieved via a queryLIKE
— used to perform string comparisons; the%
wildcard matches any number of characters, even zero characters; e.g. to select animals whosetype
contains “wolf”, you could useSELECT * FROM animals WHERE type LIKE '%wolf%'
Queries to Select, Insert, Update, and Delete objects in a MySQL database
Say, for example, you have a database table, cars
, with the following columns:
make
— aVARCHAR
column with the brand/company that made the carmodel
— aVARCHAR
column with the car’s modelyear
— aYEAR
column with the year the car was made
Selecting objects:
/* select all cars */
SELECT * FROM cars;
/* select only the model and year of all cars */
SELECT model, year FROM cars;
/* select all Chevys */
SELECT * FROM cars WHERE make = 'Chevy';
/* select all Corvette and Corvette variations */
SELECT * FROM cars WHERE model LIKE '%corvette%';
/* select the first 10 Chevys */
SELECT * FROM cars WHERE make = 'Chevy' LIMIT 10;
Inserting an object:
/* create a new 1969 Chevy Corvette */
INSERT INTO cars
(make, model, year)
VALUES
('Chevrolet', 'Corvette', 1969);
Updating an object:
/* update the model of all 1969 Chevys to "Corvette Stingray" */
UPDATE cars
SET model = 'Corvette Stingray'
WHERE make = 'Chevrolet' AND year = 1969;
Deleting objects:
/* delete all Chevys */
DELETE FROM cars
WHERE make = 'Chevrolet';