SQL Notes

Updated at
  • Data Query Language (DQL): SQL
  • Data Definition Language (DDL): CREATE, ALTER, and DROP
  • Data Control Language (DCL): GRANT, REVOKE
  • Data Manipulation Language (DML): SELECT, INSERT, UPDATE, DELETE

DML Operations

select <column_name, ...,  *>
from <table_name>
where <condition>
group by <column_name, ...>
having <condition>
order by <column_name | column_number, ...> [desc]
limit 10;

insert into <table_name> [(
	<column_name>, ...
)] values (
	<value_1>, ...
), ...;

update <table_name>
set <column_name> = <new_value>, ...
where <condition>;

delete from <table_name> where <condition>;
DescriptionSyntax
Execution orderfrom -> where ->group by -> having -> select -> order by -> limit
Uniquedistinct
Aggregation functionscount, sum, avg, min, max, len
Rounding resultsround(<column, value>, <n>)
Casting typescast(<column, value> as <type>)
Case conversionlower(), upper()
Conditional logiccase when <expression> then <value1> [...] [else <value2>] end as <name>
IN Operator<column, value> in (<values>)
Joining data<inner, left, right, full (outer), cross> join on <condition>
Combining rowsunion [all], intersect, except
Null operationsis [not] null
Like patternlike '[pattern] [%]'
Named subquerywith <name> as <query> [...]

DDL Operations

create table <table_name> (
	<column_name> <column_type> [primary key]
	,primary key (<column_name>, ...)
	,foreign key (<column_name>) references <table_name>(<column_name>)
);

alter table <table_name>
	add column <column_name> <column_type>;
DescriptionSyntax
SQLite column typestext, integer, real, numeric, blob
Creating a viewcreate view <name> as <query>
Removing an objectdrop <view, table> [if exists] <name>

Normalization

  1. First normal form: the values in each column of a table must be atomic
  2. Second normal form: every non candidate-key attribute must depend on the whole candidate key, not just part of it
  3. Third normal form: eliminating the transitive functional dependencies

SQLite

ShellCommand
Open databasesqlite3 <dbname.db>
Enable column headers.headers on
Enable column output.mode column
Help.help
Tables list.tables
Run in shell.shell <command>
Quit.quit
View the schema for a table.schema <table_name>
Python APICommand
Import moduleimport sqlite3
Connect to databaseconn = connect(path)
Close the connectionconn.close()
Create a cusrorcursor = conn.cursor()
Run the querycursor.execute(sql_query)
Return one rowcursor.fetchone()
Return n rowscursor.fetchmany(n)
Return the full resultscursor.fetchall()
No cursor shortcutconn.execute(sql_query).fetchall()

SQL with Python

#!conda install -yc conda-forge ipython-sql

%%capture
%load_ext sql
%sql sqlite:///sqlite_file.db

%%sql
<query>
from sqlalchemy import create_engine
engine = create_engine(f'mysql://{LOGIN}:{PASS}@{URL}/{DB}?charset=utf8')
with engine.begin() as conn:
    cursor = conn.execute('''
        select value
        from table
        ''')
df = pd.DataFrame(cursor.all())

SQL Server Snippets

select convert(varchar(8), getdate(), 112) as [DateKey]
select cast([YYYMMDD] as datetime) as [DateTime]