SQL Selecting Particular Rows

Syntax:

                                  
                                    SELECT * FROM table_name WHERE condition;
                                  
                                

Replace table_name with the name of the table, and condition with the criteria that the rows must meet.


Example:

Assuming you have a table named employees:

                                  
                                    CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    department VARCHAR(50),
    salary DECIMAL(10, 2)
);

INSERT INTO employees VALUES
    (1, 'John', 'Doe', 'HR', 50000.00),
    (2, 'Jane', 'Smith', 'IT', 60000.00),
    (3, 'Bob', 'Johnson', 'Finance', 55000.00);
                                  
                                

To select only the employees from the HR department:

                                
                                    SELECT * FROM employees WHERE department = 'HR';
                                
                              

This query will return:

Employee ID First Name Last Name Department Salary
1 John Doe HR 50000.0

Multiple Conditions:

You can use logical operators such as AND and OR to combine multiple conditions:

                                  
                                    SELECT * FROM employees WHERE department = 'IT' AND salary > 55000.00;
                                  
                                

This query selects employees from the IT department with a salary greater than $55,000.

Comparison Operators:

You can use various comparison operators, including =, <, >, <=, >=, and <> (not equal), to define conditions.

                                  
                                    SELECT * FROM employees WHERE salary > 55000.00;
                                  
                                

This query selects employees with a salary greater than $55,000.


Pattern Matching:

You can use the LIKE operator for pattern matching:

                                  
                                    SELECT * FROM employees WHERE first_name LIKE 'J%';
                                  
                                

This query selects employees whose first name starts with 'J'.


Tips:

  • Use meaningful conditions to filter the rows you need.
  • Be careful with case sensitivity; SQL is case-insensitive by default in many databases.
  • Understand the data types of columns and use appropriate comparisons.