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
102
votes
17 answers

SQL query: Delete all records from the table except latest N?

Is it possible to build a single mysql query (without variables) to remove all records from the table, except latest N (sorted by id desc)? Something like this, only it doesn't work :) delete from table order by id ASC limit ((select count(*) from…
serg
  • 109,619
  • 77
  • 317
  • 330
102
votes
11 answers

Drop all tables command

What is the command to drop all tables in SQLite? Similarly I'd like to drop all indexes.
alamodey
  • 14,320
  • 24
  • 86
  • 112
102
votes
1 answer

What does a (+) sign mean in an Oracle SQL WHERE clause?

Possible Duplicate: Oracle: What does (+) do in a WHERE clause? Consider the simplified SQL query below, in an Oracle database environment (although I'm not sure that it's Oracle-specific): SELECT t0.foo, t1.bar FROM FIRST_TABLE t0,…
Steve Perkins
  • 11,520
  • 19
  • 63
  • 95
102
votes
9 answers

How to create a Date in SQL Server given the Day, Month and Year as Integers

FOR Example if I have: DECLARE @Day int = 25 DECLARE @Month int = 10 DECLARE @Year int = 2016 I want to return 2016-10-25 As Date or datetime
MswatiLomnyama
  • 1,326
  • 2
  • 13
  • 19
102
votes
12 answers

How to run a SQL query on an Excel table?

I'm trying to create a sub-table from another table of all the last name fields sorted A-Z which have a phone number field that isn't null. I could do this pretty easy with SQL, but I have no clue how to go about running a SQL query within Excel.…
Vap0r
  • 2,588
  • 3
  • 22
  • 35
102
votes
7 answers

How do I write LINQ's .Skip(1000).Take(100) in pure SQL?

What is the SQL equivalent of the .Skip() method in LINQ? For example: I would like to select rows 1000-1100 from a specific database table. Is this possible with just SQL? Or do I need to select the entire table, then find the rows in memory? I'd…
Ray
  • 45,695
  • 27
  • 126
  • 169
102
votes
7 answers

SQL like search string starts with

Learning SQL. Have a simple table games with field title. I want to search based on title. If I have a game called Age of Empires III: Dynasties, and I use LIKE with parameter Age of Empires III: Dynasties, everything works fine, the search returns…
0xSina
  • 20,973
  • 34
  • 136
  • 253
102
votes
13 answers

Primary key/foreign Key naming convention

In our dev group we have a raging debate regarding the naming convention for Primary and Foreign Keys. There's basically two schools of thought in our group: 1: Primary Table (Employee) Primary Key is called ID Foreign table (Event) Foreign…
Jeremy
  • 44,950
  • 68
  • 206
  • 332
102
votes
9 answers

How to round down to nearest integer in MySQL?

How would I round down to the nearest integer in MySQL? Example: 12345.7344 rounds to 12345 mysql's round() function rounds up. I don't know how long the values nor the decimal places will be, could be 10 digits with 4 decimal places, could be 2…
d-_-b
  • 21,536
  • 40
  • 150
  • 256
102
votes
8 answers

Oracle SQL escape character (for a '&')

While attempting to execute SQL insert statements using Oracle SQL Developer I keep generating an "Enter substitution value" prompt: insert into agregadores_agregadores ( idagregador, nombre, url ) values ( 2, 'Netvibes', …
ian_scho
  • 5,906
  • 9
  • 35
  • 51
101
votes
13 answers

Equivalent of Oracle's RowID in SQL Server

What's the equivalent of Oracle's RowID in SQL Server?
None
101
votes
8 answers

Simple DateTime sql query

How do I query DateTime database field within a certain range? I am using SQL SERVER 2005 Error code below SELECT * FROM TABLENAME WHERE DateTime >= 12/04/2011 12:00:00 AM AND DateTime <= 25/05/2011 3:53:04 AM Note that I need to get rows…
ove
  • 3,092
  • 6
  • 34
  • 51
101
votes
2 answers

How can I have multiple common table expressions in a single SELECT statement?

I am in the process of simplifying a complicated select statement, so thought I would use common table expressions. Declaring a single cte works fine. WITH cte1 AS ( SELECT * from cdr.Location ) select * from cte1 Is it possible to…
Paul Rowland
  • 8,244
  • 12
  • 55
  • 76
101
votes
8 answers

Difference between Top and Limit Keyword in SQL

A quick Question. Suppose I have the following two queries: SELECT TOP 2 * FROM Persons; and SELECT * FROM Persons limit 2; I want to know the difference between the execution of the above 2 queries? Basically, I want to know when should I use the…
reggie
  • 13,313
  • 13
  • 41
  • 57
101
votes
6 answers

How do I create a parameterized SQL query? Why Should I?

I've heard that "everyone" is using parameterized SQL queries to protect against SQL injection attacks without having to vailidate every piece of user input. How do you do this? Do you get this automatically when using stored procedures? So my…
Jim Counts
  • 12,535
  • 9
  • 45
  • 63