SQL Queries
A query is a request for data or information from a database table or combination of tables. This query can be thought of as providing a "view" of the database, which means it presents a specific slice or interpretation of the database data according to the query's conditions and structure.
Queries that view the database contents use the SELECT keyword
SELECT Query
The simplest form of SELECT query uses the * wildcard operator to retrieve all database columns from the table.
Here's a basic SQL SELECT query that retrieves all columns for all customers in the Customers table:
SELECT * FROM Customers;
If you only want to retrieve data from certain columns then you can specific the column data the you wish to retrieve:
SELECT CustomerName, EmailAddress FROM Customers;
Which SQL keyword is used to retrieve data from a database table?
Filtering using WHERE
Queries can filter data based on specific criteria, showing only the data that meets these conditions.
SELECT name, department, salary
FROM employees
WHERE department = 'Marketing'
This query selects employees in the Marketing department.
Which SQL keyword is used to filter rows based on a specified condition?
ORDER BY Clause
The ORDER BY clause in SQL is used to sort the result set of a query by one or more columns. It can sort the data in ascending order (which is the default) or descending order, based on the specified column(s).
Example: Employees Table
If you want to retrieve all employees' first and last names, sorted by the LastName in ascending order and then by FirstName in descending order, your query would look like this:
SELECT FirstName, LastName
FROM Employees
ORDER BY LastName ASC, FirstName DESC;
LIKE Operator
The LIKE operator in SQL is used in a WHERE clause to search for a specified pattern in a column. It's particularly useful when you want to perform searches on strings, such as finding rows with columns that contain a certain substring, begin with specific characters, or end with specific characters. The % and _ are two wildcards often used with LIKE:
- % represents zero, one, or multiple characters.
- _ represents a single character.
SELECT * FROM Employees
WHERE Name LIKE 'J%';
This query will retrieve all rows from Employees where the Name starts with 'J', regardless of what follows after 'J'.
Which SQL keyword is used to match a value against a pattern using wildcard characters?
Complete! Ready to test your knowledge?
SELECT Queries
- SQL Queries
- SELECT Query
- Filtering using WHERE
- ORDER BY Clause
- LIKE Operator