DEV Community

Cover image for SQL Statement
Sthefany Spina
Sthefany Spina

Posted on

SQL Statement

Most of the actions you need to perform on a database are done with SQL statements.

  • CREATE DATABASE: statement is used to create a new SQL database.
CREATE DATABASE databasename;
Enter fullscreen mode Exit fullscreen mode
  • DROP: The DROP DATABASE statement is used to drop an existing SQL database.
DROP DATABASE databasename;
Enter fullscreen mode Exit fullscreen mode
  • BACKUP: The BACKUP DATABASE statement is used in SQL Server to create a full back up of an existing SQL database.
BACKUP DATABASE databasename
TO DISK = 'filepath';
Enter fullscreen mode Exit fullscreen mode
  • CREATE TABLE: The CREATE TABLE statement is used to create a new table in a database.
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);
Enter fullscreen mode Exit fullscreen mode
  • DROP TABLE: The DROP TABLE statement is used to drop an existing table in a database.
DROP TABLE table_name;
Enter fullscreen mode Exit fullscreen mode
  • ALTER TABLE: is used to add, delete, or modify columns in an existing table.Is also used to add and drop various constraints on an existing table.

  • ALTER TABLE - ADD Column: To add a column in a table, use the following syntax:

ALTER TABLE table_name
ADD column_name datatype;
Enter fullscreen mode Exit fullscreen mode
  • ALTER TABLE - DROP COLUMN: To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
Enter fullscreen mode Exit fullscreen mode
  • ALTER TABLE - RENAME COLUMN: To rename a column in a table, use the following syntax:
ALTER TABLE table_name
RENAME COLUMN old_name to new_name;
Enter fullscreen mode Exit fullscreen mode
  • ALTER TABLE - ALTER/MODIFY DATATYPE: To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
Enter fullscreen mode Exit fullscreen mode
  • NOT NULL: The NOT NULL constraint enforces a column to NOT accept NULL values.
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255) NOT NULL,
    Age int
);
Enter fullscreen mode Exit fullscreen mode
  • SQL NOT NULL on ALTER TABLE: To create a NOT NULL constraint on the "Age" column when the "Persons" table is already created, use the following SQL:
ALTER TABLE Persons
ALTER COLUMN Age int NOT NULL;
Enter fullscreen mode Exit fullscreen mode
  • UNIQUE: The UNIQUE constraint ensures that all values in a column are different.
CREATE TABLE Persons (
    ID int NOT NULL UNIQUE,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);
Enter fullscreen mode Exit fullscreen mode
  • SQL UNIQUE Constraint on ALTER TABLE: To create a UNIQUE constraint on the "ID" column when the table is already created, use the following SQL:
ALTER TABLE Persons
ADD UNIQUE (ID);
Enter fullscreen mode Exit fullscreen mode
  • PRIMER KEY: must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (ID)
);
Enter fullscreen mode Exit fullscreen mode
  • FOREIGN KEY: The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. Is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
Enter fullscreen mode Exit fullscreen mode
  • CHECK: The CHECK constraint is used to limit the value range that can be placed in a column.
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CHECK (Age>=18)
);
Enter fullscreen mode Exit fullscreen mode
  • DEFAULT: is used to set a default value for a column, will be added to all new records, if no other value is specified.
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    City varchar(255) DEFAULT 'Sandnes'
);
Enter fullscreen mode Exit fullscreen mode
  • INDEX: is used to create indexes in tables.
CREATE INDEX index_name
ON table_name (column1, column2, ...);
OR
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
Enter fullscreen mode Exit fullscreen mode
  • AUTO INCREMENT: allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
CREATE TABLE Persons (
    Personid int NOT NULL AUTO_INCREMENT,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (Personid)
);
Enter fullscreen mode Exit fullscreen mode
  • DATES: MySQL comes with the following data types for storing a date or a date/time value in the database:
  1. DATE - format YYYY-MM-DD
  2. DATETIME - format: YYYY-MM-DD HH:MI:SS
  3. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
  4. YEAR - format YYYY or YY
SELECT * FROM Orders WHERE OrderDate='2008-11-11'
Enter fullscreen mode Exit fullscreen mode
  • VIEWS: a view is a virtual table based on the result-set of an SQL statement. Contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • Updating a View: can be updated with the CREATE OR REPLACE VIEW statement.
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • Dropping a View: is deleted with the DROP VIEW statement.
DROP VIEW view_name;
Enter fullscreen mode Exit fullscreen mode
  • SELECT: is used to select data from a database.
SELECT CustomerName, City FROM Customers;
Enter fullscreen mode Exit fullscreen mode
  • SELECT DISTINCT: is used to return only distinct (different) values.
SELECT DISTINCT Country FROM Customers;
Enter fullscreen mode Exit fullscreen mode
  • WHERE: It is used to extract only those records that fulfill a specified condition.
SELECT column1, FROM table_name WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • ORDER BY: is used to sort the result-set in ascending or descending order.
SELECT * FROM Products
ORDER BY Price;
Enter fullscreen mode Exit fullscreen mode
  • AND: The AND operator is used to filter records based on more than one condition, like if you want to return all customers from Spain that starts with the letter 'G':
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
Enter fullscreen mode Exit fullscreen mode
  • OR: The OR operator is used to filter records based on more than one condition, like if you want to return all customers from Germany but also those from Spain:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
