Questions tagged [sql]

Structured Query Language (SQL) is a language for querying databases. Questions should include code examples, table structure, sample data, and a tag for the DBMS implementation (e.g. MySQL, PostgreSQL, Oracle, MS SQL Server, IBM DB2, etc.) being used. If your question relates solely to a specific DBMS (uses specific extensions/features), use that DBMS's tag instead. Answers to questions tagged with SQL should use ISO/IEC standard SQL.

How to write a good SQL question?

There are five ingredients to this recipe:

  1. Provide a clear textual explanation of the problem at hand.
  2. Provide proper sample data, as DDL (create table statement(s)) and DML (insert statement(s)). The sample data should be enough to demonstrate the problem, including edge cases. Usually, a few relevant rows are enough.
  3. Provide the expected output for the sample data you've posted.
  4. Show your attempts to solve the problem.
  5. Tag properly. In addition to , also provide the relevant rdbms tag (i.e. , , ), and the lowest version you need the solution for (i.e , ).
    Remember - different products use different dialects of SQL, and this can have a drastic effect on the answers you might get.
    Different versions of the same product have different built-in functions and capabilities that might also have a drastic effect on the answers.

Do not include images of data or code!

A link to an online SQL test environment such as SQL Fiddle, Rextester, or db<>fiddle might help, but it is not a replacement for having all the data inside the question.
For more information, Read Why should I provide an MCVE for what seems to me to be a very simple SQL query? and Help me write this query in SQL.

General Information

From Wikipedia:

SQL stands for Structured Query Language (informally) and is usually pronounced as Sequel.

SQL is based on relational algebra. In relational algebra, the word relation is synonymous with the word table. SQL is a standard to use relational algebra in a technical environment.

One subset of the SQL standard is DDL (Data Definition Language), used to create tables and constraints. These include:

  • CREATE
  • DROP
  • ALTER

Another subset is DML (Data Manipulation Language), which is used to modify and view data within the database:

  • SELECT
  • INSERT
  • UPDATE
  • DELETE

The final "standard" subset of commands is DCL (Data Control Language):

  • GRANT
  • REVOKE

Many database implementations require the use of SQL, and over the years, vendors have implemented dialects of SQL to provide more functionality and simplify it. Because of these deviations from the standard, SQL is fractured – syntax that works on one implementation does not necessarily work on another.

ISO/IEC (formerly ANSI) standards have been beneficial in resolving such situations, but adoption is selective. Queries conforming to these standards should be portable to other databases, though performance may vary.

Most DBMSs have additional languages for writing stored procedures. In Oracle, it is PL/SQL (Procedural Language/Structured Query Language). In PostgreSQL, it's PL/pgSQL (Procedural Language/PostgreSQL). Outside of stored procedures or functions, Oracle and PostgreSQL use SQL. Thus the tags and should only be used for problems directly related to writing stored procedures. Microsoft SQL Server uses the term T-SQL (Transact-SQL)() for both "plain" SQL (queries, DML, ..) and the language used for stored procedures.

List of Procedural Extensions

  • ANSI/ISO Standard: SQL/PSM (SQL / Persistent Stored Modules)
  • Interbase/Firebird: PSQL (Procedural SQL)
  • IBM DB2 SQL: PL/SQL (Procedural Language, implements SQL/PSM)
  • IBM Informix: SPL (Stored Procedural Language)
  • IBM Netezza: NZPLSQL (based on Postgres PL/pgSQL)
  • Microsoft/Sybase: T-SQL (Transact-SQL)
  • Mimer SQL: SQL/PSM (SQL / Persistent Stored Module, implements SQL/PSM)
  • MySQL: SQL/PSM (SQL / Persistent Stored Module, implements SQL/PSM)
  • MonetDB: SQL/PSM (SQL / Persistent Stored Module, implements SQL/PSM)
  • NuoDB: SSP (Starkey Stored Procedures)
  • Oracle: PL/SQL (Procedural Language / SQL, based on Ada)
  • PostgreSQL: PL/pgSQL (Procedural Language / PostgreSQL Structured Query Language, implements SQL/PSM)
  • Sybase: Watcom-SQL (SQL Anywhere Watcom-SQL Dialect)
  • Teradata: SPL (Stored Procedural Language)
  • SAP: SAP HANA (SQL Script)

Tagging Recommendation

This tag should be used for general SQL programming language questions, in addition to tags for specific products. For example, questions about Microsoft SQL Server should use the tag, while questions regarding MySQL should use the tag. SQL is the umbrella under which these products exist; tagging them by product (including version, e.g , , ) is the easiest way to know what functionality is available for the task at hand. It is very common for questions to omit this tag because query discussions on MySQL are more often stated as MySQL rather than SQL in general.

Please read this summary about the SQL standard (The 1992 one in this case, broadly implemented) and if you can, refer to the book itself.

More specific tags

When you are asking a question about SQL you can also add more specific tags. Here is the list of available tags:

Implementation specific tags

You can specify your question by adding the implementation you used as a tag.

Other Resources

Free SQL Programming Books

Free SQL/Database Online Courses

SQL/Database Online Tutorial

SQL reserved words overview

Online Testing

While you should always provide complete code examples (e.g., schema, data sample and expected result) in your question or answer, you can also isolate problematic code and reproduce it in an online environment:

  • SQL Fiddle MySQL 5.6, Oracle 11g R2, PostgreSQL 9.6, PostgreSQL 9.3, SQLite (WebSQL), SQLite (SQL.js), SQL Server 2017
  • Rextester: SQL Server, PostgreSQL, MySql, Oracle
  • Stack Exchange Data Explorer Microsoft SQL Server 2016
  • db-fiddle MySQL 5.5, 5.6, 5.7, 8.0 PostgreSQL 9.4, 9.5, 9.6, 10, 11, 12, 13 SQLite 3.26, 3.30
  • db <> fiddle Db2 Developer-C 11.1, Firebird 3.0, MariaDB 10.3, 10.4, 10.5, 10.6, MySQL 5.5, 5.6, 5.7, 8.0, Oracle 11g Release 2, Postgres 9.5, 9.6, 10, 11, 12,13, SQLite 3.27, SQL Server 2014, 2016 and 2017, 2017 (Linux), 2019, 2019 (Linux)
  • Hue demo Hive, Trino, MySQL, Flink SQL, Phoenix SQL, ksqlDB, Dask SQL, SparkSQL
665031 questions
96
votes
5 answers

How to properly set up a PDO connection

From time to time I see questions regarding connecting to database. Most answers is not the way I do it, or I might just not get the answers correctly. Anyway; I've never thought about it because the way I do it works for me. But here's a crazy…
ThomasK
  • 2,210
  • 3
  • 26
  • 35
96
votes
15 answers

Delete statement in SQL is very slow

I have statements like this that are timing out: DELETE FROM [table] WHERE [COL] IN ( '1', '2', '6', '12', '24', '7', '3', '5') I tried doing one at a time like this: DELETE FROM [table] WHERE [COL] IN ( '1' ) and so far it's at 22 minutes and…
Kyle
  • 32,731
  • 39
  • 134
  • 184
95
votes
2 answers

SQL query to make all data in a column UPPER CASE?

I need a SQL query to make all data in a column UPPER CASE? Any ideas?
MetaGuru
  • 42,847
  • 67
  • 188
  • 294
95
votes
8 answers

Best way to delete millions of rows by ID

I need to delete about 2 million rows from my PG database. I have a list of IDs that I need to delete. However, any way I try to do this is taking days. I tried putting them in a table and doing it in batches of 100. 4 days later, this is still…
Anthony Greco
  • 2,885
  • 4
  • 27
  • 39
95
votes
8 answers

Aggregate function in SQL WHERE-Clause

In a test at university there was a question; is it possible to use an aggregate function in the SQL WHERE clause. I always thought this isn't possible and I also can't find any example how it would be possible. But my answer was marked false and…
n3on
  • 2,051
  • 1
  • 16
  • 16
95
votes
7 answers

Can I reuse a calculated field in a SELECT query?

Is there a way to reuse a calculated field within a mysql statement. I get the error "unknown column total_sale" for: SELECT s.f1 + s.f2 as total_sale, s.f1 / total_sale as f1_percent FROM sales s or do I have to repeat the calculation,…
sdfor
  • 6,324
  • 13
  • 51
  • 61
95
votes
4 answers

PostgreSQL visual interface similar to phpMyAdmin?

I'd like to view and possibly edit tables for PostgreSQL visually like phpMyAdmin, where you can see the list of tables, and fields and individual rows for a table. Is there any utility that can do this? Forgive me if this is actually possible in…
Tristan
  • 1,561
  • 3
  • 18
  • 22
95
votes
3 answers

WHERE statement after a UNION in SQL?

How do I apply a WHERE statement after a UNION in SQL/MySQL?
einstein
  • 13,389
  • 27
  • 80
  • 110
95
votes
20 answers

Get month and year from a datetime in SQL Server 2005

I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is…
Malik Daud Ahmad Khokhar
  • 13,470
  • 24
  • 79
  • 81
95
votes
4 answers

ROW_NUMBER Without ORDER BY

I've to add row number in my existing query so that I can track how much data has been added into Redis. If my query failed so I can start from that row no which is updated in other table. Query to get data start after 1000 row from table SELECT *…
lucy
  • 4,136
  • 5
  • 30
  • 47
95
votes
5 answers

Get count of records affected by INSERT or UPDATE in PostgreSQL

My database driver for PostgreSQL 8/9 does not return a count of records affected when executing INSERT or UPDATE. PostgreSQL offers the non-standard syntax "RETURNING" which seems like a good workaround. But what might be the syntax? The example…
Un Homme
  • 1,021
  • 1
  • 8
  • 5
95
votes
9 answers

MySQL get row position in ORDER BY

With the following MySQL table: +-----------------------------+ + id INT UNSIGNED + + name VARCHAR(100) + +-----------------------------+ How can I select a single row AND its position amongst the other rows in the table, when…
leepowers
  • 37,828
  • 23
  • 98
  • 129
95
votes
6 answers

ORA-00972 identifier is too long alias column name

i have a query like : SELECT column as averyveryveryverylongalias (more than 30 characters) FROM Table_name it returns the error ORA-00972 identifier is too long , is there any tip to make it work without making the alias shorter?
mcha
  • 2,938
  • 4
  • 25
  • 34
95
votes
3 answers

Oracle SQL - DATE greater than statement

As the title says, I want to find a way to check which of my data sets are past 6 months from SYSDATE via query. SELECT * FROM OrderArchive WHERE OrderDate <= '31 Dec 2014'; I've tried the following but it returns an error saying my date format is…
user3521826
  • 979
  • 2
  • 7
  • 7
95
votes
1 answer

How to COALESCE for empty strings and NULL values?

I'm trying to make the fastest COALESCE() that accepts two or more arguments, and returns the first non-null AND non-empty ("") value. I'm using this: CREATE OR REPLACE FUNCTION coalescenonempty(VARIADIC in_ordered_actual varchar[]) RETURNS varchar…
MikeCW
  • 951
  • 1
  • 6
  • 3
1 2 3
99
100