Skip to content

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”

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.

SELECT column1, column2, ...
FROM table_name
WHERE condition; -- Optional: Filters rows
ORDER BY column1 ASC/DESC; -- Optional: Sorts the result set
LIMIT number; -- Optional: Limits the number of rows returned
  • SELECT: 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. ASC for ascending (default), DESC for descending.
  • LIMIT: Limits the number of rows returned.
  • 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;
  • 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 WHERE clauses are indexed. Indexes significantly speed up query execution.
  • Limit Results: Use LIMIT to prevent retrieving unnecessary data, especially when exploring data.
  • Write Efficient WHERE Clauses: Use the most selective conditions first in the WHERE clause.
  • Avoid OR with indexed columns: Using OR can negate index usage. Consider using UNION ALL or rewriting the query.
  • Test your queries: Always test your queries on a development or staging environment before deploying to production. Use EXPLAIN to analyze query plans and identify potential bottlenecks.

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_namelast_namesalary
JohnDoe60000.00
JaneSmith75000.00
RobertJones62000.00
EmilyBrown90000.00
MichaelDavis65000.00
JessicaWilson95000.00

Example 3: Select employees in the IT department

SELECT * FROM employees WHERE department = 'IT';

Output:

idfirst_namelast_namedepartmentsalaryhire_date
4EmilyBrownIT90000.002020-11-01
6JessicaWilsonIT95000.002021-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:

idfirst_namelast_namedepartmentsalaryhire_date
6JessicaWilsonIT95000.002021-08-15
4EmilyBrownIT90000.002020-11-01
2JaneSmithMarketing75000.002021-05-20

Example 5: Select the top 3 highest-paid employees

SELECT * FROM employees ORDER BY salary DESC LIMIT 3;

Output:

idfirst_namelast_namedepartmentsalaryhire_date
6JessicaWilsonIT95000.002021-08-15
4EmilyBrownIT90000.002020-11-01
2JaneSmithMarketing75000.002021-05-20

Example 6: Select employees whose last name starts with ‘S’

SELECT * FROM employees WHERE last_name LIKE 'S%';

Output:

idfirst_namelast_namedepartmentsalaryhire_date
2JaneSmithMarketing75000.002021-05-20

Example 7: Select distinct departments

SELECT DISTINCT department FROM employees;

Output:

department
Sales
Marketing
IT
HR
  • Forgetting the WHERE clause: This can lead to retrieving the entire table, which can be slow and resource-intensive.
  • Incorrect WHERE clause 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() or UPPER() 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, SELECT statements can become very slow on large tables.
  • Null values: Be mindful of NULL values when using WHERE clauses. Use IS NULL or IS NOT NULL instead of = or <> to check for null values.

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
  • String Concatenation:
    • MySQL: CONCAT(string1, string2)
    • PostgreSQL: string1 || string2
    • SQL Server: string1 + string2
    • Oracle: string1 || string2
  • 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 NULL values: The syntax for handling NULL values (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.