Enter fullscreen mode Exit fullscreen mode
  • NOT: The NOT operator is used in combination with other operators to give the opposite result, also called the negative result.
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Enter fullscreen mode Exit fullscreen mode
  • INSERT INTO: is used to insert new records in a table.
  • It is possible to write the INSERT INTO statement in two ways:
  • 1. Specify both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

Enter fullscreen mode Exit fullscreen mode
  • 2. If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query. However, make sure the order of the values is in the same order as the columns in the table. Here, the INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Enter fullscreen mode Exit fullscreen mode
  • NULL VALUES: It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

IS NULL Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Enter fullscreen mode Exit fullscreen mode

IS NOT NULL Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Enter fullscreen mode Exit fullscreen mode
  • UPDATE: is used to modify the existing records in a table.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • DELETE: is used to delete existing records in a table.
DELETE FROM table_name WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • MIN: returns the smallest value of the selected column.
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • MAX: returns the largest value of the selected column.
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • COUNT: returns the number of rows that matches a specified criterion.
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • SUM: returns the total sum of a numeric column.
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • AVG: returns the average value of a numeric column.
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • LIKE: The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.There are two wildcards often used in conjunction with the LIKE operator
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Enter fullscreen mode Exit fullscreen mode
  • IN: The IN operator allows you to specify multiple values in a WHERE clause.
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
Enter fullscreen mode Exit fullscreen mode
  • BETWEEN: The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Enter fullscreen mode Exit fullscreen mode
  • ALIASES (AS): SQL aliases are used to give a table, or a column in a table, a temporary name.
  • Aliases are often used to make column names more readable.
  • An alias only exists for the duration of that query.
  • An alias is created with the AS keyword.
SELECT column_name AS alias_name
FROM table_name;
SELECT column_name(s)
FROM table_name AS alias_name;
Enter fullscreen mode Exit fullscreen mode
  • INNER JOIN: The INNER JOIN keyword selects records that have matching values in both tables.
  • SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Enter fullscreen mode Exit fullscreen mode
  • LEFT JOIN: The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Enter fullscreen mode Exit fullscreen mode
  • RIGHT JOIN: The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records from the left table (table1). The result is 0 records from the left side, if there is no match.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Enter fullscreen mode Exit fullscreen mode
  • FULL JOIN: The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or right (table2) table records.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • SELF JOIN: A self join is a regular join, but the table is joined with itself.
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • UNION: The UNION operator is used to combine the result-set of two or more SELECT statements.
  • Every SELECT statement within UNION must have the same number of columns
  • The columns must also have similar data types
  • The columns in every SELECT statement must also be in the same order
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Enter fullscreen mode Exit fullscreen mode
  • UNION ALL: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Enter fullscreen mode Exit fullscreen mode
  • GROUP BY: The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Enter fullscreen mode Exit fullscreen mode
  • HAVING: The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Enter fullscreen mode Exit fullscreen mode
  • EXISTS: The EXISTS operator is used to test for the existence of any record in a subquery.
  • The EXISTS operator returns TRUE if the subquery returns one or more records.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Enter fullscreen mode Exit fullscreen mode
  • ANY: returns a boolean value as a result and returns TRUE if ANY of the subquery values meet the condition.
  • ANY means that the condition will be true if the operation is true for any of the values in the range.
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
  (SELECT column_name
  FROM table_name
  WHERE condition);
Enter fullscreen mode Exit fullscreen mode
  • ALL: The ALL operator:
  1. returns a boolean value as a result
  2. returns TRUE if ALL of the subquery values meet the condition
  3. is used with SELECT, WHERE and HAVING statements
  4. ALL means that the condition will be true only if the operation is true for all values in the range.
SELECT ALL column_name(s)
FROM table_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • SELECT INTO: The SELECT INTO statement copies data from one table into a new table.
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
Copy only some columns into a new table:
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • INSERT INTO SELECT: The INSERT INTO SELECT statement copies data from one table and inserts it into another table.
  • The INSERT INTO SELECT statement requires that the data types in source and target tables match.
  • Note: The existing records in the target table are unaffected.
  • Copy all columns from one table to another table:
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
Copy only some columns from one table into another table:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
  • CASE: The CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.
  • If there is no ELSE part and no conditions are true, it returns NULL.
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;
Enter fullscreen mode Exit fullscreen mode
  • STORED PROCEDURE: A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.
  • So if you have an SQL query that you write over and over again, save it as a stored procedure, and then just call it to execute it.
  • You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed.
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a Stored Procedure
EXEC procedure_name;
Enter fullscreen mode Exit fullscreen mode
  • COMMENTS: Single line comments start with --.
  • Any text between -- and the end of the line will be ignored (will not be executed).
-- Select all:
SELECT * FROM Customers;
Enter fullscreen mode Exit fullscreen mode

API Trace View

Struggling with slow API calls? πŸ‘€

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more β†’

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay