SELECT Statements and Basic Queries
Difficulty: Basic
Generated on: 2025-07-10 02:21:19
Category: SQL Cheatsheet for Database Development
SQL SELECT Statements and Basic Queries Cheat Sheet
Section titled “SQL SELECT Statements and Basic Queries Cheat Sheet”1. Quick Overview
Section titled “1. Quick Overview”The SELECT statement is the foundation of SQL queries. It’s used to retrieve data from one or more tables in a database. It allows you to specify which columns to retrieve, filter the rows based on conditions, and order the results. It’s the most frequently used SQL command.
2. Syntax
Section titled “2. Syntax”SELECT column1, column2, ...FROM table_nameWHERE condition; -- Optional: Filters rowsORDER BY column1 ASC/DESC; -- Optional: Sorts the result setLIMIT number; -- Optional: Limits the number of rows returnedSELECT: Specifies the columns to retrieve. Use*to select all columns.FROM: Specifies the table(s) to retrieve data from.WHERE: Filters the rows based on a specified condition.ORDER BY: Sorts the result set based on one or more columns.ASCfor ascending (default),DESCfor descending.LIMIT: Limits the number of rows returned.
3. Common Use Cases
Section titled “3. Common Use Cases”- Retrieving all data from a table:
SELECT * FROM table_name; - Retrieving specific columns:
SELECT column1, column2 FROM table_name; - Filtering data based on a condition:
SELECT * FROM table_name WHERE column1 = 'value'; - Sorting data:
SELECT * FROM table_name ORDER BY column2 DESC; - Retrieving a limited number of rows:
SELECT * FROM table_name LIMIT 10; - Searching for partial string matches:
SELECT * FROM table_name WHERE column1 LIKE '%keyword%'; - Retrieving distinct values:
SELECT DISTINCT column1 FROM table_name;
4. Best Practices
Section titled “4. Best Practices”- Specify Columns: Avoid using
SELECT *in production. Explicitly list the columns you need. This improves performance and reduces network traffic, especially with wide tables. - Use Indexes: Ensure that columns used in
WHEREclauses are indexed. Indexes significantly speed up query execution. - Limit Results: Use
LIMITto prevent retrieving unnecessary data, especially when exploring data. - Write Efficient WHERE Clauses: Use the most selective conditions first in the
WHEREclause. - Avoid
ORwith indexed columns: UsingORcan negate index usage. Consider usingUNION ALLor rewriting the query. - Test your queries: Always test your queries on a development or staging environment before deploying to production. Use
EXPLAINto analyze query plans and identify potential bottlenecks.
5. Examples
Section titled “5. Examples”Let’s assume we have a table called employees with the following structure and data:
CREATE TABLE employees ( id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), department VARCHAR(50), salary DECIMAL(10, 2), hire_date DATE);
INSERT INTO employees (id, first_name, last_name, department, salary, hire_date) VALUES(1, 'John', 'Doe', 'Sales', 60000.00, '2022-01-15'),(2, 'Jane', 'Smith', 'Marketing', 75000.00, '2021-05-20'),(3, 'Robert', 'Jones', 'Sales', 62000.00, '2022-03-10'),(4, 'Emily', 'Brown', 'IT', 90000.00, '2020-11-01'),(5, 'Michael', 'Davis', 'HR', 65000.00, '2023-02-28'),(6, 'Jessica', 'Wilson', 'IT', 95000.00, '2021-08-15');Example 1: Select all employees
SELECT * FROM employees;Output: All rows and columns from the employees table.
Example 2: Select first name, last name, and salary
SELECT first_name, last_name, salary FROM employees;Output:
| first_name | last_name | salary |
|---|---|---|
| John | Doe | 60000.00 |
| Jane | Smith | 75000.00 |
| Robert | Jones | 62000.00 |
| Emily | Brown | 90000.00 |
| Michael | Davis | 65000.00 |
| Jessica | Wilson | 95000.00 |
Example 3: Select employees in the IT department
SELECT * FROM employees WHERE department = 'IT';Output:
| id | first_name | last_name | department | salary | hire_date |
|---|---|---|---|---|---|
| 4 | Emily | Brown | IT | 90000.00 | 2020-11-01 |
| 6 | Jessica | Wilson | IT | 95000.00 | 2021-08-15 |
Example 4: Select employees with salary greater than 70000, ordered by salary in descending order
SELECT * FROM employees WHERE salary > 70000 ORDER BY salary DESC;Output:
| id | first_name | last_name | department | salary | hire_date |
|---|---|---|---|---|---|
| 6 | Jessica | Wilson | IT | 95000.00 | 2021-08-15 |
| 4 | Emily | Brown | IT | 90000.00 | 2020-11-01 |
| 2 | Jane | Smith | Marketing | 75000.00 | 2021-05-20 |
Example 5: Select the top 3 highest-paid employees
SELECT * FROM employees ORDER BY salary DESC LIMIT 3;Output:
| id | first_name | last_name | department | salary | hire_date |
|---|---|---|---|---|---|
| 6 | Jessica | Wilson | IT | 95000.00 | 2021-08-15 |
| 4 | Emily | Brown | IT | 90000.00 | 2020-11-01 |
| 2 | Jane | Smith | Marketing | 75000.00 | 2021-05-20 |
Example 6: Select employees whose last name starts with ‘S’
SELECT * FROM employees WHERE last_name LIKE 'S%';Output:
| id | first_name | last_name | department | salary | hire_date |
|---|---|---|---|---|---|
| 2 | Jane | Smith | Marketing | 75000.00 | 2021-05-20 |
Example 7: Select distinct departments
SELECT DISTINCT department FROM employees;Output:
| department |
|---|
| Sales |
| Marketing |
| IT |
| HR |
6. Common Pitfalls
Section titled “6. Common Pitfalls”- Forgetting the
WHEREclause: This can lead to retrieving the entire table, which can be slow and resource-intensive. - Incorrect
WHEREclause syntax: Using incorrect operators or comparing incompatible data types can cause errors or unexpected results. - Case sensitivity: In some databases, string comparisons are case-sensitive. Use functions like
LOWER()orUPPER()to normalize the data before comparison. - SQL Injection: Never directly embed user input into SQL queries. Use parameterized queries or prepared statements to prevent SQL injection vulnerabilities. This is a critical security consideration.
- Performance issues with large datasets: Without proper indexing and query optimization,
SELECTstatements can become very slow on large tables. - Null values: Be mindful of
NULLvalues when usingWHEREclauses. UseIS NULLorIS NOT NULLinstead of=or<>to check for null values.
7. Database Variations
Section titled “7. Database Variations”While the core syntax of SELECT statements is generally consistent across different database systems, there are some variations:
- LIMIT:
- MySQL/PostgreSQL:
LIMIT number - SQL Server:
SELECT TOP number ... - Oracle: Requires a subquery or
ROWNUM <= number
- MySQL/PostgreSQL:
- String Concatenation:
- MySQL:
CONCAT(string1, string2) - PostgreSQL:
string1 || string2 - SQL Server:
string1 + string2 - Oracle:
string1 || string2
- MySQL:
- Date Functions: Date functions vary significantly across databases. Consult the documentation for your specific database system.
- Case Sensitivity: The default case sensitivity of string comparisons varies. MySQL is generally case-insensitive by default, while PostgreSQL and SQL Server are case-sensitive.
- Handling
NULLvalues: The syntax for handlingNULLvalues (e.g.,IS NULL,IS NOT NULL,COALESCE) is generally consistent, but the behavior of certain functions may differ.
Example: LIMIT variations
MySQL/PostgreSQL:
SELECT * FROM employees LIMIT 5;SQL Server:
SELECT TOP 5 * FROM employees;Oracle:
SELECT * FROM (SELECT * FROM employees) WHERE ROWNUM <= 5;This cheat sheet provides a starting point for understanding and using SELECT statements in SQL. Always refer to the documentation for your specific database system for the most accurate and up-to-date information. Remember to prioritize security and performance in your SQL queries.