SQL CRUD Flashcards
How to create and use a database?
CREATE DATABASE database_name;
USE database_name;
How to create a table with 2 text fields?
CREATE TABLE table_sample ( name VARCHAR(10), type_sample VARCHAR(6) );
What data type sql have? ( 8 types )
VARCHAR(10) -> string
CHAR(1) -> character with fixed size
BLOB -> big text
INT -> integer number
DEC -> decimal number
DATE -> date
DATETIME -> date and time
TIME -> Time
How to show a table structure?
use DESC -> decribe
DESC table_name;
How to remove table?
DROP TABLE table_name;
How to add new value to the table?
INSERT INTO my_contacts
(last_name, first_name) VALUES (‘Андерсон’, ‘Джиллиан’);
How to create a table and don’t allow null value?
CREATE TABLE table_sample ( name VARCHAR(10) NOT NULL );
How to create a table with a default value?
CREATE TABLE table_sample ( name VARCHAR(10) default ‘aaa’ );
How to delete the rows from the table?
DELETE FROM Customers WHERE City = ‘Paris’;
How to update the row?
# with 1 field UPDATE Customers SET city = 'Berlin' WHERE city = 'London'; # with 2 fields for updation UPDATE Customers SET city='London', country='Germany' WHERE city = 'Berlin';
How to update the integer row using already existing values?
# price is already existing value UPDATE Products SET price = price + 1 WHERE categoryID = 1;
How to create a primary key for the table?
CREATE TABLE sample (sample_id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (sample_id));
# OR
CREATE TABLE sample (sample_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
How to add a new column?
ALTER TABLE sample ADD COLUMN name VARCHAR(10);
How to rename table?
ALTER TABLE sample RENAME TO samples;
How to rename column and change column type?
ALTER TABLE samples CHANGE COLUMN number number1 VARCHAR(10) DEFAULT ‘ddd’;
How to update only column type?
ALTER TABLE samples MODIFY COLUMN number1 INT ;
How to remove column?
ALTER TABLE samples DROP COLUMN name1;
How to update the column name with case statement?
UPDATE Products SET ProductName = CASE WHEN Price = 20 THEN 'Hello 20' WHEN Price = 30 THEN 'Hello 30' ELSE 'Nothing' END;
How to insert values from another table to your table?
INSERT INTO my_table (name) SELECT name FROM another_table;
How to create table with preinstalled values from another table?
CREATE TABLE profession (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(10)) AS SELECT name FROM samples;
How to save request and reuse it later?
# Create view CREATE VIEW my_sample_view AS SELECT * FROM Customers;
# then you can use this request SELECT * FROM my_sampe_view;
How to drop view?
DROP VIEW my_sample_view;