Common SQL commands with example

By | January 20, 2024

Certainly! SQL (Structured Query Language) is used to interact with relational databases. Here are some common SQL commands with examples:

  1. SELECT:
  • The SELECT statement is used to query the database and retrieve data.
   SELECT column1, column2 FROM table_name WHERE condition;

Example:

   SELECT first_name, last_name FROM employees WHERE department = 'IT';
  1. INSERT:
  • The INSERT statement is used to insert new records into a table.
   INSERT INTO table_name (column1, column2, column3) VALUES (value1, value2, value3);

Example:

   INSERT INTO customers (first_name, last_name, email) VALUES ('John', 'Doe', 'john.doe@example.com');
  1. UPDATE:
  • The UPDATE statement is used to modify existing records in a table.
   UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;

Example:

   UPDATE products SET price = 25.99 WHERE product_id = 101;
  1. DELETE:
  • The DELETE statement is used to delete records from a table.
   DELETE FROM table_name WHERE condition;

Example:

   DELETE FROM customers WHERE last_purchase_date < '2022-01-01';
  1. CREATE TABLE:
  • The CREATE TABLE statement is used to create a new table.
   CREATE TABLE table_name (
       column1 datatype,
       column2 datatype,
       ...
   );

Example:

   CREATE TABLE employees (
       employee_id INT PRIMARY KEY,
       first_name VARCHAR(50),
       last_name VARCHAR(50),
       department VARCHAR(50)
   );
  1. ALTER TABLE:
  • The ALTER TABLE statement is used to modify an existing table (e.g., add or drop columns).
   ALTER TABLE table_name
   ADD column_name datatype;

   ALTER TABLE table_name
   DROP COLUMN column_name;

Example:

   ALTER TABLE employees
   ADD hire_date DATE;

   ALTER TABLE employees
   DROP COLUMN phone_number;
  1. DROP TABLE:
  • The DROP TABLE statement is used to delete an existing table and all its data.
   DROP TABLE table_name;

Example:

   DROP TABLE customers;
  1. JOIN:
  • The JOIN operation is used to combine rows from two or more tables based on a related column between them.
   SELECT * FROM table1
   INNER JOIN table2 ON table1.column_name = table2.column_name;

Example:

   SELECT orders.order_id, customers.first_name, customers.last_name
   FROM orders
   INNER JOIN customers ON orders.customer_id = customers.customer_id;

These are just a few examples of common SQL commands. SQL is a powerful language with many features, and its usage can vary depending on the specific database system you are working with (e.g., MySQL, PostgreSQL, SQLite, SQL Server).

Leave a Reply

Your email address will not be published. Required fields are marked *