SQL queries with Examples
Structured Query Language (SQL) is the universal language of databases, allowing users to interact with data efficiently. Understanding the basic SQL commands is essential for anyone working with databases, whether you’re a beginner or an experienced professional. In this article, we’ll explore the fundamental SQL commands with practical examples to illustrate their usage and importance.
SQL SELECT Statement:
The SELECT statement is the cornerstone of SQL, used to retrieve data from one or more tables. It allows you to specify the columns you want to retrieve and apply filtering conditions to narrow down the result set.
Example:
Suppose we have a table named employees with columns employee_id, name, and department. To retrieve the names of all employees, the SQL query would be:
SELECT name FROM employees;
SQL INSERT INTO Statement:
The INSERT INTO statement is used to add new records to a table by specifying values for each column. It’s essential for populating tables with initial data or adding new entries as needed.
Example:
Let’s insert a new employee record into the employees table with columns employee_id, name, and department :
INSERT INTO employees (employee_id, name, department) VALUES (101, 'John Smith', 'IT');
SQL UPDATE Statement:
The UPDATE statement modifies existing records within a table based on specified conditions. It’s useful for making changes to data already stored in the database.
Example:
Suppose we want to update the department of employee with ID 101 to “Finance”:
UPDATE employees SET department = 'Finance' WHERE employee_id = 101;
SQL DELETE Statement:
The DELETE statement removes records from a table based on specified criteria. It’s used to delete unwanted or outdated data from the database.
Example:
Let’s delete an employee with ID 102 from the “employees” table:
DELETE FROM employees WHERE employee_id = 102;
SQL CREATE TABLE Statement:
The CREATE TABLE statement creates a new table with specified columns and data types. It’s the first step in designing the database schema.
Example:
To create a table named “customers” with columns for customer_id, name, and email:
CREATE TABLE customers ( customer_id INT PRIMARY KEY, name VARCHAR(100), email VARCHAR(255) );
Mastering the basic SQL commands lays the foundation for effectively working with databases. In this article, we’ve explored essential commands such as SELECT, INSERT INTO, UPDATE, DELETE, and CREATE TABLE, along with practical examples demonstrating their usage. By understanding and practicing these commands, you’ll be well-equipped to manipulate data and perform various operations within your database environment.