SQL Selecting Particular Columns

Syntax:

                                  
                                    SELECT column1, column2, ... FROM table_name;
                                  
                                

Replace column1, column2, ... with the names of the columns you want to select, and table_name with the name of the table.


Example:

Assuming you have a table called "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 first_name and last_name columns:

                                
                                    SELECT first_name, last_name FROM employees;
                                
                              

This query will return:

First Name Last Name
John Doe
Jane Smith
Bob Johnson

Aliasing Columns:

You can use aliases to rename columns in the result set:

                                  
                                    SELECT first_name AS "First Name", last_name AS "Last Name" FROM employees;
                                  
                                

This query will return:

First Name Last Name
John Doe
Jane Smith
Bob Johnson

Using DISTINCT:

If you want to retrieve distinct values from a column, you can use the DISTINCT keyword:

                                  
                                    SELECT DISTINCT department FROM employees;
                                  
                                

This query will return the distinct department values:

Department
HR
IT
Finance

Tips:

  • Select only the columns you need to improve query performance.
  • Use aliases for column names to provide more meaningful names in the result set.
  • Consider using DISTINCT to retrieve unique values from a column.